场景:文件夹2中的Folder1 * .rtf中的* .pdf,两个文件夹具有相同的文件名但具有不同的扩展名。需要比较两个文件夹并仅复制等于=>的* .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}
答案 0 :(得分:1)
通常你应该有一个问题。我不知道你从哪里得到了财产RelativePath
,所以我提出这个应该很容易理解。我本可以将它变成一行命令,但同样,这更具可读性。
$Folder1 = "C:\temp\folder1"
$Folder2 = "C:\temp\folder2"
$Folder3 = "C:\temp\folder3"
$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
。
答案 1 :(得分:0)
最终结果:我添加了一个Transcript和if / elseif语句用于记录。双重比较对象只是比较结果将显示在日志中。谢谢你的帮助马特,你救了我几个小时的头痛。
$Folder1 = "C:\temp\folder1"
$Folder2 = "C:\temp\folder2"
$Folder3 = "C:\temp\folder3"
$log = "C:\logs\compare.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:\temp\folder1\*.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