2

So I have hundreds of files in a folder:

The files are always First_Last (MMM yyyy):

C:\Test\Bob_Johnson (May 2017).pdf
C:\Test\James_Smith (Apr 2017).pdf

They get moved to individual folders based on their filenames (I think I know how to move the files). The folders are named Last, First 00-0000 where the zeros are the case number.

The following script will remove the (MMM yyyy) from the filenames:

Get-ChildItem -Path C:\Test | ?{ ($_.PsIsContainer)} | %{
    $File = ($_.name.substring(0,$_.basename.length-11))
    Write-Host $File
}

Output:

Bob_Johnson
James_Smith

Great. But it needs to be "Last, First".

Get-ChildItem -Path C:\Test | ?{!($_.PsIsContainer)} | %{
    $File = ($_.BaseName -split '_')[1] + ", " + ($_.BaseName -split '_')[0]
    Write-Host $File
}

Output:

Johnson (May 2017), Bob
Smith (Apr 2017), James

So here's my question: how do I combine the substring and the split so that it trims the last 11 characters and rearranges the first and last names with a ", " in between?

Desired Output:

Johnson, Bob
Smith, James
0

2 Answers 2

2

It's not the most elegant solution, but I think you could just do this:

Get-ChildItem -Path C:\Test | ?{ ($_.PsIsContainer)} | %{
    $File = ($_.name.substring(0,$_.basename.length-11))
    $File = ($File -split '_')[1] + ", " + ($File -split '_')[0]
    Write-Host $File
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. So simple, yet so elusive. I tried so many variations including one similar to this. But I think instead of the 2nd variable declaration where it splits, I put "$_.BaseName -split" instead of "$File -split". This seems to work perfectly with my code and everything is getting moved to its correct folder. Thank you!
0

Here a solution using regex:

Get-ChildItem -Path C:\Test | ?{!($_.PsIsContainer)} | %{
    $regexMatch = [regex]::Match($_.BaseName, '(\w+)_(\w+)\s+\((\w+)\s+(\d+)')
    $File = '{0}, {1} {2}-{3}' -f $regexMatch.Groups[1].Value, $regexMatch.Groups[2].Value, $regexMatch.Groups[3].Value, $regexMatch.Groups[4].Value
    Write-Host $File
}

Output:

Bob, Johnson May-2017

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.