I have part of a deploy PowerShell 2.0 script that copy a potential robots.dev.txt to robots.txt, if it doesn’t exist don’t do anything.
My original code was:
$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, in a difference with C#, even if $RobotFilesToOverWrite is null, code is entering in the foreach.
So I had to surround everything with:
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 that?
EDIT: This problem seems to be fixed in PowerShell 3.0
1 Answer