#PSTip Inserting characters at a specified string index position

How do you turn ‘20130701’ to ‘2013-07-01’?

There are many ways to tackle this, breaking it into pieces (substring) and joining it back with a dash, use some regex fu to manipulate it, parse it as a DateTime and format it and so on. Here’s another way that uses the String.Insert method.

The Insert() method takes two arguments–the index position of the insertion and the string to insert.

PS> "".Insert.OverloadDefinitions
string Insert(int startIndex, string value)

In our example we need to add a dash after the year part which is the fourth character.

PS> $s = '20130701'
PS> $s = $s.Insert(4,'-')
PS> $s

Now we can add the second dash right after the month/day part (depending on your culture):

PS> $s = $s.Insert(7,'-')
PS> $s

Or we can insert the dashes in two consecutive method calls:

PS> '20130701'.Insert(4,'-').Insert(7,'-')
Filed in: Columns, Tips and Tricks Tags: , ,

One Response to "#PSTip Inserting characters at a specified string index position"

  1. maria rutgers says:

    Very neat, thank you!

    I used this to get file times in the form hh:mm:ss for a set of log files with names like this:

    Cut-down version of the command I used:
    Get-ChildItem ‘MyServer\MyShare\Myfolder\MyFilename_*.log’ |
    Select-Object Name, @{n=’Time’;ex={($_.Name.substring($_.Name.Length – 10, 6)).Insert(2,’:’).Insert(5,’:’) }}

Leave a Reply

Submit Comment

© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: