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

3
我有一个路径数组,是从一些注册表查询中检索到的。目前,仍将它们作为目录对象返回,但我需要将它们转换为仅由字符串组成的数组。在PowerShell中,最有效的方法是什么?
代码:
  $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  

顺便提一下:如果您把多个语句放在同一行上,PowerShell中只需要使用来终止语句。 - mklement0
1个回答

6
最有效的方法是使用成员访问枚举 ((...).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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接