How to start Robocopy from a Powershell Script

4k views Asked by At

I am trying to transfer user data in the C:\ drive from a networked computer to the C:\ drive on the local computer. So I need to exclude all the System Folders and Hidden Folders.

This is what I have for my powershell script.

$asset = Read-Host "What is the Asset Number?"
$useraiu = Read-Host "What is the user's AIU?"

$source = "\\$asset\C$\"
$dest = "C:\Temp\Dest"

$excludedFolders = '_SMSTaskSequence','inetpub','Program Files','Program Files (x86)','Swsetup','Users','Windows','CCM','Notes'

$myFolders = Get-ChildItem  -Path "\\$asset\C$\" -Directory | where { $_ -notin $excludedFolders }

$myFolders | foreach { robocopy $_  $dest /S /Z /MT /XJD /XA:SH /log+:"\\server\path\path\%asset%-to-%computername%-Transfer-Log.log" /NP /FP /V /TEE}

Read-Host "Press ENTER to quit"

When I do a Write-Output $myFolders it displays the correct directories that I want to copy.

Looks like the robocopy function is using the local C:\ path as the source. The source should be \\$asset\C$\ the folders listed in $myFolders

Example. If this folder is on the old computer \\computername\C$\Userfolder-Pictures Use Robocopy to copy that folder to C:\Userfolder-Pictures on the local computer

I get this output from Robocopy after I run the script.

 Log File : \\server\path\path\%asset%-to-%computername%-Transfer-Log.log

-------------------------------------------------------------------------------
   ROBOCOPY     ::     Robust File Copy for Windows                              
-------------------------------------------------------------------------------

  Started : Mon Jun 08 11:11:28 2015

   Source : C:\WINDOWS\system32\Temp\
     Dest : C:\Temp\Dest\

    Files : *.*

  Options : *.* /V /FP /TEE /S /COPY:DAT /Z /NP /XJD /XA:SH /MT:8 /R:1000000 /W:30 

------------------------------------------------------------------------------

2015/06/08 11:11:28 ERROR 2 (0x00000002) Accessing Source Directory C:\WINDOWS\system32\Temp\
The system cannot find the file specified. 
1

There are 1 answers

5
Samuel Prout On BEST ANSWER

Adding Select-Object -ExpandProperty FullName will give you the full network path to the folders in an array of strings. Your foreach loop through $myFolders is currently looping through an array of DirectoryInfo objects instead.

$myFolders = Get-ChildItem  -Path "\\$asset\C$\" -Directory | where { $_ -notin $excludedFolders } | Select-Object -ExpandProperty FullName

Or, if you plan on using information from $myFolders other than FullName, you could change this line to use $_.FullName.

$myFolders | foreach { robocopy $_.FullName  $dest /S /Z /MT /XJD /XA:SH /log+:"\\server\path\path\%asset%-to-%computername%-Transfer-Log.log" /NP /FP /V /TEE}