我的结构如下:
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.发布于 2013-09-20 10:30:00
你选择了误导变量的名字,然后掉进了你自己挖的洞里。
$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作为侧指示符=>的结果(因为C:\one和C:\two中的项的名称是不同的,即使文件大小不相同),而且C:\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-20 07:10:00
如果删除文件夹路径中的尾斜杠会发生什么?
$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)"?
https://stackoverflow.com/questions/18909070
复制相似问题