gpt4 book ai didi

string - PowerShell 中 "System.Version"的版本字符串太长(或太短)

转载 作者:行者123 更新时间:2023-12-03 08:06:39 28 4
gpt4 key购买 nike

如何在 PowerShell 中强制转换为 System.Version 类型,或者更好地理解为什么我不能任意分配数字字符串类型 System.Version

我们在标题包含版本号的文件夹中提取一些软件更新。在尝试获取有关所摄取的最新版本的报告时,我一直在执行以下快速而肮脏的操作:

ForEach ($Folder in $(Get-ChildItem -Path $SoftwareDirectory -Directory))
{
$CurrentVersion = $Folder -Replace "[^0-9.]"
If ($CurrentVersion -ne $null)
{
If ([System.Version]$CurrentVersion -gt [System.Version]$MaxVersion)
{
$MaxVersion = $CurrentVersion
$MaxFolder = $Folder
}
}
}

这将提供如下所示的目录标题,

  • foo-tools-1.12.file
  • bar-static-3.4.0.file

大多数时候,这是可以接受的。然而,当遇到一些数字比较长的怪人时,比如下面这样,

  • applet-4u331r364.file

在这种情况下,System.Version 会因为结果字符串太长而拒绝。

Cannot convert value "4331364" to type "System.Version". Error: "Version string portion was too short or too long."

最佳答案

您需要确保您的版本字符串至少有两个个组件才能转换为 [version]成功:

(
@(
'oo-tools-1.12.file'
'bar-static-3.4.0.file'
'applet-4u331r364.file'
) -replace '[^0-9.]'
).TrimEnd('.') -replace '^[^.]+$', '$&.0' | ForEach-Object { [version] $_ }

上面将 'applet-4u331r364.file' 转换为 '4331364.0',在转换为 [version] 时有效。

请注意,如果您排除以下文件扩展名,则可以避免使用 .TrimEnd('.'):$Folder.BaseName -replace '[^0-9 .]'

-replace '^[^.]+$', '$&.0' 仅匹配不包含 . 字符的字符串。完整的,即仅那些还没有至少两个组件的;替换表达式 $&.0 将文字 .0 附加到匹配的字符串 ($&)。

输出(通过Format-Table -AutoSize):

Major   Minor Build Revision
----- ----- ----- --------
1 12 -1 -1
3 4 0 -1
4331364 0 -1 -1

关于string - PowerShell 中 "System.Version"的版本字符串太长(或太短),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72146147/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com