【问题标题】:How to handle backslash character in PowerShell -replace string operations?如何在 PowerShell -replace 字符串操作中处理反斜杠字符?
【发布时间】:2016-08-28 08:30:47
【问题描述】:

我正在使用 -replace 更改从源到目标的路径。但是我不确定如何处理 \ 字符。例如:

$source = "\\somedir"
$dest = "\\anotherdir"

$test = "\\somedir\somefile"

$destfile = $test -replace $source, $dest

此操作后,$destfile 被设置为

"\\\anotherdir\somefile"

避免结果中出现三个反斜杠的正确方法是什么?

【问题讨论】:

    标签: powershell replace backslash


    【解决方案1】:

    我在遇到 Test-PathGet-Item 无法使用带空格的 UNC 路径后来到这里。部分问题已解决here,另一部分解决如下:

    $OrginalPath = "\\Hostname\some\path with spaces"
    $LiteralPath = $OriginalPath -replace "^\\{2}", "\\?\UNC\"
    

    结果: \\?\UNC\Hostname\some\path with spaces

    为了完整起见,将其放入 Test-Path 会返回 true(假设路径确实存在)。正如@Sage Pourpre 所说,需要使用-LiteralPath

    Test-Path -LiteralPath $LiteralPath 要么 Get-Item -LiteralPath $LiteralPath

    replacement operator -replace 使用正则表达式。

    • ^ 表示字符串的开头。
    • \ 是转义字符,因此我们使用 \ 转义 \
    • 由于我们有两个\,我们告诉正则表达式使用{2} 查找\ 的两次出现。

    您可以按照@Richard 所说的使用四个\,而不是使用{2}。一个逃脱另一个。

    试试看here

    【讨论】:

      【解决方案2】:

      尝试以下方法:

      $source = "\\\\somedir"
      

      替换时您只匹配了 1 个反斜杠,这在路径的开头为您提供了三个 \\\

      反斜杠是regex 转义字符,因此\\ 将被视为仅匹配一个\ 而不是两个\\。由于第一个反斜杠是转义字符,不用于匹配。

      处理反斜杠的另一种方法是使用regex 转义函数。

      $source = [regex]::escape('\\somedir')
      

      【讨论】:

      • [regex]::Escape() 是更安全的解决方案,因为它也会处理其他特殊字符(如 + 或括号)。
      • 谢谢,虽然我使用了正则表达式解决方案,但它仍然有效
      • [regex]::Escape() 对于包含 '.' 的路径无法正常工作
      猜你喜欢
      • 2015-11-10
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      相关资源
      最近更新 更多