【问题标题】:Get the current working directory or any directory with "/" instead of "\" in powershell script在powershell脚本中获取当前工作目录或任何带有“/”而不是“\”的目录
【发布时间】:2021-07-29 01:06:18
【问题描述】:

为了将当前工作目录地址传递给程序。我需要提供由正斜杠/ 分隔的目录路径。该程序不接受包含反斜杠的字符串。

目前,pwd-Command 提供以下功能: C:\testdir1\testdir2

我想要以下字符串: C:/testdir1/testdir2

有没有一种简单的方法可以在 powershell 脚本中转换这个目录地址?

提前谢谢你。

【问题讨论】:

  • 是什么引发了这个问题?

标签: powershell pwd


【解决方案1】:

使用-replace operator[1] 执行(总是全局的)字符串替换(因为它是基于regex,所以必须将逐字的\ 转义为\\); automatic $PWD variable 包含 PowerShell 会话的当前 位置(如果底层 providerFileSystem 提供程序,则它是一个 目录):

$PWD -replace '\\', '/'

如果您想确保生成的路径是文件系统本机路径(不基于 PowerShell-only 驱动器):

$PWD.ProviderPath -replace '\\', '/'

如果当前位置有可能来自文件系统以外的提供者(例如,基于注册表的驱动器,例如 HKLM:)。

(Get-Location -PSProvider FileSystem).ProviderPath -replace '\\', '/'

[1] 在这个简单的案例中,调用 [string] 类型的 .Replace() method 是一种替代方法,但 -replace 运算符更符合 PowerShell 的习惯并提供卓越的功能。 This answer 对比两者。

【讨论】:

    【解决方案2】:

    快速的代码,但似乎按预期工作

    # Original path
    $Path = "C:\testdir1\testdir2"
    Write-Host "Original Path is:" $Path
    #Replace \ by /
    $Changed = $Path -replace '\\', '/'
    Write-Host "changed path:" $Changed
    

    输出

    Original Path is: C:\testdir1\testdir2
    changed path: C:/testdir1/testdir2
    

    【讨论】: