Question

I have the following structure:

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

In my Powershell file.ps1 I have the following code:

$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}

HOWEVER, I get this error below WHY?

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.
Était-ce utile?

La solution

You chose misleading variable names and fell into the hole you dug yourself.

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

These instructions will fill the variables with the child items of the given folders.

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

This instruction, however, uses $Folder1 and $Folder3 as if they contained the folder path (which they don't).

On top of that, your code will fail, because Compare-Object -Property Name, Length will always produce web_rollback.config as the result for the side indicator => (since the names of the items in C:\one and C:\two are different even if the file sizes aren't), and no file with that name is present in C:\one.

Another flaw with your approach is that you're relying on a difference in size for detecting a change between the two files. This check will fail if for instance a value was changed from 0 to 1.

Change your code to something like this:

$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
}

Autres conseils

What happens if you remove the trailing slash in the folder path?

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

Because if you expanded the variable $Folder1 you would get

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

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

?????

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top