gpt4 book ai didi

string - 如何将目录对象转换为字符串 - Powershell

转载 作者:行者123 更新时间:2023-12-05 01:25:50 26 4
gpt4 key购买 nike

我有一组从某些注册表查询中检索到的路径。截至目前,它们仍作为目录对象返回,但我需要将它们转换为字符串数组。在 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

最佳答案

最有效的方法是使用member-access enumeration ( (...).PropName ):

$full_install_path = (
Get-ChildItem -Directory -LiteralPath $base_install_path | Where-Object Name -match '^Office\d{1,2}\D?'
).FullName

注意:听起来您的命令可能只返回一个目录信息对象,但该方法也适用于多个,在这种情况下 返回路径的 em>array

您需要处理的对象越多,成员访问枚举相对于 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

关于string - 如何将目录对象转换为字符串 - Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70671757/

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