polo
polo

Reputation: 385

Powershell: How to extract part a file name

I have a file that follows this naming convention: project.customer.version-number.zip

So for example i might have a file called: project.customer.1.1.889.zip

The "version-number" will change.

"project" and "customer" will stay the same. The zip file extension will always be the same.

I long way to get it I have found is to use multiple Split paths and then concatenate together to get the full version number. So i would have:

$1 = (Split-Path -Path $filePath -Leaf).Split(".")[2];
$2 = (Split-Path -Path $filePath -Leaf).Split(".")[3];
$3 = (Split-Path -Path $filePath -Leaf).Split(".")[4];
$version = $1 + "." + $2 "." + $3

Is there a quicker / better way to extract just the version number (i.e. the 1.1.889) if i don't know what it will be every time with powershell?

Upvotes: 1

Views: 564

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36297

You can limit the number of item that split returns. In this case you just want to split it into Project, Customer, and Version. First we'll reduce it to just the file name with Split-Path -leaf, then we remove the file extension with -replace, and then we'll split the remaining file base name 3 times.

$project,$customer,$version = ((Split-Path -Path $filePath -Leaf) -replace '\.zip$').Split(".",3)

Upvotes: 2

Related Questions