如何修正PowerShell脚本快捷方式中参数位置颠倒的问题?
解决快捷方式中PowerShell启动参数顺序颠倒的问题
你当前的脚本逻辑完全搞反了快捷方式的目标程序和启动参数,导致生成的快捷方式不符合预期。
问题根源
你把.ps1脚本路径设为了快捷方式的TargetPath(目标程序),却把powershell.exe -file设为了Arguments(启动参数),这相当于让系统尝试以脚本文件为“程序”,把PowerShell命令当作参数传递,自然会出现顺序颠倒的结果。
正确的实现思路
- 快捷方式的
TargetPath必须是PowerShell的可执行文件路径(推荐用完整路径,避免环境变量异常) - 快捷方式的
Arguments则是-file加上带引号的脚本完整路径(路径带空格时必须加引号)
修改后的完整脚本
foreach($filename in $reqshortcutlist){ $scriptPath = Join-Path "C:\Users\yo\Documents\Powershell Lab\source" $fileName # 使用PowerShell的完整路径,避免环境变量找不到的情况 $targetExe = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" $shortcutPath = "C:\Users\yo\Documents\Powershell Lab\fixes\$filename.lnk" $WScriptObj = New-Object -ComObject WScript.Shell $shortcut = $WscriptObj.CreateShortcut($shortcutPath) # 目标程序设为PowerShell可执行文件 $shortcut.TargetPath = $targetExe # 参数设为 -file 加上带引号的脚本路径 $shortcut.Arguments = "-file `"$scriptPath`"" $shortcut.Save() }
验证效果
生成的快捷方式目标会变成:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -file "C:\Users\yo\Documents\Powershell Lab\source\PS CMD Workaround.ps1"
完全符合你需要的格式。
内容的提问来源于stack exchange,提问作者Get-Help
相关产品推荐
相关产品推荐

