Search code examples
powershellstart-job

Using Start-Job on script


Using a script in PowerShell to recursivly pass through all folders on multiple NAS boxes to display every folder with its full path in an Out-File. Using the Get-FolderEntry script I found here.

Since I have multiple NAS boxes with more then 260 chars in the filename/pathlength I figured I'd use multithreading to speed the process up.

Code:

. 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

So far:

  1. I either get empty files with the correct naming of the file.

  2. I get the correct named file with the code of Get-FolderEntry in it.

  3. I get errors depend on what I pass along to the scriptblock.

In short, it's probably stupid but don't see it.


Solution

  • Found it eventually myself after some trial and error:

    . 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
    

    Thanks a lot Ansgar for pointing my in the right direction!