Powershell:删除目录名称中的大引号

问题描述 投票:0回答:2

这应该非常简单,但我不明白为什么它不起作用。我正在尝试将大引号 (',“,”) 替换为常规引号 (',")。正在读入的目录名称字符串中的引号。我不想重命名目录。我只想更改字符串以进行进一步处理。

为了测试这一点,我创建了以下文件夹:

D:\Test
    Double Left “ Quote
    Double Right ” Quote
    Single ’ Quote

为了测试,我有这个代码:

count = 0

Get-ChildItem -LiteralPath 'D:\test' -Directory |
ForEach-Object {

    $name = $_.Name

    Write-Host $name

    if ($name.Contains("’")) {
        Write-Host "Single Curly Quote: $name"
        $name = $name -replace("’","'")
        Write-Host "Fixed: $name"
    }
    if ($name.Contains('“')) {
        Write-Host "Double Left Curly Quote: $name"
        $name = $name -replace('“','"')
        Write-Host "Fixed: $name"
    }
    if ($name.Contains('”')) {
        Write-Host "Single Right Curly Quote: $name"
        $name = $name -replace('”','"')
        Write-Host "Fixed: $name"
    }

    $count += 1

}

Write-Host $count

但是当我运行它时,我得到了这个结果:

C:\Users\brian.w.williams> . 'C:\Users\brian.w.williams\Desktop\Test.ps1'
Double Left “ Quote
Double Right ” Quote
Single ’ Quote
3

它没有看到有问题的大引号。

如果我直接替换,我会得到相同的结果。我输入额外的代码只是为了尝试弄清楚发生了什么。

有什么建议吗?

代码在 Windows 10 x64 计算机上的 Powershell 7 中运行。

我希望将弯引号替换为常规直引号。

如果我创建一个包含大引号的字符串变量而不是使用目录名称值,则代码可以完美运行。

string powershell replace
2个回答
0
投票

您可以使用正则表达式模式来匹配这 3 个智能引号,并使用 用脚本块替换,您可以将它们替换为存储在哈希表中的正确值,例如:

$map = @{
    "’" = "'"
    '”' = '"'
    '“' = '"'
}

@'
Double Left “ Quote
Double Right ” Quote
Single ’ Quote
'@ -replace '[\u201d\u2019\u201c]', { $map[$_.Value] }

您的代码可能是:

$map = @{
    "’" = "'"
    '”' = '"'
    '“' = '"'
}

Get-ChildItem -LiteralPath 'D:\test' -Directory | ForEach-Object {
    $_.Name -replace '[\u201d\u2019\u201c]', { $map[$_.Value] }
}

0
投票

由于单卷曲和双卷曲智能引号有更多变体,我将在顶部使用一个小辅助函数:

function Convert-SmartQuotes {
    param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [string]$Text
    )

    # return the given string with all curly quotes replaced by straight ones
    $Text -replace '[\u201C\u201D\u201E\u201F\u2033\u2036]', '"' -replace "[\u2018\u2019\u201A\u201B\u2032\u2035]", "'"
}                   

那么你的代码可能是:

Get-ChildItem -LiteralPath 'D:\test' -Directory | ForEach-Object {
    Convert-SmartQuotes $_.Name
}
© www.soinside.com 2019 - 2024. All rights reserved.