我有一个从一些注册表查询中检索到的路径数组。到目前为止,它们仍作为目录对象返回,但我需要将它们转换为字符串数组。在PS中,最有效的方法是什么?
代码:
$found_paths = @();
$uninstall_keys = getRegistrySubkeys "HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionUninstall" '\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 '^Officed{1,2}D?' | Select-Object FullName;
$found_paths += ,$full_install_path
}
}
write-output $found_paths;
输出:
FullName
--------
C:Program FilesMicrosoft Office ServersOFFICE15
C:Program FilesMicrosoft OfficeOffice15
期望输出:
C:Program FilesMicrosoft Office ServersOFFICE15
C:Program FilesMicrosoft OfficeOffice15
最有效的方法是使用成员访问枚举((...).PropName
(:
$full_install_path = (
Get-ChildItem -Directory -LiteralPath $base_install_path | Where-Object Name -match '^Officed{1,2}D?'
).FullName
注意:听起来您的命令可能只返回了一个目录信息对象,但这种方法也适用于多个组。
需要处理的对象越多,与Select-Object
-ExpandProperty
解决方案相比,成员访问枚举的速度优势就越大(见下文(。
至于您尝试了什么:
... | Select-Object FullName
不返回输入对象的.FullName
属性的值,而是返回具有包含该值的.FullName
属性的[pscustomobject]
实例。要仅获取值,您需要使用... | Select-Object -ExpandProperty FullName
$found_paths += , $full_install_path
您的意思可能是$found_paths += $full_install_path
-不需要首先在RHS上构造数组(使用,
(。
事实上,如果这样做,并且$full_install_path
恰好包含多个元素,则会得到嵌套的数组。
后退一步:让PowerShell自动为您收集数组中循环语句的输出要高效得多:
$uninstall_keys = getRegistrySubkeys "HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionUninstall" '\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 '^Officed{1,2}D?').FullName
}
}
$found_paths # output (implicit equivalent of Write-Output $found_paths