简体   繁体   中英

What is the way to escape colon in powershell?

I have the following powershell in a script file:

cd "$env:systemdrive:\$env:APPDATA\Mozilla\Firefox\Profiles\*.default"

Expanded, I want this to do something similar to this:

cd "C:\Users\Bob\AppData\Roaming\Mozilla\Firefox\Profiles\f1wkii3l.default"

But when I run it, I get:

cd : Cannot find drive. A drive with the name '\\C' does not exist.

I am guessing the colon I put in there to be at the end of C:\\ is causing problems.

I tried:

cd "${env:systemdrive}:\${env:APPDATA}\Mozilla\Firefox\Profiles\*.default"

But then I get the error:

cd : Cannot find a provider with the name 'C'.

How can I escape the colon so that powershell just sees it as normal text?

NOTE: I looked at this question: Escaping a colon in powershell and the answer is all about .NET and does not answer my question (though the question is very similar).

You don't need to escape anything there. The APPDATA environment variable already includes the drive, so you only need

cd "${env:APPDATA}\Mozilla\Firefox\Profiles\*.default"

${env:systemdrive}:\\${env:APPDATA} would create a path C:\\C:\\Users\\... , which is indeed invalid.

If you write-host those environmental variables, you'll see that:

PS C:\>write-host $env:systemdrive
C:

PS C:\>write-host $env:appdata
C:\Users\****\AppData\Roaming

So your current attempt expands to C:C:\\Users\\****\\AppData\\Roaming\\... So all you need is the command:

cd "$env:Appdata\Mozilla\Firefox\Profiles\*.default"

Other answers are valid for troubleshooting and for your task at hand. One suggestion I have, and what I consider a best-practice, is making use of Join-Path anytime you are dealing with paths so you don't have to worry about trailing or beginning path separators.

This example

$d1 = "${env:APPDATA}\Mozilla\Firefox\Profiles\*.default"
$d2 = Join-Path ${env:APPDATA} "\Mozilla\Firefox\Profiles\*.default"
$d3 = Join-Path ${env:APPDATA} "Mozilla\Firefox\Profiles\*.default"
Write-Output "d1 = '$d1'"
Write-Output "d2 = '$d2'"
Write-Output "d3 = '$d3'"

Produces

d1 = 'C:\Users\xxx\AppData\Roaming\Mozilla\Firefox\Profiles\*.default'
d2 = 'C:\Users\xxx\AppData\Roaming\Mozilla\Firefox\Profiles\*.default'
d3 = 'C:\Users\xxx\AppData\Roaming\Mozilla\Firefox\Profiles\*.default'

All are acceptable, and I would tend to use the d3 version in my own scripts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM