Anuj Masand
Anuj Masand

Reputation: 359

Formatting String in PowerShell

While using " in my command string, double quotes gets interpreted.

$printername="Intouch Printer"
print($printername)

$command ='D:\spool12\spool.exe '+ $_.FullName + ' "'+ $printername+'"'
print($command)
iex $command

I am getting this while I am executing this code:

> D:\spool12\spool.exe D:\Spool Files-20170113T061110Z\Spool Files\Un
> Readable\creame and  fudge\00143.SPL IntouchPrinter

Rather I want it to be like:

> D:\spool12\spool.exe D:\Spool Files-20170113T061110Z\Spool Files\Un
> Readable\creame and  fudge\00143.SPL "IntouchPrinter"

Upvotes: 4

Views: 490

Answers (3)

Kirill Pashkov
Kirill Pashkov

Reputation: 3236

You could also wrap strings like this:

$command = @"
D:\spool12\spool.exe "Intouch Printer"
"@
iex $command

Upvotes: 0

Martin Brandl
Martin Brandl

Reputation: 59001

I prefer using a format string in such scenarios:

$command = 'D:\spool12\spool.exe {0} "{1}"' -f $_.FullName, $printername

Upvotes: 4

henrycarteruk
henrycarteruk

Reputation: 13227

Have a read of the About Quoting Rules, it'll cover what you need to know about quotes and escaping them.

In your case you need to use double quotes around the entire command, and then use the backtick to escape the quotes around $printername.

You will also need to use the Subexpression operator $() so that the FullName property evaluates correctly:

$command = "D:\spool12\spool.exe $($_.FullName) `"$printername`""

Upvotes: 0

Related Questions