简体   繁体   中英

Creating a shortcut for cmd from powershell with arguments - exception cannot save with 0 args

$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"

Error

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

I assure you that this path - C:\\Users\\Administrator\\Desktop\\Packages\\checkLauncher.bat does exist. Please do help to find out what is wrong with this.

Any help is awaited.. Thanks in advance

I can successfully create a shortcut using this approach however, have you defined $user somewhere else because that isn't defined by default. Perhaps you meant to use $env:username ? Alternatively you could use $home to get the c:\\users\\<username> part of the path. And even better is to use this .NET method:

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

I think you also want to specify the arguments like so:

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

The following works fine for me:

$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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM