Powershell pitfalls

后端 未结 21 1363
梦谈多话
梦谈多话 2020-12-23 01:44

What Powershell pitfalls you have fall into? :-)

Mine are:

# -----------------------------------
function foo()
{
    @(\"text\")
}

# Expected 1, a         


        
21条回答
  •  一生所求
    2020-12-23 02:35

    $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).

提交回复
热议问题