title: How to handle file paths with special characters?
body: <p>I've got a PowerShell script that needs to be able to call another PS script from within the same directory with elevated credentials.  Because the scripts need to be portable, the file path of the scripts isn't known ahead of time and needs to be able to handle spaces and special characters in the file path without failing.</p>
  
  <p>Since elevating a PS session will cause the current working directory to change to "C:\Windows\System32", I need to be able to pass the current directory to the script as a parameter.  Now, my current script (below) is handling this fine as long as there aren't special characters in the directory path.</p>
  
  <p>Here's my current script (updated per @mklement0's suggestion):</p>
  
  <pre><code>$scriptpath = $MyInvocation.MyCommand.Path
  $dir = Split-Path $scriptpath
  
  Start-Process Powershell -Verb runas -ArgumentList "-ExecutionPolicy","Bypass","-File","`"$dir\elevated.ps1`"","`"$dir`""
  </code></pre>
  
  <p>I've tried escaping some of the special characters, like so:</p>
  
  <pre><code>$dir = $dir.Replace('&amp;','`"&amp;`"')
  </code></pre>
  
  <p>but that's not working consistently for all the different characters that Windows allows in a folder/filename.  Not all special characters need to be escaped either, but I need to make sure this works for the ones that do; at least those that are likely to show up in a filepath.</p>
  
  <p>Special characters I'm mainly concerned with (though foreign characters might also need to be addressed at some point): <code>!@#$%^_+-=.,{}`~&amp;()[]</code></p>
  
  <p>Example directory path I'm testing with: </p>
  
  <pre>
  C:\Users\Administrator\Desktop\Test Folder\badname-!@#$%^_+-=.,{}`~&()[]
  </pre>
  
  <p>Trying to run my script from the above location returns the following error:</p>
  
  <pre>
  The specified wildcard character pattern is not valid:
  badname-!@#$%^_+-=.,{}\~&()[]
      + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
      + FullyQualifiedErrorId : RuntimeException
  </pre>
  
  <p>So, what's the best way to have the script dynamically handle special characters in the directory path?</p>