2015-04-22 41 views
2

我有一個簡單的工作流程並行循環,但寫入結果時發生錯誤。因爲寫入輸出是並行的。我得到的錯誤:PowerShell ForEach使用並行文件

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 

    } 

} 

什麼想法?

回答

4

我建議寫出來的臨時文件的一部分。你可以做類似下面的代碼:

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命名的文本文件和您的輸出,他們都串聯成一個,然後除去所有的人都

0

根據變量創建test.txt文件名 - 那麼你將沒有衝突。

在過程結束時收集的所有個人文件,並創建一個文件,所有的結果 - 然後取出單個文件的清理」

0

您可以通過在年底使用緩衝區和輸出緩衝區的內容做一個簡單的形式:

workflow Get-ServerServices 
{ 
    $srvlst = Get-Content C:\TEMP\srvlst.txt 
    $out = @() 

    foreach -parallel ($srv in $srvlst) 
    { 
     $WORKFLOW:out += (Get-Service -ComputerName $srv) 

    } 

    Out-File c:\temp\test.txt -InputObject $out 

} 

看到technet「並行和順序聲明變量」獲取更多信息