Subscribe via Email

Subscribe via RSS


Creative Commons Attribution 4.0 International License
© Rakhesh Sasidharan

Using comma to preserve arrays

I had mentioned earlier that when you pipe an array to the get-member cmdlet the array is unraveled.

While reading Bruce Payette’s excellent “Powershell in Action” book yesterday (and also coincidentally from an unrelated serverfault topic I was reading) I discovered that it’s possible to modify this behavior by prepending a , to the array. Like thus:

Notice it gives the type of the array as well as the various sub-types within it (strings and integers). Useful!

Removing the first four characters in an array in PowerShell

Looking at my site stats I saw someone had reached this blog via the above query. Here’s a quick one liner on how to do it:

Assuming an array of strings $array, do the following:

That’s all!

You can also do the following (probably more readable):

Warning: There are probably better/ more efficient ways to do this as I am just a beginner to PowerShell.

What I do is (a) for each element of the array (b) extract a sub-string starting from the 5th place (strings start from 0, hence SubString(4) stands for “extract everything from the 5th character”) and (c) put it back into the array. Rather than keep a counter I just use the IndexOf method to find the index of the element we are looking – this is required so I can replace the element at that index with the extracted text.

If you don’t care about putting the extracted text back into the array it’s even more straight-forward: