powershellescapingspecial-charactersfilepathstart-process

How to handle file paths with special characters?


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.

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.

Here's my current script (updated per @mklement0's suggestion):

$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath

Start-Process Powershell -Verb runas -ArgumentList "-ExecutionPolicy","Bypass","-File","`"$dir\elevated.ps1`"","`"$dir`""

I've tried escaping some of the special characters, like so:

$dir = $dir.Replace('&','`"&`"')

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.

Special characters I'm mainly concerned with (though foreign characters might also need to be addressed at some point): !@#$%^_+-=.,{}`~&()[]

Example directory path I'm testing with:

C:\Users\Administrator\Desktop\Test Folder\badname-!@#$%^_+-=.,{}`~&()[]

Trying to run my script from the above location returns the following error:

The specified wildcard character pattern is not valid:
badname-!@#$%^_+-=.,{}\~&()[]
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : RuntimeException

So, what's the best way to have the script dynamically handle special characters in the directory path?


Solution

  • So, I was able to figure out a solution that works as long as the brackets aren't empty [].

    Here's what I've got:

    Start-Process Powershell -Verb runas -ArgumentList "-ExecutionPolicy","Bypass","-File","`"$(Get-Item -LiteralPath $PSScriptRoot\elevated.ps1)`""
    

    Using this as the test path:

    C:\Users\Administrator\Desktop\Test Folder\badname-!@#$%^_+-=.,{}`~[&]()
    

    A path with empty brackets [] still doesn't work, but doesn't return an error. I'm assuming this means that it wasn't able to find a file in the expected path while interpreting the brackets as a wildcard still. Not sure if there's really anything that will fix that except maybe checking the path before running and throwing an error.