从foreach调用脚本



我需要一些帮助,或者建议一个更好的方法,我正在努力做什么。

我想复制一些东西所以我有

$tests = @("test1", "test3", "test5")
$copy_1 = {
$source = "C:Sourcetest1"
$Destination = "C:Destinationtest1"
Copy-Item $Source -Recurse -Destination $Destination -Container -Force
}
$copy_2 = {
$source = "C:Sourcetest2"
$Destination = "C:Destinationtest2"
 Copy-Item $Source -Recurse -Destination $Destination -Container -Force
}
$copy_3 = {
$source = "C:Sourcetest3"
$Destination = "C:Destinationtest3"
Copy-Item $Source -Recurse -Destination $Destination -Container -Force
}
$copy_4 = {
$source = "C:Sourcetest4"
$Destination = "C:Destinationtest4"
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块?

我不知道你那样做是想达到什么目的。这样就容易多了。

$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等变量没有任何作用。你所做的就是遍历字符串数组。这样做会有效,而且更接近你想要做的方法。利用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:Sourcetest1"
$copy_1 | Add-Member -MemberType NoteProperty -name Destination -value "C:Destinationtest1"
$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:Sourcetest2"
$copy_2 | Add-Member -MemberType NoteProperty -name Destination -value "C:Destinationtest2"
$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:Sourcetest3"
$copy_3 | Add-Member -MemberType NoteProperty -name Destination -value "C:Destinationtest3"
$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 }          
        }
}

相关内容

  • 没有找到相关文章

最新更新