【问题标题】:Dot Slash and Backslashes in PowerShell Cross-PlatformPowerShell 跨平台中的点斜杠和反斜杠
【发布时间】:2019-04-10 08:11:10
【问题描述】:

我正在编写 PowerShell 脚本,它使用 & .\other\script.ps1 调用其他 PowerShell 脚本,但我认为反斜杠 \ 是 Windows 的东西,我希望我的脚本能够跨平台工作。

我注意到 Windows 中的 PowerShell 确实接受 & ./other/script.ps1 但这可能是偶然的。 PowerShell 是否总是将我的反斜杠翻译成主机平台?

在 PowerShell 中跨平台处理路径分隔符的最佳方法是什么?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    根据我的经验,Windows PowerShell 很乐意接受 \/ 作为路径分隔符,因此跨平台的一种方法是始终使用 /

    您也可以使用Path cmdlet 为您处理构建路径,例如:

    Join-Path -Path $Pwd -ChildPath (Join-Path -Path 'Other' -ChildPath 'script.ps1')
    

    或者获取当前目录下文件的路径:

    Resolve-Path test.txt
    

    路径 cmdlet:

    ~> get-command *-path* | Select Name
    
    Name
    ----
    Convert-Path
    Join-Path
    Resolve-Path
    Split-Path
    Test-Path
    

    【讨论】:

    【解决方案2】:

    我没有足够的信誉来为@mark-wragg 接受的答案添加评论,但我只想指出我开始仅在跨平台脚本等中使用正斜杠并遇到符号链接问题。

    例如,运行

    new-item -itemtype SymbolicLink -path TestScript8.ps1 -target ./TestScript.ps1
    

    您将无法在 Windows 上的 VS Code 中打开 TestScript8.ps1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      • 2013-11-14
      • 2021-05-29
      相关资源
      最近更新 更多