What Powershell pitfalls you have fall into? :-)
Mine are:
# -----------------------------------
function foo()
{
@(\"text\")
}
# Expected 1, a
$files = Get-ChildItem . -inc *.extdoesntexist
foreach ($file in $files) {
"$($file.Fullname.substring(2))"
}
Fails with:
You cannot call a method on a null-valued expression.
At line:3 char:25
+ $file.Fullname.substring <<<< (2)
Fix it like so:
$files = @(Get-ChildItem . -inc *.extdoesntexist)
foreach ($file in $files) {
"$($file.Fullname.substring(2))"
}
Bottom line is that the foreach statement will loop on a scalar value even if that scalar value is $null. When Get-ChildItem in the first example returns nothing, $files gets assinged $null. If you are expecting an array of items to be returned by a command but there is a chance it will only return 1 item or zero items, put @() around the command. Then you will always get an array - be it of 0, 1 or N items. Note: If the item is already an array putting @()
has no effect - it will still be the very same array (i.e. there is no extra array wrapper).