具有Robocopy和参数传递的Powershell [英] Powershell with Robocopy and Arguments Passing
问题描述
我正在尝试编写使用 robocopy
的脚本。如果我只是手动执行此操作,则命令将是:
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
但是,当我从powershell进行操作时,例如:
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
我得到:
-------------------------------------------------------------------------------
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 "
但是,如果我将robocopy命令更改为
However, if I change the robocopy command to
robocopy $source $destination $fileLIst /NJH /NJS
一切都成功运行。
所以,我的问题是,如何将字符串作为我的robocopy命令选项传递(从更大的意义上讲,对任何给定的外部命令都执行相同操作)
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)
推荐答案
使用数组,卢克。如果指定值数组,PowerShell将自动将它们扩展为单独的参数。以我的经验,这是最可靠的方法。而且它不需要您弄乱 Start-Process
cmdlet,在我看来,对于这样的任务而言,cmdlet实在是太过分了。
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.
此技巧来自我在PowerShell方面针对外部可执行文件所见的最佳文章: PowerShell和外部命令正确完成。
This trick is from the best article I've seen on the PowerShell behavior towards external executables: PowerShell and external commands done right.
示例:
$source = 'C:\hold\first test'
$destination = 'C:\hold\second test'
$robocopyOptions = @('/NJH', '/NJS')
$fileList = 'test.txt'
$CmdLine = @($source, $destination, $fileList) + $robocopyOptions
& 'robocopy.exe' $CmdLine
这篇关于具有Robocopy和参数传递的Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!