I have Powershell v5 running in Windows 10 64Bit OS.
And I also have a nice trick to make the paths with square brackets compatible to be read by Powershell by escaping with tilde signs like $Path.Replace('[','
[' ).Replace(']',']')
, so intuitively I thought, why not make it a function like below for the same:
Function GetEscapedPath($Path) {
Return $Path.Replace('[','`[' ).Replace(']','`]')
}
Now I want to use this function return value as input to Remove-Item
function or any File-fullpath based functions for that matter, but this doesn't work:
Remove-Item GetEscapedPath $File.Fullname -WhatIf
$File
is variable from loop on Get-ChildItem
with Fullname
selected, but still the above line doesn't print anything.
How can I achieve what I want ?
Use (...)
, the grouping operator to pass the output from a command or expression as an argument to another command:
# Positionally binds to the -Path parameter, which interprets its argument
# as a wildcard pattern.
Remove-Item (GetEscapedPath $File.Fullname) -WhatIf
However, in your particular case, a function is not needed to escape a file-system path in order to treat it literally (verbatim): simply use the -LiteralPath
parameter of the various file-related cmdlets instead:
Remove-Item -LiteralPath $file.FullName -WhatIf
See this answer for more information.