Author Posts

July 31, 2014 at 9:33 am

Hello everyone. I am new here and pretty new to PowerShell as well so please excuse me if this question seems basic.

I have a directory of files that need to be renamed. They all start with a 3 number code and space another 3 number code another space and then some descriptive name that can also contain spaces. I will ultimately need to rename the file to change one or both of the numeric codes in the file names and leave the rest of the file name unchanged.

Example: "021 042 Example File.txt"

My original thought was to just read in the file name as a string and split it based on a space character but that introduced a problem where any spaces in the text description portion of the file name gets split out too so now I don't have a consistent number of string elements to peice back together again. Does anyone have a better way of doing this? I would like to keep it all native PowerShell commandlets if at all possible.

Your help would be greatly appreciated.

July 31, 2014 at 9:41 am

I'd use a regular expression for this, since your pattern is so straightforward. Something along these lines:

$folderPath = 'C:\Your\Folder'

Get-ChildItem -Path $folderPath -File |
ForEach-Object {
    $file = $_

    if ($file.Name -match '^(\d{3}) (\d{3}) (.*)')
    {
        $firstNumber = [int]$matches[1]
        $secondNumber = [int]$matches[2]
        $remainingFileName = $matches[3]

        # Do something with these three values, and call Rename-Item when you're ready.
    }
}

If you're not familiar with regular expressions or the -match operator, start out by reading the about_Regular_Expressions and about_Comparison_Operators help files.

July 31, 2014 at 11:55 am

Since it's just space delimited and not a complex pattern, you could also just use -split and -join:

PS C:\> $arrFile = "021 042 Example File.txt" -split " "

PS C:\> $arrFile
021
042
Example
File.txt

PS C:\> $arrFile[0] = 222

PS C:\> $arrFile -join " "
222 042 Example File.txt

July 31, 2014 at 3:36 pm

Thanks Dave & Rob. Regular expressions do definitely look very powerful. I will be reading up on them more in the near future for sure. Since what I needed for this purpose was really simple, Rob's suggestion works the best for me and was the least re-work from what I had written to that point. Now on to the remainder of the code.

Thanks again guys.