【问题标题】:Powershell - Get-ChildItem and Join-PathPowershell - Get-ChildItem 和 Join-Path
【发布时间】:2020-09-11 18:36:32
【问题描述】:

我正在尝试在注册表中查询特定应用的 InstallLocation,然后我希望根据该信息创建路径。

例如,我希望在注册表中找到 Microsoft Office 安装目录,然后找到 Directory\Word.exe。挑战在于“Join-Path”函数不断为存储的变量返回空值:

$ProgramName = "*Microsoft*Office*"
$results = Get-ChildItem 
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\*\Products\*\InstallProperties" | 
Where-Object { $_.getValue('DisplayName') -like $ProgramName } | ForEach-Object {   
$_.getValue('InstallLocation')} 
$childfolder = 'Office16'
Join-Path $results $childfolder

错误:连接路径:无法将参数绑定到参数“路径”,因为它是一个空字符串。 此外,当我完全删除 Join-Path 并尝试手动连接字符串时,似乎总是添加了一个空格,即使我明确调用了变量,这导致我假设 PS 正在单独执行命令(实际上不是连接他们)。

我假设我没有正确存储变量。尝试 .ToString() 会导致同样的错误。我究竟做错了什么?谢谢!

编辑:这是我调用 $results 并尝试连接它们时的行为:

$results
$Endpath = ($results) + ($childfolder)
$Endpath

C:\Program Files (x86)\Microsoft Office\

Office16

【问题讨论】:

  • 可能InstallLocation 对于这些键是空的。
  • 当我切换断点和/或调用 $results 时,我成功看到了路径:C:\Program Files (x86)\Microsoft Office\
  • 其中一个InstallLocation 值为空。您需要过滤掉空的。 --> Where-Object { $_.getValue('DisplayName') -like $ProgramName -and $_.getValue('InstallLocation')}join-path ($results |? {$_}) $childfolder
  • 看起来是这样做的!我想我明白了。 “额外空格”是由添加到非空结果中的空结果引起的,我假设 join-path 不喜欢以空格结尾的路径。非常感谢,我正在拔头发。

标签: powershell


【解决方案1】:

您的InstallLocation 值之一为空。当绑定到Join-Path-Path 参数的值之一为空或$null 时,将引发错误。您需要过滤掉空值。

$ProgramName = "*Microsoft*Office*"
$childfolder = 'Office16'
$results = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\*\Products\*\InstallProperties" |
    Where {$_.DisplayName -like $ProgramName -and $_.InstallLocation}
if ($results) { Join-Path $results $childfolder }

如果属性包含一个通常不会计算为False 的非空和非空值,则Where {$_.Property} 将计算为True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多