我有一个带有并行循环的简单工作流程,但在写出结果时遇到错误。因为写输出是并行的。我收到错误:
The process cannot access the file because it is being used by another process.
这是我的脚本:
workflow Get-ServerServices
{
$srvlst = Get-Content C:\TEMP\srvlst.txt
foreach -parallel ($srv in $srvlst)
{
Get-Service -PSComputerName $srv | Out-File c:\temp\test.txt -Append
}
}
有什么想法吗?
最佳答案
我建议写入临时文件。您可以执行类似以下代码的操作:
workflow Get-ServerServices
{
#Get the temp path of the context user
$TempPath = Join-Path -Path $([System.IO.Path]::GetTempPath()) -ChildPath "ServerServices"
New-Item -Path $TempPath -ItemType Directory # and create a new sub directory
$srvlst = Get-Content C:\TEMP\srvlst.txt
foreach -parallel ($srv in $srvlst)
{
$TempFileName = [System.Guid]::NewGuid().Guid + ".txt" #GUID.txt will ensure randomness
$FullTempFilePath = Join-Path -Path $TempPath -ChildPath $TempFileName
Get-Service -PSComputerName $srv | Out-File -Path $FullTempFilePath -Force #Write out to the random file
}
$TempFiles = Get-ChildItem -Path $TempPath
foreach ($TempFile in $TempFiles) {
Get-Content -Path $TempFile.FullName | Out-File C:\temp.txt -Append #concatenate all the files
}
Remove-Item -Path $TempPath -Force -Recurse #clean up
}
基本上,您正在获取临时目录,附加一个新目录,在您的输出中添加一堆 GUID 命名的文本文件,将它们全部连接成一个,然后将它们全部删除
关于PowerShell ForEach - 正在使用的并行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29797961/