0

I am struggling to find a way to get only the first set of numbers in a file name in PowerShell. The file names can be similar to the ones below but I only want to get the first string of numbers and nothing else.

Example file names:

123456 (12).csv
123456abc.csv
123456(Copy 1).csv
123456 (Copy 1).csv

What I am currently attempting:

$test = "123456 (12).csv" 
$POPieces = $test -match "^[0-9\s]+$" 
Write-Host $POPieces

What I'd expect from above:

123456
4
  • What have you tried so far? Show some code for us to demonstrate an alternative/better fit solution or debug yours for you. Commented Oct 9, 2017 at 12:56
  • I have been overwriting most of what I tried with the next try so I don't remember most of it. I have tried about 20 different options and even found some that work perfect in the Regex test sites but in PowerShell do not. I have tried both .split and replace. This is the last try I did. $test = "123456 (12).csv" $POPieces = $test -match "^[0-9\s]+$" write-host $POPieces. so far I have been able to return all numbers but that includes numbers in parenthesis. Commented Oct 9, 2017 at 13:01
  • 2
    $test -match '^\d+'; $matches[0] Commented Oct 9, 2017 at 13:14
  • $ anchors it to the end, ^ anchors to the beginning, so you're telling powershell to match a regex that has one or more numbers or spaces, and nothing else. Commented Oct 9, 2017 at 13:23

1 Answer 1

2

The -match operator stores the matches in the automatic variable $matches. However, your regular expression includes not only digits, but also whitespace (\s), so you won't necessarily get just the number. Change the expression to ^\d+ to match only a number at the beginning of the string. Use Get-ChildItem to enumerate the files, as Martin Brandl suggested.

$POPieces = Get-ChildItem 'C:\root\folder' -Filter '*.csv' |
            Where-Object { $_.Name -match '^\d+' } |
            ForEach-Object { $matches[0] }
Sign up to request clarification or add additional context in comments.

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.