kyb
kyb

Reputation: 8101

PowerShell pass arguments with quotes

Have very useful script named sudo.ps1:

$w=""; foreach($a in $args[1..($args.length-1)] ){ $w += " " + $a }; $w
Start-Process $args[0] -ArgumentList $w -Verb RunAs -Wait 

but it can't handle complex command

./sudo.ps1 schtasks /create /F /TN "$vpn_name Connection Update" /TR "Powershell.exe -noexit -command D:\vpn-route.ps1" /SC ONEVENT /EC Application /MO "*[System[(Level=4 or Level=0) and (EventID=20225)]] and *[EventData[Data='$vpn_name']]" /RL HIGHEST 

Problem is in obfuscated quotes. In sudo.ps1 quotes are opened:

 /create /F /TN VPN-Kosmos6 Connection Update /TR Powershell.exe -noexit -command D:\vpn-route.ps1 /SC ONEVENT /EC Application /MO *[System[(Level=4 or Level=0) and (EventID=20225)]] and *[EventData[Data='VPN-Kosmos6']] /RL HIGHEST

Command executed with no error, but does no work. How can it be fixed?

Upvotes: 4

Views: 4204

Answers (1)

kyb
kyb

Reputation: 8101

If arg contains space, add quotes via """ (thanks to PetSerAl). Now sudo.ps1 works fine:

$w=""; foreach($a in $args[1..($args.length-1)] ){ $w+=" "; if($a -match " "){$w+="""$a"""}else{$w+=$a} }; $w
Start-Process $args[0] -ArgumentList $w -Verb RunAs -Wait 

Consider another solutions suggested by Keith Hill and Bill_Stewart, if looking for better and more complex decision.

Upvotes: 1

Related Questions