Powershell pitfalls

powershell

Solution

My personal favorite is

function foo() {
  param ( $param1, $param2 = $(throw "Need a second parameter"))
  ...
}

foo (1,2)

For those unfamiliar with powershell that line throws because instead of passing 2 parameters it actually creates an array and passes one parameter. You have to call it as follows

foo 1 2

Problem

What Powershell pitfalls you have fall into? :-) Mine are: ``` # ----------------------------------- function foo() { @("text") } # Expected 1, actually 4. (foo).length # ----------------------------------- if(@($null, $null)) { Write-Host "Expected to be here, and I am here." } if(@($null)) { Write-Host "Expected to be here, BUT NEVER EVER." } # ----------------------------------- function foo($a) { # I thought this is right. #if($a -eq $null) #{ # throw "You can't pass $null as argument." #} # But actually it should be: if($null -eq $a) { throw "You can't pass $null as argument." } } foo @($null, $null) # ----------------------------------- # There is try/catch, but no callstack reported. function foo() { bar } function bar() { throw "test" } # Expected: # At bar() line:XX # At foo() line:XX # # Actually some like this: # At bar() line:XX foo ``` Would like to know yours to walk them around :-)

Original source

Related problems