Minor gripes
A number of little things bother me about PowerShell, and I’d just like to outline them here.
Adding to arrays
According to get-help about_array :
“You can append an element to an existing array by using the += operator. When the operator is used on the array itself, it appends the value.”
This isn’t completely true. If the right hand side of the += is also an array, then the elements of that array are added, not the array itself. This makes it very difficult to build up an array of arrays:
$a = @() # start with an empty array $a += 1,2 # this doesn't work - it adds 1 and 2
so you need to do:
$a += 1 $a[-1] = 1,2
I think that either a) the documentation be updated to make this clear or b) fix += so it really does add the RHS as a new element. Otherwise, I’m going to have to use something like this, which is a bit ugly (but actually much more efficient):
$a = new-object collections.ArrayList $a.add( @(1,2) )
Update: I’ve since discovered you can do this instead with the unary comma operator followed by a parenthesised list. The syntax is a bit weird (and hard to guess) but I believe the next version of PowerShell will get better documentation in this area.
$a=@() $a += ,(1,2)
Integer division
Many languages support integer division, yielding an integer result. Many languages compliment this by offering a modulus division aswell. This is great, because one often has an index into a pseudo-2d array and you want to get the row and column values. Notionally:
width=10 offset = 17 row = offset DIV width column = offset MOD width
This should yield row=1, column=7
In PowerShell:
[int]$width = 10 [int]$offset = 17 [int]$row = $offset / $width [int]$column = $offset % $width
This yields a row of 2. The division, even though both sides are [int] is done using floating point and rounded up.
To work around it, we have to do this:
[int]$row = [Math]::Floor($offset/$width)
Not sure of a sensible fix for this… maybe a new operator like -idiv ? or the pythonesque //