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 :-)
Related problems
- Multiline regex to match config block
- Pipe complete array-objects instead of array items one at a time?
- What is Truthy and Falsy? How is it different from True and False?
- How do I pass multiple parameters into a function in PowerShell?
- Unexpected ConvertTo-Json results? Answer: it has a default -Depth of 2
- Should $null be on the left side of the equality comparison? (-eq with arrays)
- Why should I avoid using the increase assignment operator (+=) to create a collection
- Not all properties displayed