在脚本上使用Start-Job

时间:2016-12-13 09:15:44

标签: powershell start-job

使用PowerShell中的脚本递归传递多个NAS框上的所有文件夹,以在Out-File中显示其完整路径的每个文件夹。 使用Get-FolderEntry脚本我找到了here

由于我有多个NAS盒子,文件名/路径长度超过260个字符,我想我会使用多线程来加快处理速度。

代码:

. C:\Users\mdevogea\Downloads\Get-FolderEntry.ps1
# list with the servers
$Computers = Get-Content C:\Users\mdevogea\Desktop\servers.txt

# scriptblock calling on get-FolderEntry
$sb = {
    param ($Computer, $fname)
    C:\Users\mdevogea\Downloads\Get-FolderEntry.ps1 -Path $Computer |
        fl | Out-File -Append -Width 1000 -FilePath $fname
}

foreach($Computer in $Computers)
{
    $name = $Computer.Replace("\", "")
    $fname = $("C:\Users\mdevogea\Desktop\" + $name + ".txt")
    #Get-FolderEntry -Path $Computer | fl | Out-File -Append -Width 1000 $fname

    $res = Start-Job $sb -ArgumentList $Computer, $fname
}

# Wait for all jobs
Get-Job
while(Get-Job -State "Running")
{
    Write-Host "Running..."
    Start-Sleep 2
}
# Get all job results
Get-Job | Receive-Job | Out-GridView

到目前为止:

  1. 我要么得到文件正确命名的空文件。

  2. 我得到了代码为Get-FolderEntry的正确命名文件。

  3. 我得到错误取决于我传递给scriptblock的内容。

  4. 简而言之,这可能是愚蠢但却看不到它。

1 个答案:

答案 0 :(得分:0)

经过一些试验和错误后,最终自己找到了它:

. C:\Users\mdevogea\Downloads\Get-FolderEntry.ps1
# list with the servers
$Computers = Get-Content C:\Users\mdevogea\Desktop\servers.txt

# scriptblock calling on get-FolderEntry
$sb = {
    Param ($Computer, $fname)
    . C:\Users\mdevogea\Downloads\Get-FolderEntry.ps1 
    (Get-FolderEntry -Path $Computer | fl | Out-File -Append -Width 1000 -FilePath $fname)
}

foreach ($Computer in $Computers)
{
    $name = $Computer.Replace("\", "")
    $fname = $("C:\Users\mdevogea\Desktop\" + $name + ".txt")
    $res = Start-Job $sb -ArgumentList $Computer, $fname
}

# Wait for all jobs
Get-Job
while (Get-Job -State "Running")
{
    Write-Host "Running..."
    Start-Sleep 2
}
# Get all job results
Get-Job | Receive-Job | Out-GridView

非常感谢Ansgar指出我正确的方向!