Function to delete characters in tracks

Is there a function in PowerShell to escape characters in tracks?

NB: I know that most cmdlets that provide a parameter Pathalso provide a parameter LiteralPaththat solves this problem. This question is more connected with curiosity than with necessity, since in most cases that I can think of, switching to LiteralPathmakes sense. However, there are some use cases (for example, it Start-BitsTransferhas a parameter Source, but does not have an equivalent literal).

Detail

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

Even the path returned by another PowerShell command returns a string without saving; that is, it Get-ChildItem 'c:\temp\' -Filter 'test*.txt' | Convert-Path | Get-Itemdoes not work (NB: if we pass the actual object FileSystemInfo, everything works, but this object does not have properties with a properly shielded path).

We can easily avoid this by using the following code:

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

However, avoiding the lines, the standard tip is to not minimize your own solution / use language solutions for these problems.

Is there any pre-existing function in PowerShell for this purpose or any recommended way to approximate it; or is the only option to use a custom 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 ?
        })
    }
}

Special Character Information:

+4
1

, :

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

:

test`[1`].txt

: https://msdn.microsoft.com/en-us/library/system.management.automation.wildcardpattern.escape(v=vs.85).aspx

+5

Source: https://habr.com/ru/post/1685024/


All Articles