场景:文件夹1中的*.pdf文件夹2中的*.rtf,两个文件夹的文件名相同,但扩展名不同。需要比较这两个文件夹,并仅将*.rtf从Folder2复制到Folder3。
脚本:
Compare-Object (Get-childitem $Folder1 -Recurse | foreach-object {$_.basename}) (Get-childitem $Folder2 -Recurse | foreach-object {$_.basename}) -Property RelativePath, Name, Length |
Sort RelativePath, Name, Length -desc | % {
if ($file -ne $_.RelativePath)
{ $_ }
$file = $_.RelativePath
} | Where-Object {$_.SideIndicator -eq "=>"} | ForEach-Object {Copy-Item ("$Folder2" + $file) -Destination ("$Folder3" + $file) -Force}
通常情况下,您应该有一个问题。我不确定你从哪里得到属性RelativePath
,所以我介绍了这个应该很容易理解。我本可以把它变成一个单行命令,但同样,它更可读。
$Folder1 = "C:tempfolder1"
$Folder2 = "C:tempfolder2"
$Folder3 = "C:tempfolder3"
$Folder1Contents = Get-childitem $Folder1 -Recurse -Include *.pdf
$Folder2Contents = Get-childitem $Folder2 -Recurse -Include *.rtf
Compare-Object $Folder1Contents $Folder2Contents -Property BaseName -PassThru | Where-Object{$_.SideIndicator -eq "=>"} | Move-Item -Destination $Folder3 -Force -WhatIf
将$Folder1
中的pdf文件与$Folder2
中的rtf文件进行比较。如果$Folder2
中有.rtf文件,则它将被移动到$Folder3
。-Force
将覆盖该目录中预先存在的文件,因此在完成测试后删除-WhatIf
。
最终结果:我添加了一个用于日志记录的Transcript和if/elseif语句。双重比较对象只是为了使比较结果显示在日志中。谢谢你的帮助马特,你帮我省去了几个小时的头痛。
$Folder1 = "C:tempfolder1"
$Folder2 = "C:tempfolder2"
$Folder3 = "C:tempfolder3"
$log = "C:logscompare.log"
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
$OutputFileLocation = "$log"
Start-Transcript -path $OutputFileLocation -append
$folder1contents = Get-childitem $folder1 -Recurse -Include *.pdf
$folder2contents = Get-childitem $folder1 -Recurse -Include *.rtf
$filecheck = "C:tempfolder1*.pdf"
$filepresent = Test-Path $filecheck
if ($filepresent -eq $false)
{
Write-host "No Files To Compare"
}
elseif ($filepresent -eq $true)
{
Compare-Object $folder1contents $folder2contents -Property BaseName -PassThru
Compare-Object $folder1contents $folder2contents -Property BaseName -PassThru | Where-Object{$_.SideIndicator -eq "=>"} | Copy-Item -Destination $folder3 -Force
}
stop-transcript