ast*_*_zh 3 parallel-processing powershell foreach
我有一个带有并行循环的简单工作流,但是在写出结果时遇到了错误。因为写输出是并行的。我收到错误:
The process cannot access the file because it is being used by another process.
Run Code Online (Sandbox Code Playgroud)
这是我的脚本:
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
}
}
Run Code Online (Sandbox Code Playgroud)
任何的想法?
我建议写出临时文件。您可以执行类似以下代码的操作:
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
}
Run Code Online (Sandbox Code Playgroud)
基本上,您正在获取临时目录,附加一个新目录,在输出中添加一堆 GUID 命名的文本文件,将它们全部连接成一个,然后将它们全部删除