在PowerShell中使用foreach之前,有没有更好的方法来检查集合是否为空?

Osc*_*ley 5 powershell foreach powershell-2.0

我有一部分部署PowerShell 2.0脚本,可以将潜在的robots.dev.txt复制到robots.txt,如果它不存在则不执行任何操作.

我原来的代码是:

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

        #Copy-Item $origin $destination
    }
Run Code Online (Sandbox Code Playgroud)

但是,与C#不同的是,即使$ RobotFilesToOverWrite为null,代码也会在foreach中输入.

所以我不得不围绕一切:

if($RobotFilesToOverWrite)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

这是最终的代码:

$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
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更好的方法来实现这一目标?

编辑:这个问题似乎在PowerShell 3.0中得到修复

Rom*_*min 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")
{
    ...
}
Run Code Online (Sandbox Code Playgroud)


Loï*_*HEL 6

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

ForEach语句不会迭代$ null

在PowerShell V2.0中,人们常常惊讶于:

PS> foreach($ $ in $ null){'got here'}来到这里

当cmdlet不返回任何对象时,通常会出现这种情况.在PowerShell V3.0中,您不需要添加if语句以避免迭代$ null.我们会为您照顾.

  • 我提交了这个语言变化在2007年6月解决的错误.它花了一段时间,但他们最终承认它是不良行为(本身需要一段时间),然后修复它.:-) https://connect.microsoft.com/PowerShell/feedback/details/281908/foreach-should-not-execute-the-loop-body-for-a-scalar-value-of-null (6认同)