【问题标题】:Strip file from path PowerShell从路径 PowerShell 中剥离文件
【发布时间】:2022-01-18 05:42:27
【问题描述】:

我有一个 PowerShell 脚本,可以查找系统上的所有 log4j jar 文件。我想根据 pathfilenameversion 将找到的路径中的值分开。

例如,如果我有一个C:\Users\Administrator\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.14.1\log4j-core-2.14.1.jar的返回路径,我该如何获取:

只是路径 - C:\Users\Administrator\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.14.1\

只是文件 - log4j-core-2.14.1.jar

只是版本 - 2.14.1

【问题讨论】:

  • 你考虑过使用Split-Path吗?
  • 现在查看文档。
  • 它对前两个有用,但是版本正则表达式呢?

标签: windows powershell


【解决方案1】:

我会简单地使用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"
}

这将确保您确实拥有某个版本。而不是不同的字符串(只有当他们突然将文件名更改为其他名称时才会发生这种情况)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    相关资源
    最近更新 更多