我有一組從一些注冊表查詢中檢索到的路徑。截至目前,它們仍作為目錄物件回傳,但我需要將它們轉換為字串陣列。在 PS 中執行此操作的最有效方法是什么?
代碼:
$found_paths = @();
$uninstall_keys = getRegistrySubkeys "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" '\\Office[\d .*]';
if ($uninstall_keys -ne $null)
{
foreach ($key in $uninstall_keys)
{
$product_name = getRegistryValue $key "DisplayName";
$version = getRegistryValue $key "DisplayVersion";
$base_install_path = getRegistryValue $key "InstallLocation";
$full_install_path = Get-ChildItem -Directory -LiteralPath $base_install_path | Where-Object Name -match '^Office\d{1,2}\D?' | Select-Object FullName;
$found_paths = ,$full_install_path
}
}
write-output $found_paths;
輸出:
FullName
--------
C:\Program Files\Microsoft Office Servers\OFFICE15
C:\Program Files\Microsoft Office\Office15
期望的輸出:
C:\Program Files\Microsoft Office Servers\OFFICE15
C:\Program Files\Microsoft Office\Office15
uj5u.com熱心網友回復:
的最有效的方法是使用構件列舉((...).PropName):
$full_install_path = (
Get-ChildItem -Directory -LiteralPath $base_install_path | Where-Object Name -match '^Office\d{1,2}\D?'
).FullName
注意:聽起來您的命令可能只回傳一個目錄資訊物件,但該方法也適用于多個,在這種情況下會回傳一組路徑。
您需要處理的物件越多,成員列舉與解決方案相比的速度優勢就越大(見下文)。Select-Object -ExpandProperty
至于你嘗試了什么:
... | Select-Object FullName
不回傳輸入物件屬性的值.FullName,它回傳一個[pscustomobject]實體,其.FullName 屬性包含該值。要僅獲取值,您需要使用... | Select-Object -ExpandProperty FullName
$found_paths = , $full_install_path
您可能的意思是$found_paths = $full_install_path- 無需先在 RHS 上構造一個陣列(使用,)。
事實上,如果你這樣做并且$full_install_path碰巧包含多個元素,你會得到一個嵌套陣列。
退后一步:讓 PowerShell 自動為您從陣列中的回圈陳述句收集輸出會更有效:
$uninstall_keys = getRegistrySubkeys "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" '\\Office[\d .*]'
if ($null -ne $uninstall_keys)
{
# Collect the `foreach` loop's outputs in an array.
[array] $found_paths = foreach ($key in $uninstall_keys)
{
$product_name = getRegistryValue $key "DisplayName"
$version = getRegistryValue $key "DisplayVersion"
$base_install_path = getRegistryValue $key "InstallLocation"
# Get and output the full path.
(Get-ChildItem -Directory -LiteralPath $base_install_path | Where-Object Name -match '^Office\d{1,2}\D?').FullName
}
}
$found_paths # output (implicit equivalent of Write-Output $found_paths
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408668.html
標籤:
上一篇:回圈遍歷表和列組合
