文件夹名称中带括号时脚本失败

时间:2019-01-11 22:16:47

标签: powershell

我正在尝试构建脚本,以便可以在任何目录中运行脚本,而用户仅需更改$location(或在以后提示时选择一个),而所有其他路径均由变量设置:

$location = "C:\\Scripts\\Script_Temp\(1\)"

Set-Location $location

$folder1 = "$location\\Folder1"
$folder2 = "$location\\Folder2"

$fol1_cont = Get-ChildItem "$folder1" -File
$fol2_cont = Get-ChildItem "$folder2" -File

$dupfolsexist = (Test-Path -LiteralPath $folder1\\Duplicates) -and (Test-Path -LiteralPath $folder2\\Duplicates)
$duplicates = (Compare-Object -Property Name -ReferenceObject $fol1_cont -DifferenceObject $fol2_cont -IncludeEqual -ExcludeDifferent)

cls;sleep 1

if (!($duplicates)) { Write-Host "no duplicates" }

if ($duplicates) {
    if (!($dupfolsexist)) {
        New-Item -ItemType Directory -Path "$folder1\\Duplicates\\Hashes Match", "$folder2\\Duplicates\\Hashes Match" | Out-Null
    }

    foreach ($file in $duplicates) {
        Move-Item $folder1\\$($file.Name) -Destination $folder1\\Duplicates
        Move-Item $folder2\\$($file.Name) -Destination $folder2\\Duplicates
    }
}
$hash1 = Get-FileHash -Path $folder1\\Duplicates\\*.*
$hash2 = Get-FileHash -Path $folder2\\Duplicates\\*.*

for ($i=0; $i -lt $hash1.Count; $i++) {
    if ($hash1.Hash[$i] -eq $hash2.Hash[$i]) {
        $filestomove = $hash1.Path[$i]-replace ("$folder1\\Duplicates\\",'')
        Write-Host "File hashes are the same "-NoNewline -ForegroundColor Green;
        Write-Host ">> " -NoNewline -ForegroundColor Yellow;
        $filestomove;
        Move-Item $folder1\\Duplicates\\$filestomove -Destination "$folder1\\Duplicates\\Hashes Match";
        Move-Item $folder2\\Duplicates\\$filestomove -Destination "$folder2\\Duplicates\\Hashes Match"
    } else {
        Write-Host "File hashes are different " -NoNewline -ForegroundColor Red;
        Write-Host ">> " -NoNewline -ForegroundColor Yellow;
        $hash1.Path[$i] -replace ("$folder1\\Duplicates\\",'')
    }
}

可能有一种更好的方法来完成整件事!!但是现在,我只是想找到一种解决办法,在其中文件夹名称包含(和)。当文件夹名称中没有括号时,脚本将按预期工作。

我遇到的错误:

$location中没有双反斜杠:

  

移动项:找不到路径'C:\ Scripts \ Script_Temp \ Folder1 \ Duplicates \ C:\ Scripts \ Script_Temp \ Folder1 \ Duplicates \ Test File 01.txt',因为它不存在。

带有双反斜杠,$location中的(或)之前没有

  

移动项:找不到路径'C:\ Scripts \ Script_Temp(1)\ Folder1 \ Duplicates \ C:\ Scripts \ Script_Temp(1)\ Folder1 \ Duplicates \ Test File 02.txt',因为它不存在

$location中带有双反斜杠和\之前()的

  

移动项:找不到路径'C:\ Scripts \ Script_Temp(1)\ Folder2 \ Test File 03.txt',因为它不存在。

1 个答案:

答案 0 :(得分:1)

您看到的问题是您在RegEx(正则表达式)匹配和替换中使用了非转义字符串。 -replace运算符对您构建的字符串执行RegEx匹配,例如:

$filestomove = $hash1.Path[$i]-replace ("$folder1\\Duplicates\\",'')

在正则表达式中,有一些保留字符,例如括号,方括号和反斜杠。您已经手动计算了反斜杠,但是其他字符可能会使您的匹配混乱。更好的方法是使用[regex]::escape()方法。像这样:

$filestomove = $hash1.Path[$i] -replace [regex]::escape("$folder1\Duplicates\"),''