Home > Software design >  Strip file from path PowerShell
Strip file from path PowerShell

Time:12-15

I have a PowerShell Script that finds all log4j jar files on a system. I want to separate the values out of the found paths based on just path, filename, and version.

For example, if I have a returned path of C:\Users\Administrator\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.14.1\log4j-core-2.14.1.jar, how can I get:

Just the path - C:\Users\Administrator\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.14.1\

Just the file - log4j-core-2.14.1.jar

Just the version - 2.14.1

CodePudding user response:

I would simply use Get-ChildItem for that.

$Item = Get-ChildItem -Path 'C:\Users\Administrator\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.14.1\log4j-core-2.14.1.jar'

# Folder containing the file
$Item.PSParentPath

# Filename
$Item.Name

# Version extracted from the Parent path
# As string
($ITem.PSParentPath.Split('\'))[-1]
# As System.Version object
[Version]($ITem.PSParentPath.Split('\'))[-1]

Or, using Split-Path

$FullPath = 'C:\Users\Administrator\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.14.1\log4j-core-2.14.1.jar'
$Filename = Split-Path -Path $FullPath -Leaf
$ParentPath = Split-Path -Path $FullPath -Parent
# Version from Parent path
$Version = $ParentPath.Split('\')[-1]

Bonus

This is unnecessary since you can get the version straight from the path but if the path was not formatted in such a way, you could extract the version from the filename in the following way.

$Version = $Filename -replace 'log4j-core-(.*).jar', '$1'

Bonus #2

Let's say you want to be proactive with the possible filename change, you could then parse the extracted version into a System.Version object to make sure you are getting something that make sense.

$Version = $null
if (![Version]::TryParse(($Filename -replace 'log4j-core-(.*).jar', '$1'),[ref]$Version)) {
    Write-Warning 'Version could not be parsed from the filename'
} else {
    Write-Host "Version is $Version"
}

That would ensure that you indeed have a version of something. and not a different string (this would only happen if they suddently changed the filename to something else).

  • Related