Edwin
Edwin

Reputation: 65

Print a PNG-file from PowerShell using variables

I want to print a PNG file from within a PowerShell script. I can make it work by inserting the full path to the image, but I want it to be variable.

This works:

Start-Process -filepath "C:\windows\system32\mspaint.exe" -argumentlist '/p "D:\simplecodegenerator\5555.png" /pt "Microsoft Print to PDF"'

But I cannot get it to work with variables.

$photo = "5555.png"
$folder = "D:\simplecodegenerator\"

Start-Process -filepath "C:\windows\system32\mspaint.exe" -argumentlist '/p $folder$photo /pt "Microsoft Print to PDF"'

When I run the last code it will give the following error:

C:\Users\*******\$folder$photo.png not found. I was expecting that it would save as D:\simplecodegenerator\5555.png

Can anybody help me with this, or is it impossible to do ?

Upvotes: 2

Views: 1617

Answers (2)

Ash
Ash

Reputation: 3246

Satya has given you good advice and the approach will work. The reason why your example did not work is that the variables are not pre-processed inside single quotes before they are passed to the command, whereas inside double quotes PowerShell does perform this pre-processing replacing the variables with their values. The end result is what you saw, it looks for the variable names as strings in your current directory.

Here are some alternatives.

  1. Escape the additional double quotes around the printer option using the backtick character. This is useful in some situations where you need to use specific types of quotes.
Start-Process -FilePath mspaint.exe -ArgumentList "/p $folder$photo /pt `"Microsoft Print To PDF`""
  1. You do not need to use Start-Process. This will run fine with just the call operator.
& mspaint.exe /p $folder$photo /pt "Microsoft Print To PDF"
  1. Or without anything at all.
mspaint.exe /p $folder$photo /pt "Microsoft Print To PDF"

Upvotes: 1

Satya Sahoo
Satya Sahoo

Reputation: 81

Use " instead of ' as the outer string in command when you are using variables inside it.

Ex:

$photo = "5555.png"
$folder = "D:\simplecodegenerator\"

Start-Process -filepath "C:\windows\system32\mspaint.exe" -argumentlist "/p $folder$photo /pt 'Microsoft Print to PDF'"

Upvotes: 1

Related Questions