Powershell中的StreamWriter输出空白文件

时间:2014-02-20 19:44:34

标签: powershell file-io powershell-v2.0 streamwriter

以下是代码:

$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()

如果文件不存在,则会创建文件,但不会写入任何文件。完全空白的文件,我无法弄清楚为什么,为了我的生活。

1 个答案:

答案 0 :(得分:1)

我以前见过这个 - 通常是因为StreamWriter抛出异常。你认为这会在你的脚本中引起异常,但是我已经看到它抛出非终止异常的情况,所以你的脚本不会收到它。

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

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

如果有异常,它应该可以帮助您弄清楚导致问题的确切原因。我的猜测是这是一个权限问题。