我会简单地使用Get-ChildItem。
$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]
或者,使用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]
奖金
这是不必要的,因为您可以直接从路径中获取版本,但如果路径没有以这种方式格式化,您可以通过以下方式从文件名中提取版本。
$Version = $Filename -replace 'log4j-core-(.*).jar', '$1'
奖金 #2
假设您想主动处理可能的文件名更改,然后您可以将提取的版本解析为 System.Version 对象,以确保您得到有意义的东西。
$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"
}
这将确保您确实拥有某个版本。而不是不同的字符串(只有当他们突然将文件名更改为其他名称时才会发生这种情况)。