title: How do I pass quoted parameters to PowerShell Invoke-Command and ScripBlocks?
body: <p>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 <strong>when trying to support spaces in the script name and/or file name</strong>.</p>
  
  <p><em>Note: The end result will be running a script on a <strong>REMOTE</strong> computer using the <code>-ComputerName</code> parameter to <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-6" rel="nofollow noreferrer">Invoke-Command</a>, but for simplicity and testing all the examples run locally.</em></p>
  
  <p>Given the sample "remote" script</p>
  
  <pre><code>#processFile.ps1
  $args[0]     # Just outputs the first parameter passed
  </code></pre>
  
  <p>The following works when there are no spaces in the name</p>
  
  <pre><code>$cmd = ".\processFile.ps1"
  $fn = "someFile.csv"
  $sb = [ScriptBlock]::Create("$cmd $fn")
  Invoke-Command -ScriptBlock $sb
  
  # Outputs the correct
  someFile.csv
  </code></pre>
  
  <p>However, the following does not work</p>
  
  <pre><code>$cmd = ".\processFile.ps1"
  $fn = "some File.csv"
  $sb = [ScriptBlock]::Create("$cmd $fn")
  Invoke-Command -ScriptBlock $sb
  
  # Outputs the incorrect
  some
  </code></pre>
  
  <p>Obviously, the file name parameter needs to be escaped and passed as "some File.csv". And this can be done with the following:</p>
  
  <pre><code>$cmd = ".\processFile.ps1"
  $fn = "some File.csv"
  $sb = [ScriptBlock]::Create("$cmd `"$fn`"")   # Notice the escape $fn parameter
  Invoke-Command -ScriptBlock $sb
  
  # Outputs the correct
  some File.csv
  </code></pre>
  
  <p><strong>BUT</strong>, when I try to extended this space support to the script name, everything falls apart. The following fails</p>
  
  <pre><code>$cmd = ".\processFile.ps1"
  $fn = "some File.csv"
  $sb = [ScriptBlock]::Create("`"$cmd`" `"$fn`"") # Notice the attempt to escape both parameters
  </code></pre>
  
  <p>with the following exception</p>
  
  <pre><code>Exception calling "Create" with "1" argument(s): "Unexpected token 'some File.csv' in expression or statement."
  </code></pre>
  
  <p>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 <strong>first</strong> parameter. Some of my attempts have included nested quotes, single quotes, [ScriptBlock]::Create, { }, $executionContext, etc.</p>