PowerShell将目录和副本与另一个目录进行比较

时间:2013-09-20 04:56:46

标签: powershell powershell-ise

我有以下结构:

C:\one\web.config
C:\two\web_rollback.config
C:\three\    ( this is empty , it is where I want to copy to

在我的Powershell文件.ps1中,我有以下代码:

$Folder1 = Get-childitem  "C:\one\"
$Folder2 = Get-childitem  "C:\two\"
$Folder3 = Get-childItem  "C:\three\"

Compare-Object $Folder1 $Folder2 -Property Name, Length | Where-Object {$_.SideIndicator -eq "=>"} | ForEach-Object {
    Copy-Item "$Folder1\$($_.name)" -Destination $Folder3 -Force}

但是,我为什么会出现以下错误?

PS C:\windows\system32> C:\pscripts\compareobject.ps1
Copy-Item : Cannot find path 'C:\windows\system32\Web.config\Web_Rollback.config' because it does not exist.

2 个答案:

答案 0 :(得分:3)

你选择了误导性的变量名称并陷入了你自己挖掘的洞中。

$Folder1 = Get-childitem  "C:\one\"
$Folder2 = Get-childitem  "C:\two\"
$Folder3 = Get-childItem  "C:\three\"

这些说明将使用给定文件夹的子项填充变量。

Copy-Item "$Folder1\$($_.name)" -Destination $Folder3 -Force

但是,此说明使用$Folder1$Folder3,就好像它们包含文件夹路径(它们没有)。

最重要的是,您的代码将失败,因为Compare-Object -Property Name, Length将始终生成web_rollback.config作为旁边指示符=>的结果(因为{{1}中的项目名称即使文件大小不是这样,{}和C:\one也不同,C:\two中不存在具有该名称的文件。

您的方法的另一个缺陷是,您依靠大小差异来检测两个文件之间的更改。如果值已从C:\one更改为0,则此检查将失败。

将您的代码更改为以下内容:

1

答案 1 :(得分:0)

如果删除文件夹路径中的尾部斜杠,会发生什么?

$Folder1 = Get-childitem  "C:\one"
$Folder2 = Get-childitem  "C:\two"
$Folder3 = Get-childItem  "C:\three"

因为如果扩展变量$ Folder1,你会得到

Copy-Item "$Folder1\$($_.name)"

Copy-Item "C:\One\\$($_.name)"

···

相关问题