【问题标题】:StreamWriter in Powershell Outputs Blank FilePowershell中的StreamWriter输出空白文件
【发布时间】:2014-03-21 23:52:12
【问题描述】:

代码如下:

$outputPath = "c:\Output"
$scopePath = "$($outputpath)\scopes.csv"
$clientsPath = "$($outputpath)\clients.csv"
$scopeStream = New-Object System.IO.StreamWriter($scopePath)
$clientStream = New-Object System.IO.StreamWriter($clientsPath)
$scopeStream.WriteLine("Scope,ScopeName")
$clientStream.WriteLine("IP,MAC,Lease,Reservation,Hostname")
$scopeStream.Flush()
$clientStream.Flush()
...
$scopeStream.WriteLine("$($scope.Name),$($scope.Address)")
...
$clientStream.WriteLine("$($client.IP),$($client.MAC),$($client.Lease),$($client.Reservation)$($client.Hostname)")
...
$scopeStream.close()
$scopeStream.dispose()
$clientStream.close()
$clientStream.dispose()

如果文件不存在,则会创建这些文件,但不会向它们写入任何内容。完全空白的文件,我一生都无法弄清楚为什么。

【问题讨论】:

    标签: powershell file-io powershell-2.0 streamwriter


    【解决方案1】:

    我以前见过这种情况——通常是因为 StreamWriter 抛出异常。你会认为这会导致你的脚本出现异常,但我见过它抛出非终止异常的情况,所以你的脚本永远不会收到它。

    运行代码块后,尝试获取最后的异常详情:

    $Error[0].Exception | Format-List * -Force
    

    如果出现异常,它应该可以帮助您准确找出导致问题的原因。我的猜测是这是一个权限问题。

    【讨论】:

    • 我要到星期一才能检查这个,但肯定不会受伤。
    • 事实证明,之前的脚本运行在句柄可以关闭和处置之前已经终止,因此文件被锁定。所以我将 New-Object 包装在 try/catch 中。 catch 关闭并处理,然后对 new-object 执行第二次(嵌套)try/catch。如果失败,我只是抛出一个错误。
    • 太棒了!我很高兴你能够让它工作。
    猜你喜欢
    • 1970-01-01
    • 2013-04-03
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    相关资源
    最近更新 更多