PowerShell ForEach-正在使用的并行文件 [英] PowerShell ForEach -parallel file in use
本文介绍了PowerShell ForEach-正在使用的并行文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有并行循环的简单工作流程,但是在写出结果时遇到错误.因为写输出是并行的.我收到错误消息:
I have a simple workflow with a parallel loop but i run into an error when writing out the result. Because the write-output is parallel. I get the error:
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
}
}
有什么主意吗?
推荐答案
我建议写出临时文件.您可以执行以下代码:
I would suggest writing out to temporary files. You could do something like the below code:
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,将它们全部连接成一个,然后将其全部删除
Basically you are getting the temp dir, appending a new directory, adding a bunch of GUID named text files with your output, concatenating them all into one, and then removing all of them
这篇关于PowerShell ForEach-正在使用的并行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文