Powershell 将参数传递给嵌套在 Start-Job 中的 robocopy

Powershell pass arguments to robocopy nested in a Start-Job

经过大量的头痛之后,我几乎可以正常工作了。

问题:在 error/output 中,Robocopy 似乎将 $args[4](参考:$sourcePath)视为范围内的每一个 IP,而不仅仅是一个对象。

我假设其余的语法是正确的,因为如果我将 $ip = 101..119 | foreach { "192.168.1.$_" } 切换到 $ip = "192.168.1.101" 一切正常。

Robocopy 将 $ip 范围内的所有 IP 地址转储到控制台源中。我在这里做错了什么?

#####################################################
#Purpose: to ping an IP range of network locations in a loop until successful. When successful, copy new files from source onto storage.
#Each ping and transfer needs to be ran individually and simultaneously due to time constraints.
#####################################################

#define the IP range, source path & credentials, and storage path
$ip = 101..119 | foreach { "192.168.1.$_" } 
#$ip = "192.168.1.101"  #everything works if I comment above and uncomment here
$source = "\$ip"
$sourcePath = "$source\admin\" 
$dest = "C:\Storage\"
$destFull = "$dest$ip\"
$username = "user"
$password = "password"

#This is how to test connection. Once returns TRUE, then copy new files only from source to destination.
#copy all subdirectories & files in restartable mode

foreach ($src in $ip){
Start-Job -ScriptBlock {
   DO {$ping = Test-Connection $args[0] -BufferSize 16 -Count 4 -quiet} 
   until ($ping)
    net use \$args[1] $args[2] /USER:$args[3]
    robocopy $args[4] $args[5] /E /Z   
    } -ArgumentList $src, $source, $password, $username, $sourcePath, $destFull  -Name "$src"  #pass arguments to Start-Job's scriptblock
}

#get all jobs in session, supress command prompt until all jobs are complete. Then once complete, get the results.

Get-Job | Wait-Job 
Get-Job | Receive-Job

在您创建 $source 时,$ip 是一个数组,因此 $source 最终是一个非常长的字符串,由所有项目连接而成:

\192.168.1.101 192.168.1.102 192.168.1.103 192.168.1.104 ...

您可以自己查看,只需 运行 这两行,然后检查 $source:

的内容
$ip = 101..119 | foreach { "192.168.1.$_" }
$source = "\$ip"

这对 $sourcePath 有 knock-on 影响,它在调用 RoboCopy 时用作 $args[4]。您应该在 foreach 循环中构建您的路径,您可以在其中访问 $ip 集合中的每个 IP 地址($src)。

一些sources/etc。是不同的,但这只是由于测试环境。我决定使用 [io.path] 作为路径,因为我 运行 在定义变量时遇到 $args 的问题。

感谢 boxdog 提供的上述帮助。我完全忽略了这个事实。

$ScriptBlock = {

$source = [io.path]::Combine('\',$args[0])
$sourcePath = [io.path]::Combine('\',$args[0],'c$','admin\')
$dest = "C:\Storage\"
$destFull = [io.path]::Combine($dest,$args[0])

    DO {$ping = Test-Connection $args[0] -BufferSize 16 -Count 1 -quiet} 
    until ($ping)
        net use $source password /USER:user
        robocopy $sourcePath $destFull /E /Z   
}

$ip = 101..119 | foreach { "192.168.1.$_" }

foreach ($dvr in $ip){
Start-Job $ScriptBlock -ArgumentList $dvr
}

Get-Job | Wait-Job 
Get-Job | Receive-Job