2016-06-17 53 views
3

最近我們開始研究需要很長時間才能完成的腳本。所以我們深入瞭解PowerShell工作流程。閱讀了一些文檔後,我忽略了基本知識。但是,我似乎無法找到爲foreach -parallel聲明中的每個單獨項目創建[PSCustomObject]的方法。Foreach-平行對象

某些代碼來解釋:

Workflow Test-Fruit { 

    foreach -parallel ($I in (0..1)) { 

     # Create a custom hashtable for this specific object 
     $Result = [Ordered]@{ 
      Name = $I 
      Taste = 'Good' 
      Price = 'Cheap' 
     } 

     Parallel { 
      Sequence { 
       # Add a custom entry to the hashtable 
       $Result += @{'Color' = 'Green'} 
      } 

      Sequence { 
       # Add a custom entry to the hashtable 
       $Result += @{'Fruit' = 'Kiwi'} 
      } 
     } 

     # Generate a PSCustomObject to work with later on 
     [PSCustomObject]$Result 
    } 
} 

Test-Fruit 

其中它出錯是從Sequence塊內增加一個值到$Result哈希表的一部分。嘗試以下情況下,也仍然失敗:

$WORKFLOW:Result += @{'Fruit' = 'Kiwi'} 

回答

1

好了在這裏你去,久經考驗:

Workflow Test-Fruit { 

    foreach -parallel ($I in (0..1)) { 

     # Create a custom hashtable for this specific object 
     $WORKFLOW:Result = [Ordered]@{ 
      Name = $I 
      Taste = 'Good' 
      Price = 'Cheap' 
     } 

     Parallel { 

      Sequence { 
       # Add a custom entry to the hashtable 
       $WORKFLOW:Result += @{'Color' = 'Green'} 
      } 

      Sequence { 
       # Add a custom entry to the hashtable 
       $WORKFLOW:Result += @{'Fruit' = 'Kiwi'} 
      } 


     } 

     # Generate a PSCustomObject to work with later on 
     [PSCustomObject]$WORKFLOW:Result 
    } 
} 

Test-Fruit 

您應該將其定義爲$ WORKFLOW:var並重復使用整個工作流訪問範圍。

+0

這是完全真棒!正是我所期待的。謝謝你,很好的回答! :) – DarkLite1

+0

很高興能幫到你! – Thom

+1

正在寫入$ WORKFLOW:並行操作的結果線程安全嗎?在foreach-parallel模塊運行內聯腳本的情況下,他們似乎都可以嘗試訪問這個變量來同時寫出結果。 –

0

您可以分配$ResultParallel塊的輸出,之後添加其他屬性:

$Result = Parallel { 
    Sequence { 
     # Add a custom entry to the hashtable 
     [Ordered]@{'Color' = 'Green'}      
    } 

    Sequence { 
     # Add a custom entry to the hashtable 
     [Ordered] @{'Fruit' = 'Kiwi'} 
    } 
} 

# Generate a PSCustomObject to work with later on 
$Result += [Ordered]@{ 
    Name = $I 
    Taste = 'Good' 
    Price = 'Cheap' 
} 

# Generate a PSCustomObject to work with later on 
[PSCustomObject]$Result 
+0

謝謝你的幫助馬丁。但我似乎無法通過這種方式正確轉換爲「PCCustomObject」。它仍然輸出爲'HashTable' – DarkLite1

+0

你是對的,它可能是因爲哈希表的類型是'Deserialized.System.Collections.Specialized.OrderedDictionary'。但不知道如何解決這個... –