Is there a better way to check if a collection is empty before foreach in PowerShell?

I have a deployment part of a PowerShell 2.0 script that copies a potential robots.dev.txt file to a robots.txt file, if it does not exist, do nothing.

My source code:

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

But, unlike C #, even if $ RobotFilesToOverWrite is null, the code is entered in foreach.

So I had to surround everything:

 if($RobotFilesToOverWrite) { ... } 

This is the final code:

 $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 } } 

I was wondering if there is a better way to achieve this?

EDIT: This issue seems to be fixed in PowerShell 3.0

+4
source share
2 answers
 # one way is using @(), it ensures an array always, ie 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") { ... } 
+8
source

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

ForEach statement does not iterate over $ null

In PowerShell V2.0, people often wondered:

PS> foreach ($ I'm in $ null) {'got here'} got here

This situation often occurs when the cmdlet does not return any objects. In PowerShell V3.0, you do not need to add an if statement to avoid iterating over $ null. We will take care of this for you.

+5
source

All Articles