Jun 16, 2015

Quick conversion from PowerShell array to collection

powershell

In my previous post on accessing TeamCity REST API using PowerShell there is a small inconspicuous line that reads like this:

  $changeList = {@()}.Invoke()

I found this on the inter-webs somewhere and I’d love to give credit for it but I can’t remember where I found it.

If you are familiar with PowerShell you know that @() simply initializes a PowerShell array. The trouble here is this array is fixed sizes and you cannot add items to it after it has been created.

The curly braces create a block that is immediately invoked by calling the Invoke() method on it. From the MSDN documentation we can see this method returns a collection of PSObjects which means that we now have a collection we can add to. This is just a nice and quick way to initialize a collection we can add items to on the fly.