Home > OS >  Regex, PowerShell, How can I get this to show up in PowerShell?
Regex, PowerShell, How can I get this to show up in PowerShell?

Time:03-03

In using the following PowerShell Script with Regex.

THE PROBLEM: I don't get any data returned for the Filename.

CURRENT RESULTS IN POWERSHELL:

enter image description here

EXPECTED RESULTS IN POWERSHELL:

enter image description here

This Regex Demo is doing what I would think it should be doing in Regex. (Originating from this question.)

POWERSHELL SCRIPT:

$InStuff = @('111111_SMITH, JIM_END TLD 6-01-20 THR LEWISHS.pdf','222222_JONES, MIKE_G URS TO 7.25 2-28-19 SA COOPSHS.pdf')


switch -Regex ($instuff) {
    '^(^.{0,6})*|(?!.*_).*(?=\.)'{     
        [pscustomobject]@{
            EmployeeID         = $matches.1
            FileName             = $matches.2            
        }
    }
}

QUESTION: What do I need to change to get the filename to show up in the PowerShell results?

CodePudding user response:

Seems like a simple .Split() can achieve what you're looking for. The method will split the string into 3 tokens which then get assigned to $a for the EmployeeID, $null for the User (we use $null here to simply ignore this token since you have already stated it was not of interest) and $b for the FileName. In PowerShell, this is known as multiple assignment.

To remove the extension from the $b token, as requested in your comment, regex is also not needed, you can use Path.GetFileNameWithoutExtension Method from System.IO.

$InStuff = @(
    '111111_SMITH, JIM_END TLD 6-01-20 THR LEWISHS.pdf'
    '222222_JONES, MIKE_G URS TO 7.25 2-28-19 SA COOPSHS.pdf'
)

foreach($i in $InStuff) {
    $a, $null, $b = $i.Split('_')
    [pscustomobject]@{
        EmployeeID = $a
        FileName   = [System.IO.Path]::GetFileNameWithoutExtension($b)
    }
}

Which results in:

EmployeeID FileName
---------- --------
111111     END TLD 6-01-20 THR LEWISHS
222222     G URS TO 7.25 2-28-19 SA COOPSHS
  • Related