[英]What is the way to escape colon in powershell?
I have the following powershell in a script file: 我在脚本文件中具有以下Powershell:
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. cd:找不到驱动器。 A drive with the name '\\C' does not exist. 名称为“ \\ C”的驱动器不存在。
I am guessing the colon I put in there to be at the end of C:\\
is causing problems. 我猜我在C:\\
末尾插入的冒号引起了问题。
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'. cd:找不到名称为“ C”的提供程序。
How can I escape the colon so that powershell just sees it as normal text? 我如何才能逃脱冒号,以便Powershell只能将其视为普通文本?
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). 注意:我看了这个问题: 在powershell中转义冒号,答案全是关于.NET的,它不能回答我的问题(尽管问题非常相似)。
You don't need to escape anything there. 您不需要在那里逃脱任何东西。 The APPDATA
environment variable already includes the drive, so you only need APPDATA
环境变量已经包含驱动器,因此您只需要
cd "${env:APPDATA}\Mozilla\Firefox\Profiles\*.default"
${env:systemdrive}:\\${env:APPDATA}
would create a path C:\\C:\\Users\\...
, which is indeed invalid. ${env:systemdrive}:\\${env:APPDATA}
将创建路径C:\\C:\\Users\\...
,这实际上是无效的。
If you write-host
those environmental variables, you'll see that: 如果您write-host
这些环境变量,您将看到:
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: 因此,您当前的尝试扩展为C:C:\\Users\\****\\AppData\\Roaming\\...
因此,您所需要的只是命令:
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. 我有一个建议,也是我认为的最佳实践,它是在您处理路径时都使用Join-Path
,因此您不必担心尾随或开始使用路径分隔符。
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. 所有这些都是可以接受的,并且我倾向于在自己的脚本中使用d3
版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.