从foreach调用脚本

时间:2015-10-19 21:08:26

标签: powershell start-job

我需要一些帮助,或者建议我采取更好的方式来做我想做的事情。

我正在尝试复制一些事情,所以我有

$tests = @("test1", "test3", "test5")
$copy_1 = {
$source = "C:\Source\test1"
$Destination = "C:\Destination\test1"

Copy-Item $Source -Recurse -Destination $Destination -Container -Force
}

$copy_2 = {
$source = "C:\Source\test2"
$Destination = "C:\Destination\test2"

 Copy-Item $Source -Recurse -Destination $Destination -Container -Force
}

$copy_3 = {
$source = "C:\Source\test3"
$Destination = "C:\Destination\test3"

Copy-Item $Source -Recurse -Destination $Destination -Container -Force
}

$copy_4 = {
$source = "C:\Source\test4"
$Destination = "C:\Destination\test4"

Copy-Item $Source -Recurse -Destination $Destination -Container -Force
}

Foreach($i in $Tests)
{
    IF($i -eq "test1)
        {
          Start-Job -Name $i -Scriptblock {$($i)}
        }
}

....

这不会调用我的scriptblock。

      PSJobTypeName   State         HasMoreData     Location             Command                  

      BackgroundJob   Running       True            localhost            ($($i))  

如何调用$ test1块?

提前致谢。

1 个答案:

答案 0 :(得分:2)

我不确定你是通过这样做来实现的。这会容易得多。

$tests = @("test1", "test3", "test5")

Foreach($i in $Tests)
{
    IF($i -eq "test1")
        {
          Start-Job -Name $i -Scriptblock { Copy-Item "C:\Source\$($i)" "C:\Destination\$($i)" -Recurse -Container -Force }
        }
}

....

编辑:

就像我在下面的评论中所说的那样,您发布的代码与您的copy_1,copy_2,ect变量无关。你所做的只是迭代一串字符串。这可行,并且更接近您尝试这样做的方式。利用PSObjects

$copy_1 = New-Object -TypeName PSObject
$copy_1 | Add-Member -MemberType NoteProperty -name Name -value "copy_1"
$copy_1 | Add-Member -MemberType NoteProperty -name Source -value "C:\Source\test1"
$copy_1 | Add-Member -MemberType NoteProperty -name Destination -value "C:\Destination\test1"

$copy_2 = New-Object -TypeName PSObject
$copy_2 | Add-Member -MemberType NoteProperty -name Name -value "copy_2"
$copy_2 | Add-Member -MemberType NoteProperty -name Source -value "C:\Source\test2"
$copy_2 | Add-Member -MemberType NoteProperty -name Destination -value "C:\Destination\test2"

$copy_3 = New-Object -TypeName PSObject
$copy_3 | Add-Member -MemberType NoteProperty -name Name -value "copy_3"
$copy_3 | Add-Member -MemberType NoteProperty -name Source -value "C:\Source\test3"
$copy_3 | Add-Member -MemberType NoteProperty -name Destination -value "C:\Destination\test3"

$tests = @($copy_1, $copy_2, $copy_3)

Foreach($i in $tests)
{
    if($i.Name -eq "copy_1")
        {
          Start-Job -Name $i.Name -Scriptblock { Copy-Item $i.Source $i.Destination -recurse -Container -Force }          
        }
}