1

I am trying to copy files from local machines to remote location. When i run the script it will check folder exist on remote location. If it is not created then it will create a directory. Once directory created it will copy all files from source location.

My script is working fine for that but i want output on screen what files are being copied.

Below are the code that is working fine to copy the files but it is not showing file names being copied.

$machine = $env:COMPUTERNAME

$dest= "\\192.168.1.5\d$\test\"

$source = "C:\windows\logs\"

$newPath = Join-Path $dest -childpath $machine

 if(!(Test-Path -Path $newPath )){
        New-Item $newPath -type directory
             foreach ($file in $source)
             {
                    write-host "Copying Files: " $file  -foregroundcolor DarkGreen -backgroundcolor white
                    Copy-Item $file -Destination $newPath -force

             }

        }else{
        foreach ($file in $source)
        {
        write-host "Copying Files: " $file  -foregroundcolor DarkGreen -backgroundcolor white
    Copy-Item -Path $file -Destination $newPath -recurse -Force

        }   
    }
2
  • There is a commandlet Write-Progress which should come in handy. Beneath that: Is there a reason why you have the same copy-code inside the if-block and inside the else-block? Why not just go for an if to ensure that the folder exists and copy beneath all that in a single operation? Commented Mar 17, 2016 at 8:43
  • this script is still in development phase. If folder not exist then it will create folder and copy the files. So, i put one copy files command under test path and another one without test path. Commented Mar 17, 2016 at 8:45

1 Answer 1

3

This code should work. I altered the if-statement so you don't have redundant code and adapted $source, so the foreach will work with your write-progress

$machine = $env:COMPUTERNAME

$dest= "\\192.168.1.5\d$\test\"

$sourcePath = 'C:\windows\logs\'

$source = Get-ChildItem $sourcePath

$newPath = Join-Path $dest -childpath $machine

if(!(Test-Path -Path $newPath )){
    New-Item $newPath -type directory
}

$count = $source.count
$operation = 0

foreach ($file in $source)
{
    $operation++
    write-host 'Copying File: ' $file  -foregroundcolor DarkGreen -backgroundcolor white
    Write-Progress -Activity 'Copying data' -Status 'Progress' -PercentComplete ($operation/$count*100)
    Copy-Item $file -Destination $newPath -force

}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. Voted up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.