How do I pass quoted parameters to PowerShell Invoke-Command and ScripBlocks?

Question:

I need to run a ps1 script on a remote computer. The script will be passed a single parameter representing a file name. I have tried many, many different combinations and approaches to passing the parameters to the script block, but I am always getting one error or another when trying to support spaces in the script name and/or file name.

Note: The end result will be running a script on a REMOTE computer using the -ComputerName parameter to Invoke-Command, but for simplicity and testing all the examples run locally.

Given the sample “remote” script

The following works when there are no spaces in the name

However, the following does not work

Obviously, the file name parameter needs to be escaped and passed as “some File.csv”. And this can be done with the following:

BUT, when I try to extended this space support to the script name, everything falls apart. The following fails

with the following exception

Everything I have tried, and there have been many, many different approaches, have resulted in something similar. I just cannot seem to get both parameters to be escaped. (Actually, the problem is more than I cannot escape the first parameter. Some of my attempts have included nested quotes, single quotes, [ScriptBlock]::Create, { }, $executionContext, etc.

Answer:

Try this:

Source:

How do I pass quoted parameters to PowerShell Invoke-Command and ScripBlocks? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply