2

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 ?

Vicky Dev
  • 1,893
  • 2
  • 27
  • 62
  • I'm not sure the function you've written is required. What happens if you run `Remove-Item $File -WhatIf`? – mjsqu Sep 24 '20 at 23:19
  • Well `Remove-Item` by it's definition needs `Fullpath` of file to be able to remove it, and the `$File` I got from the loop of `Get-ChildItem` is file object in which I can select parameters like `Name`,`Fullname`,`Length` etc. So that's why to convert the fullpath from get-childitem to escaped path, I have written that function – Vicky Dev Sep 24 '20 at 23:21
  • 1
    Ah, now I've tried it, something about square brackets confuses `Remove-Item`. Does `Remove-Item (getEscapedPath $File.Fullname) -WhatIf` work? – mjsqu Sep 24 '20 at 23:23
  • On point, the parenthesis did work, can you format this in answer with some extra info as much as possible ? Thanks a lot btw – Vicky Dev Sep 24 '20 at 23:25

1 Answers1

3

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775