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”,因为它不存在。
解决方案
您看到的问题是您在 RegEx(正则表达式)匹配和替换中使用了非转义字符串。运算符对您构建的-replace
字符串执行 RegEx 匹配,例如这里:
$filestomove = $hash1.Path[$i]-replace ("$folder1\\Duplicates\\",'')
在正则表达式中有一些保留字符,例如圆括号、方括号和反斜杠。您已经手动考虑了反斜杠,但其他字符可能会干扰您的匹配。更好的方法是使用该[regex]::escape()
方法。像这样的东西:
$filestomove = $hash1.Path[$i] -replace [regex]::escape("$folder1\Duplicates\"),''
推荐阅读
- python - 使用for循环将df数据插入sqlite
- c++ - 如果一个线程失败,我如何使用 std::barrier 让其他线程返回?
- git - 如何在 git-patch 中找到问题?
- java - 归零 II
- python - 使用 Python 在数据框列中设置标志和消息
- javascript - 通过表单为用户更新配置文件
- angular - Angular Routerlink 不工作,我做对了
- sql - Oracle SQL:JSON_TABLE;获取数组的大小
- laravel - Laravel 8 - 禁用特定包的迁移
- php - Mysql Prepared Statement Fails - 带有多个语句的 sql 查询