【发布时间】:2019-01-11 22:16:46
【问题描述】:
我正在尝试构建脚本,以便它可以在任何目录中运行,用户只需更改$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 中没有双反斜杠:
Move-Item : 找不到路径 'C:\Scripts\Script_Temp\Folder1\Duplicates\C:\Scripts\Script_Temp\Folder1\Duplicates\Test File 01.txt',因为它不存在。
带有双反斜杠,$location 中的 ( 或 ) 之前没有
Move-Item : 找不到路径 'C:\Scripts\Script_Temp(1)\Folder1\Duplicates\C:\Scripts\Script_Temp(1)\Folder1\Duplicates\Test File 02.txt',因为它不存在.
$location 中的 () 前带有双反斜杠和 \
Move-Item : 找不到路径 'C:\Scripts\Script_Temp(1)\Folder2\Test File 03.txt',因为它不存在。
【问题讨论】:
标签: powershell