[英]Powershell Out-file not working
I have a powershell script which gathers some file information on some remote servers. 我有一个Powershell脚本,该脚本在一些远程服务器上收集一些文件信息。 When writing to the console, I see the results just fine, but they don't seem to be getting written into the specified out-file:
当写入控制台时,我看到结果很好,但是它们似乎没有写入指定的输出文件中:
out-file -filepath $filepath -inputobject $date -force -encoding ASCII -width 50
ForEach($server in $serverLists)
{
$result += $server
$result += $break
ForEach($filePath in $filePaths)
{
$result += $filePath
$result += $break
$command = "forfiles /P " + $filePath + " /S /D -1 > C:\temp\result.txt"
$cmd = "cmd /c $command"
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $server
sleep 2
$result += Get-Content \\$server\C$\temp\result.txt
$result += $break
$result += $break
write-host $result
#out-file -filepath $filepath -Append -inputobject $result -encoding ASCII -width 200
Remove-Item \\$server\C$\temp\result.txt
}
$result += $break
}
out-file -filepath $filepath -Append -inputobject $result -encoding ASCII -width 200
You use same variable $filepath
in two places: as loop variable for foreach
loop and outside of loop. 您可以在两个地方使用相同的变量
$filepath
:作为foreach
循环的循环变量和循环外的循环变量。 foreach
loop does not restore value of loop variable after loop ends. 循环结束后,
foreach
循环不会恢复循环变量的值。 So, right after loop ends loop variable will have last value of loop or value where loop was interrupted by break
command. 因此,在循环结束后,循环变量将具有循环的最后一个值或由
break
命令中断循环的值。 If you does not want variable value to be overwritten by foreach
loop, then you should choose different name for loop variable. 如果您不希望变量值被
foreach
循环覆盖,则应为循环变量选择其他名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.