Working with Invoke-Command/Start-Job and PSRemoting
<p>I'm working with a script that remotes into a series of servers and executes commands from a series of PoSh functions. I will need to retain the synchronous processing and would simply like to add the capability of performing an async operation on the function.</p>

<p>How can I transform this to be called as a job from a primary function using <code>Start-Job</code> or <code>Invoke-Command -AsJob</code>? These functions are part of a PowerShell module, if that makes a difference.</p>

<p>I've tried a couple of various examples I've seen here, but they do not seem to actually process the function.</p>

<p>For example, for the below function, I've tried:</p>

<pre><code>foreach($s in $servers)
{
            if($lbFileLocation -eq $true)
            {
                #Rename-LoadBalancerFile -ServerName $server -Revert $false -filePath $filePath -cred $cred - #sync function works great
                Start-Job -Name 'RenLb'  -InitializationScript {Import-Module '.\Down.psm1'} $ScriptBlock -ArgumentList $server,$false,$lbFileLocation,$Cred | Out-Null
            }
 }

        Write-Host 'Waiting for LB rename.'
        While (Get-Job -Name 'RenLb' | where { $_.State -eq 'Running' } )
              {
                  Start-Sleep 1
              }

             Write-Host 'completed'
</code></pre>

<p>Original, synchronous function:</p>

<pre><code>function Rename-LoadBalancerFile
{
    param
    (
        [string]
        [Parameter(Mandatory=$true)]
        $ServerName,
        [bool]
        [Parameter(Mandatory=$true)]
        $Revert,
        [string]
        [Parameter(Mandatory=$true)]
        $filePath,
        [PSCredential]
        [Parameter(Mandatory=$false)]
        $cred
    )

    $scriptBlock = {
        param
        (
            [bool]
            [Parameter(Mandatory=$true)]
            $Revert,
            [string]
            [Parameter(Mandatory=$true)]
            $filePath
        )

        if(Test-Path $filePath -eq $true)
        {
            Write-Host 'file tested true'
            if($Revert -eq $true)
            {
                $fileName = [IO.Path]::GetFileName($filePath)
                $directory = [IO.Path]::GetDirectoryName($filePath)

                Rename-Item -Path "$directory\file.txt" -NewName $fileName
            }
            else
            {
                Rename-Item -Path $filePath -NewName 'file.txt'
            }
        }
    }

    $session = New-PSSession -ComputerName $ServerName -Authentication Credssp -Credential $cred
    Invoke-Command -Session $session -ScriptBlock $scriptBlock -ArgumentList $Revert, $filePath
    Remove-PSSession $session
}
</code></pre>