Reputation: 65
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
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.
Start-Process -FilePath mspaint.exe -ArgumentList "/p $folder$photo /pt `"Microsoft Print To PDF`""
Start-Process
. This will run fine with just the call operator.& mspaint.exe /p $folder$photo /pt "Microsoft Print To PDF"
mspaint.exe /p $folder$photo /pt "Microsoft Print To PDF"
Upvotes: 1
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