我查詢注冊表以獲取我正在尋找的檔案路徑。但是,我需要下一個目錄來檢索我需要的一些檔案資訊。我試圖匹配的模式是Officexxor OFFICExx。我似乎無法找到我需要的路徑。
從注冊表中找到路徑: C:\Program Files\Microsoft Office
我需要的是: C:\Program Files\Microsoft Office\Officexx
代碼:
$base_install_path = "C:\Program Files\Microsoft Office";
$full_install_path = $base_install_path '\Office[\d .*]'
Write-Output $full_install_path;
這將回傳:
C:\Program Files\Microsoft Office\Office[\d .*]
期望的輸出:
C:\Program Files\Microsoft Office\Office15
不是這可以是任何兩位數# ^^
uj5u.com熱心網友回復:
基于Santiago Squarzon 的有用評論:
# Find all child directories matching the given wildcard pattern, if any.
Get-ChildItem -Directory -Path "$base_install_path\Office[0-9][0-9]*"
不像POSIX兼容外殼,例如
bash,PowerShell將不支持無引號串的自動通配(對檔案名,被稱為模式匹配檔案名擴展和代替)需要顯式使用的Get-ChildItem或Get-Item小命令; 例如,PowerShell 中的bashcommand等價物pattern='*.txt'; echo $pattern是$pattern='*.txt'; Get-ChildItem -Path $pattern- 請注意,描述匹配檔案或目錄的物件由這些 cmdlet 輸出;根據需要使用它們的屬性,例如
(Get-ChildItem $pattern).Name或(Get-ChildItem $pattern).FullName(完整路徑)。使用Get-ChildItem $pattern | Get-Member -Type Properties查看所有可用的屬性。
- 請注意,描述匹配檔案或目錄的物件由這些 cmdlet 輸出;根據需要使用它們的屬性,例如
-Path這些 cmdlet的引數需要一個 PowerShell通配符運算式來執行所需的匹配,并且頂部命令中的運算式正好匹配兩個數字 ([0-9][0-9]),后跟零個或多個字符 (*),無論它們是什么(可能包括其他數字)。
鑒于通配符模式僅支持一種非特定的重復結構,即上述的*,匹配特定范圍的數字 - 例如最多1 或 2或特定計數- 例如恰好兩個- 需要基于正則運算式的后過濾(這是您嘗試使用的):
# Find all child directories matching the given regex, if any.
# Matches 'Office' at the start of the name (^),
# followed by 1 or 2 ({1,2}) digits (\d),
# followed by at least non-digit (\D), if any (?)
Get-ChildItem -Directory -LiteralPath $base_install_path |
Where-Object Name -match '^Office\d{1,2}\D?'
至于你嘗試了什么:
[\d .*]是一個正則運算式,但你可能的意思是\d.*在字符范圍/集合運算式 (
[...]) 內,.并且逐字*使用,即它們不是元字符并且匹配文字和字符。.*
uj5u.com熱心網友回復:
Get-ChildItem -Path 'C:\Program Files\Microsoft Office\' -Directory |
Where-Object { $_.Name -match 'Office\d ' }
在您的正則運算式中,[]是一個字符類,表示[\d .*]不是“一個或多個數字”,而是“反斜杠 OR d OR 加 OR 點 OR 星號”。
PS C:\> "d \" -match "[\d ]"
True
不是你要找的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/405490.html
標籤:
