Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell with Robocopy and Arguments Passing

I'm trying to write a script that uses robocopy. If I were just doing this manually, my command would be:

robocopy c:\hold\test1 c:\hold\test2 test.txt /NJH /NJS

BUT, when I do this from powershell, like:

$source = "C:\hold\first test"
$destination = "C:\hold\second test"
$robocopyOptions = " /NJH /NJS "
$fileList = "test.txt"

robocopy $source $destination $fileLIst $robocopyOptions

I get:

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

  Started : Fri Apr 10 09:20:03 2015

   Source - C:\hold\first test\
     Dest - C:\hold\second test\

    Files : test.txt

  Options : /COPY:DAT /R:1000000 /W:30

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

ERROR : Invalid Parameter #4 : " /NJH /NJS "

However, if I change the robocopy command to

robocopy $source $destination $fileLIst  /NJH /NJS 

everything runs successfully.

So, my question is, how can I pass a string as my robocopy command options (and, in a larger sense, do the same for any given external command)

like image 270
weloytty Avatar asked Apr 10 '15 13:04

weloytty


1 Answers

Use the arrays, Luke. If you specify an array of values, PowerShell will automatically expand them into separate parameters. In my experience, this is the most reliable method. And it doesn't require you to mess with the Start-Process cmdlet, which is in my opinion is overkill for such tasks.

This trick is from the best article I've seen on the PowerShell behavior towards external executables: PowerShell and external commands done right.

Example:

$source = 'C:\hold\first test'
$destination = 'C:\hold\second test'
$robocopyOptions = @('/NJH', '/NJS')
$fileList = 'test.txt'

$CmdLine = @($source, $destination, $fileList) + $robocopyOptions
& 'robocopy.exe' $CmdLine
like image 163
beatcracker Avatar answered Oct 21 '22 04:10

beatcracker