Extract the nth to nth characters of an string object

21,985

There are several ways to do this. One of the most straightforward, as PetSerAl suggested is with .Substring():

$_.name.Substring(35,4)

Another way is with square braces, as you tried to do, but it gives you an array of [char] objects, not a string. You can use -join and you can use a range to make that easier:

$_.name[35..38] -join ''

For what you're doing, matching a pattern, you could also use a regular expression with capturing groups:

if ($_.name -match '_(\d{4})_(\d{4})\.xml$') {
    if ($Matches[1] -eq $Matches[2]) {
        # ...
    }
}

This way can be very powerful, but you need to learn more about regex if you're not familiar. In this case it's looking for an underscore _ followed by 4 digits (0-9), followed by an underscore, and four more digits, followed by .xml at the end of the string. The digits are wrapped in parentheses so they are captured separately to be referenced later (in $Matches).

Share:
21,985
TOGEEK
Author by

TOGEEK

Updated on July 09, 2022

Comments

  • TOGEEK
    TOGEEK almost 2 years

    I have a filename and I wish to extract two portions of this and add into variables so I can compare if they are the same.

    $name = FILE_20161012_054146_Import_5785_1234.xml 
    

    So I want...

    $a = 5785
    $b = 1234
    
    if ($a = $b) {
      # do stuff
    }
    

    I have tried to extract the 36th up to the 39th character

    Select-Object {$_.Name[35,36,37,38]}
    

    but I get

    {5, 7, 8, 5}

    Have considered splitting but looks messy.