Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to escape characters in paths

Is there a function in PowerShell for escaping characters in paths?

NB: I'm aware that most cmdlets which provide a Path parameter also provide a LiteralPath parameter which resolves this issue. This question is more from curiosity than need, as in most use cases I can think of, switching to LiteralPath makes sense. However there are some genuine use-cases (e.g. Start-BitsTransfer has a Source parameter, but no literal equivalent).

Detail

If I have a file c:\temp\test[0123].txt, instead of Get-Item 'c:\temp\test[0123].txt', I'd have to use Get-Item 'c:\temp\test`[0123`].txt' to get a result (or make use of the LiteralPath parameter).

Even the path returned by another PowerShell command returns an unescaped string; i.e. Get-ChildItem 'c:\temp\' -Filter 'test*.txt' | Convert-Path | Get-Item fails (NB: if we pass the actual FileSystemInfo object all works, but that object has no properties with the correctly escaped string path).

We can easily escape this using code such as below:

$path = 'c:\temp\test[0123].txt'
$path = $path -replace '([][[])', '`$1' # escape square brackets by adding back ticks
Get-Item $path

However when escaping strings, standard advice is to avoid rolling your own solution / to make use of the language's solutions to these issues.

Is there any pre-existing function in PowerShell for this purpose, or any recommended way of approaching this; or is the only option to use a bespoke function (e.g. below)?

function ConvertFrom-LiteralPath {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$LiteralPath
    )
    process {
        (New-Object -TypeName 'PSObject' -Property @{
            LiteralPath = $LiteralPath
            Path = $LiteralPath -replace '([][[\*\?])', '`$1' # escapes ], [, *, and ?
        })
    }
}

Info on special characters:

  • Wildcard Queries: https://technet.microsoft.com/en-us/library/ee692793.aspx
  • File Paths: https://technet.microsoft.com/en-us/library/ff730956.aspx
like image 321
JohnLBevan Avatar asked Sep 04 '17 12:09

JohnLBevan


People also ask

How do you escape a special character in path?

To search for a special character that has a special function in the query syntax, you must escape the special character by adding a backslash before it, for example: To search for the string "where?", escape the question mark as follows: "where\?"

What is the function of escape character?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

How do you escape characters?

Escape CharactersUse the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped.


1 Answers

There is the following method you can use:

[Management.Automation.WildcardPattern]::Escape('test[1].txt')

Returns:

test`[1`].txt

Documented here:
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.wildcardpattern.escape

like image 67
Mark Wragg Avatar answered Oct 15 '22 07:10

Mark Wragg