views:

708

answers:

1

I'm trying to get PowerShell to copy files from a remote computer (on which I have admin rights through AD) to the local computer. It fails in the strangest place. Here's a snippet of the script:

    $configs = Get-ChildItem -Recurse -ErrorAction SilentlyContinue -Filter "*.config" $serverUNCPath 
foreach($config in $configs){
 $config_target_dir = $dest.Path + $config.Directory.FullName.Replace($serverUNCPath,"")
 if(Test-Path -Path $config_target_dir){
  Copy-Item $config -Destination  $config_target_dir
 }
}

It fails with the message

Cannot find path 'D:\ServerDeploy\TestMachine1\website\web.config' because it does not exist.
At :line:39 char:12
+     Copy-Item <<<<  $config -Destination  $config_target_dir

The path D:\ServerDeploy\TestMachine1\website exists. I'm going mad over this.

What can I do to fix it?

+3  A: 

Eeeeh.... OK?

If I replaced the line

 Copy-Item $config -Destination  $config_target_dir

with

 Copy-Item $config.FullName $config_target_dir

it suddenly magically worked....

What gives?

AndreasKnudsen
Don't forget that you are dealing with actual objects in PS. Generally speaking when you hand an object to a cmdlet the cmdlets are pretty good at choosing the right property to work with. In this case you are handing a System.IO.FileSystemInfo.FileInfo object to the Copy-Item cmdlet. I think the cmdlet is probably defaulting to using the .Name property and that is not enough information for the copy to work. When you explicitly give the .FullName property to the cmdlet, it now has the information that it needs.
EBGreen
hmm, that would explain the error, but *not* the crappy errormessage. Why report as an error that the target location does not exist?
AndreasKnudsen
What's the current working directory at the time Copy-Item is executed? My guess is it's D:\ServerDeploy\TestMachine1\website. Like EBGreen said, Copy is treating $config as a relative path. Thus, it thinks that (join-path (pwd) $config.Name) *is* the full source location.
Richard Berg