You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell条件循环问题:无法正确验证快捷方式目标路径

解决PowerShell快捷方式目标路径匹配问题

你的代码无法正确匹配快捷方式目标路径,主要是两个常见问题导致的:

  • PowerShell默认的-eq运算符区分大小写,如果快捷方式返回的目标路径大小写和你定义的$IE不一致,就会匹配失败
  • 直接传入文件对象给CreateShortcut虽然能运行,但明确使用文件完整路径能避免潜在的解析问题

以下是修正后的代码,能稳定实现需求:

$WSShell = New-Object -ComObject Wscript.Shell
# 获取所有用户文档目录下的快捷方式完整路径
$shortcutfiles = Get-ChildItem C:\Users\*\documents\*.lnk | Select-Object -ExpandProperty FullName
$IE = "C:\Program Files\Internet Explorer\iexplorer.exe"

foreach ($shortcutfile in $shortcutfiles ) {
    $shortcut = $WSShell.CreateShortcut($shortcutfile)
    # 用不区分大小写的比较运算符-ieq,避免大小写差异影响匹配
    if ($shortcut.TargetPath -ieq $IE) {
        Write-Host "找到匹配的快捷方式:$shortcutfile,目标路径:$($shortcut.TargetPath)"
    }
}

如果需要更严谨的路径匹配(比如处理路径格式差异),可以用Resolve-Path标准化路径后再比较,这种方式能统一路径的格式,同时处理可能的相对路径问题:

$WSShell = New-Object -ComObject Wscript.Shell
$shortcutfiles = Get-ChildItem C:\Users\*\documents\*.lnk | Select-Object -ExpandProperty FullName
# 标准化目标路径格式
$IE = (Resolve-Path -Path "C:\Program Files\Internet Explorer\iexplorer.exe").Path

foreach ($shortcutfile in $shortcutfiles ) {
    $shortcut = $WSShell.CreateShortcut($shortcutfile)
    # 标准化快捷方式的目标路径,忽略不存在路径的报错
    $targetPathNormalized = (Resolve-Path -Path $shortcut.TargetPath -ErrorAction SilentlyContinue).Path
    if ($targetPathNormalized -eq $IE) {
        Write-Host "找到匹配的快捷方式:$shortcutfile"
    }
}

内容的提问来源于stack exchange,提问作者Freddy Ledezma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 07:15:06