使用参数从powershell创建cmd的快捷方式 - 异常无法使用0参数保存

时间:2013-09-19 16:11:20

标签: windows powershell batch-file cmd

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("C:\Users\$user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\CheckLauncher.lnk")
$Shortcut.TargetPath = "cmd.exe"
$Shortcut.Arguments = "C:\Users\Administrator\Desktop\Packages\checkLauncher.bat"

错误

Exception calling "Save" with "0" argument(s): "Unable to save shortcut "C:\Use
rs\Administrator\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\
CheckLauncher.lnk"."
At C:\Users\Administrator\Desktop\Packages\Setup.ps1:22 char:15
+ $Shortcut.Save <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

我向您保证此路径 - C:\ Users \ Administrator \ Desktop \ Packages \ checkLauncher.bat确实存在。 请帮忙找出问题所在。

等待任何帮助..提前致谢

1 个答案:

答案 0 :(得分:2)

我可以使用这种方法成功创建快捷方式,但是你在其他地方定义了$user,因为默认情况下没有定义它。也许你打算用$env:username?或者,您可以使用$home来获取路径的c:\users\<username>部分。更好的是使用这种.NET方法:

[Environment]::GetFolderPath([environment+specialfolder]::ApplicationData)

我认为你也想要像这样指定参数:

$Shortcut.Arguments = "/c C:\Users\Administrator\Desktop\Packages\checkLauncher.bat"

以下对我来说很好:

$roaming = [environment]::GetFolderPath([environment+specialfolder]::ApplicationData)
$path = "$roaming\Microsoft\Windows\Start Menu\Programs\Startup\UpdateBinDir.lnk"
$WshShell = New-Object -comObject WScript.Shell
$shortcut = $WshShell.CreateShortcut($path)
$shortcut.TargetPath = "cmd.exe"
$shortcut.Arguments = "/c C:\bin\updateBinDir.bat"
$shortcut.Save()