过滤OneDrive上传的未知字符

时间:2018-04-02 06:20:53

标签: powershell onedrive

目前使用一个小的PowerShell脚本来检查文件结构中的非法字符,但我遇到了一个我不熟悉的字符。我需要修改代码以检测和替换此字符(或代表)的任何内容,但我无法在物理上键入字符,它只在文件资源管理器中查看时显示。该字符显示为方形子弹点,但如果我将其复制/粘贴到任何位置,它将更改为带问号的框。有人知道这个角色的alt代码吗?或者我可以使用另一条线来检测和替换它?

需要进入的代码如下:

function OneDrive-Check($Folder,[switch]$Fix){
    $Items = Get-ChildItem -Path $Folder -Recurse

    $UnsupportedChars = '[!&{}~#%]'

    foreach ($item in $items){
        filter Matches($UnsupportedChars){
        $item.Name | Select-String -AllMatches $UnsupportedChars |
        Select-Object -ExpandProperty Matches
        Select-Object -ExpandProperty Values
        }

        $newFileName = $item.Name
        Matches $UnsupportedChars | ForEach-Object {
            Write-Host "$($item.FullName) has the illegal character $($_.Value)" -ForegroundColor Red
            if ($_.Value -match "&") { $newFileName = ($newFileName -replace "&", "and") }
            if ($_.Value -match "{") { $newFileName = ($newFileName -replace "{", "(") }
            if ($_.Value -match "}") { $newFileName = ($newFileName -replace "}", ")") }
            if ($_.Value -match "~") { $newFileName = ($newFileName -replace "~", "-") }
            if ($_.Value -match "#") { $newFileName = ($newFileName -replace "#", "") }
            if ($_.Value -match "%") { $newFileName = ($newFileName -replace "%", "") }
            if ($_.Value -match "!") { $newFileName = ($newFileName -replace "!", "") }
         }
         if (($newFileName -ne $item.Name) -and ($Fix)){
            Rename-Item -LiteralPath $item.FullName -NewName ($newFileName)
            Write-Host "$($item.Name) has been changed to $newFileName" -ForegroundColor Green
         }
    }
}

角色的图像位于日期的任何一侧:

{{3}}

谢谢!

2 个答案:

答案 0 :(得分:0)

我不会尝试将非法字符与[string]匹配,而是尝试将非法字符识别为unicode字符代码。

首先,您的文件名如下:

$name = $item.FullName
$name[0..$name.Length] | % {
    "$_ = \u$(([int64]$_).ToString('X4'))"
}

所以你会得到实际的unicode charcodes:

a = \u0061
k = \u006B
o = \u006F
s = \u0073
...

然后根据指定为\u0000的unicode字符代码过滤/替换结果,作为unicode字符的十六进制代码,如:

$String -replace '\u005A\u0061\u007A', ''

在这里你可以找到一些关于实际unicode替换的很好的例子:

答案 1 :(得分:0)

更改系统代码页可能会使您无法编程过滤功能。试试chcp' windows命令行与良好的代码页。

  

https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/chcp

相关问题