Search code examples
stringpowershellshortcut-file

Assigning a string with escaped characters to a property


I want to set a string path to a string property of a $Shortcut object and it doesn't seam to work.

Running this code :

$WshShell = New-Object -comObject WScript.Shell ;
$Shortcut = $WshShell.CreateShortcut('c:\aaa.lnk');
$Shortcut.TargetPath = '"c:\Program Files\MyApp.exe" /param1: (2) /param2 "val"'

I get this error while setting $Shortcut.TargetPath:

Exception setting "TargetPath": "The parameter is incorrect. (Exception from HRESULT:
0x80070057 (E_INVALIDARG))"
At line:1 char:11
+ $Shortcut. <<<< TargetPath = '"c:\Program Files\MyApp.exe" /param1: (2) /param2 "val"'
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

The strange thing is that trying to reproduce this behavior on a new custom object, the problem doesn't appear. Just run the commands below:

$object = New-Object -TypeName PSObject
Add-Member -MemberType NoteProperty -Name prop -Value "aaa"
$object.prop = '"c:\Program Files\MyApp.exe" /param1: (2) /param2 "val"'

Solution

  • When in doubt, read the documentation. The TargetPath property takes just the path to the excutable. The arguments go into the Arguments property:

    $WshShell = New-Object -ComObject WScript.Shell
    $Shortcut = $WshShell.CreateShortcut('c:\aaa.lnk')
    $Shortcut.TargetPath = 'c:\Program Files\MyApp.exe'
    $Shortcut.Arguments  = '/param1: (2) /param2 "val"'