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中得到修复
# 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)
引自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.我们会为您照顾.
| 归档时间: |
|
| 查看次数: |
3148 次 |
| 最近记录: |