首页 > 解决方案 > 快捷方式未显示 TargetPath

问题描述

我正在尝试从带有 PowerShell 5.0 的 Windows 7 中的快捷方式获取可执行文件的路径,如果这有所不同的话。我$workingTarget = 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\SnippingTool.lnk'的和捷径就在那里。当我打开快捷方式的属性时,快捷方式的目标属性显示%windir%\system32\SnippingTool.exe. 然而,

$shortcut = $shell.CreateShortcut($workingTarget)
Write-Host "$($shortcut.TargetPath)"

什么都没有显示。当我尝试使用不同的快捷方式时,使用没有环境变量的完全解析路径,Write-Host 很好。我的希望是至少获取字符串并使用 Get-Command 通过 Paths 环境变量查找路径,但即使这样看起来也有问题,因为

Write-Host "$(Get-Command (Split-Path '%windir%\system32\SnippingTool.exe' -leaf))"
Write-Host "$(Get-Command (Split-Path 'SnippingTool.exe' -leaf))"

两者都只是 return SnippingTool.exe,而不是正确的完整路径。现在,在光明的一面

Write-Host "$([System.Environment]::ExpandEnvironmentVariables('%windir%\system32\SnippingTool.exe'))"

确实会按预期扩展,但前提是我真的可以%windir%\system32\SnippingTool.exe摆脱目前让我烦恼的捷径。

标签: powershell

解决方案


在对 SO 进行快速搜索后,我发现 Jeffs 的答案将满足您的需求。

使用 powershell 获取快捷方式 (.lnk) 文件的目标

$sh = New-Object -ComObject WScript.Shell $target = $sh.CreateShortcut('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Snipping Tool.lnk').TargetPath

我在 ISE 中运行它时的结果:

[Admin] C:\WINDOWS\system32\> $sh = New-Object -ComObject WScript.Shell
$target = $sh.CreateShortcut('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Snipping Tool.lnk').TargetPath
$target
C:\WINDOWS\system32\SnippingTool.exe

跑步

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      15063  1206

推荐阅读