11 Jan 2010

Powershell: Dealing with single quotes within arguments

A run in a very special issue when I tried to pass arguments to a powershell script if one of the arguments contained single quotes within the argument string like “this is damn ‘quote’ inside the arg!!” Your powershell script would then think that these are separated arguments. You won’t get the hell out of this sh*t. One possible solution is to place the “wracky” argument at the end, in fact use is as last argument. Install the Powershell Community Extensions and use the join-string cmdlet. Here’s an example.

# save this code as a ps script and use two arguments to pass to the script.
# use single quotes within the 2nd argument, eg.    “This is the ‘2nd’ Argument”

$i = 1 for ( $i ; $i -lt $args.count; $i++ )
$msg += $args[$i]

$msg = ($msg | join-string -separator ” “)
write-host ‘The Script Arguments where now: “‘$user’” “‘$msg’”‘