如何強制轉換為System.VersionPowerShell 中的型別,或者更有可能更好地理解為什么我不能任意分配數字字串型別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
大多數時候,這是可以接受的。但是,當遇到一些數字較長的奇怪球時,如下所示,
- 小程式-4u331r364.file
在這種情況下,System.Version拒絕結果字串太長。
Cannot convert value "4331364" to type "System.Version". Error: "Version string portion was too short or too long."
uj5u.com熱心網友回復:
您需要確保您的版本字串至少有兩個組件才能使[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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470730.html
