1

我有以下结构:

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

在我的 Powershell file.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.
4

2 回答 2

3

你选择了误导性的变量名,掉进了你自己挖的坑。

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

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

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

但是,此指令使用$Folder1and$Folder3就好像它们包含文件夹路径(它们不包含)。

最重要的是,您的代码将失败,因为Compare-Object -Property Name, Length总是会产生web_rollback.config作为侧面指示器的结果=>(因为即使文件大小不是,项目的名称也不同),并且不存在具有该名称的C:\one文件C:\twoC:\one.

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

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

$config   = "C:\one\web.config"
$rollback = "C:\two\web_rollback.config"
$target   = Join-Path "C:\three" (Get-Item $config).Name

if ([IO.File]::ReadAllText($config) -ne [IO.File]::ReadAllText($rollback)) {
  Copy-Item $rollback -Destination $target -Force
}
于 2013-09-20T10:30:00.377 回答
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)"

???

于 2013-09-20T07:10:00.447 回答