PowerShell ForEach - 正在使用的并行文件

标签 powershell foreach parallel-processing

我有一个带有并行循环的简单工作流程,但在写出结果时遇到错误。因为写输出是并行的。我收到错误:

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/

相关文章:

php - 尝试插入/更新具有多个值的两个不同表

parallel-processing - 添加并行到流导致 NullPointerException

r - 如何在R中使用循环和并行获得相同的结果?

sql - 我如何拥有在同一行上回显回声的powershell循环?

powershell - 如何在另一个 session (Powershell ISE 选项卡)中使用一个变量?

PowerShell 获取大(大)文件的行数

c# - 为什么我不能执行 foreach(DataTable.Rows 中的 var Item)?

powershell - 自定义资源 : Is it okay to reapply settings every time?

javascript - 如何修复异步 forEach 推送?

java - Spring 批量性能测试