Subscribe via Email

Subscribe via RSS/JSON


Recent Posts

Creative Commons Attribution 4.0 International License
© Rakhesh Sasidharan


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: