2012-12-07 41 views
4

我有一個部署的PowerShell 2.0腳本,一個潛在的robots.dev.txt複製到的robots.txt,如果它不存在,沒有做任何事情的一部分。是否有更好的方法來檢查,如果一個集合在PowerShell中的foreach之前是空的?

我原來的代碼是:

$RobotFilesToOverWrite= Get-ChildItem -Path $tempExtractionDirectory -Recurse -Include "robots.$Environment.txt" 
    foreach($file in $RobotFilesToOverWrite) 
    { 
     $origin=$file 
     $destination=$file -replace ".$Environment.","." 

     #Copy-Item $origin $destination 
    } 

但是,在C#中的差異,即使$ RobotFilesToOverWrite爲null,代碼在foreach進入。

所以我不得不與周圍的一切:

if($RobotFilesToOverWrite) 
{ 
    ... 
} 

這是最後的代碼:

$RobotFilesToOverWrite= Get-ChildItem -Path $tempExtractionDirectory -Recurse -Include "robots.$Environment.txt" 
if($RobotFilesToOverWrite) 
{ 
    foreach($file in $RobotFilesToOverWrite) 
    { 
     $origin=$file 
     $destination=$file -replace ".$Environment.","." 

     #Copy-Item $origin $destination 
    } 
} 

我想知道是否有更好的方式來實現這一目標?

編輯:這個問題似乎是固定在PowerShell中3.0

回答

8
# one way is using @(), it ensures an array always, i.e. empty instead of null 
$RobotFilesToOverWrite = @(Get-ChildItem -Path $tempExtractionDirectory -Recurse -Include "robots.$Environment.txt") 
foreach($file in $RobotFilesToOverWrite) 
{ 
    ... 
} 

# another way (if possible) is not to use an intermediate variable 
foreach($file in Get-ChildItem -Path $tempExtractionDirectory -Recurse -Include "robots.$Environment.txt") 
{ 
    ... 
} 
+0

測試的foreach()與該@()數組強制和工作方式類似於OP請求。 – SpellingD

+0

測試了...這兩個解決方案工作:) –

5

引自http://blogs.msdn.com/b/powershell/archive/2012/06/14/new-v3-language-features.aspx

foreach語句在$空

在PowerShell不重複V2.0,人們經常感到驚訝:

PS>的foreach($ I $中的NULL){ '來到這裏'} 來到這裏

這種情況經常出現在當一個cmdlet不返回任何對象。在PowerShell V3.0中,您不需要添加if語句以避免遍歷$ null。我們爲你照顧。

+6

我提交了這種語言的變化解析早在2007年6月,花了一段時間,但他們最終承認其作爲不良行爲(這本身花了一段時間),然後固定它的bug 。 :-) https://connect.microsoft.com/PowerShell/feedback/details/281908/foreach-should-not-execute-the-loop-body-for-a-scalar-value-of-null –

+0

非常好的錯誤充滿各種信息的言論;)帽子! –

+0

+1:很好的信息。我正在編輯我的問題以澄清它是** PowerShell v2.0 ** –

相關問題