powershellpathread-host

Escape all backslashes from a Read-Host input string


I'm building a simple tool to compile C++ and C# code faster, and with compiling, you generally paste in the path of your file/folder when you cd into the directory. The problem with this is that the path that is pasted in usually includes backslashes. These are in turn read as escape characters to the terminal, and produces multiple errors going on about unknown escape sequences. So what I need to know is, is there some way of escaping the backslashes found in the path, or in other terms, "safely" read the string?

I've tried a few different things, and none of them work. Like in other languages, find and replace does nothing, it just causes more errors.


Solution

  • The [regex] class has an Escape method:

    PS > $path = Read-Host "Path"
    Path: C:\My Folder\subfolder\file.txt
    PS > [regex]::Escape($path)
    C:\\My\ Folder\\subfolder\\file\.txt