Private/Wait-ForPSDirectSession.ps1

function Wait-ForPSDirectSession {
    [CmdletBinding()]  
    param(
        [Parameter (Mandatory=$True)]
        [string]$VMName,

        [Parameter (Mandatory=$True)]
        [PSCredential]$Credential,

        [int]$Attempts=1
    )
    try {
        for ($i = 0; $i -lt $Attempts; $i++) {
            Write-Verbose "Waiting for $VMName..."
            Wait-VM -Name $VMName -For IPAddress -Timeout 1800 -ErrorAction Stop
            Write-Verbose "Attempting to establish a remote session with $VMName..."
            $Session = New-PSSession -VMName $VMName -Credential $Credential -ErrorAction SilentlyContinue
            if ($Session) {
                $Attempts = 0
                return $Session
            }
            else {
                Write-Warning "$VMName is not ready to accept WSMan connections."
                Start-Sleep -Seconds 20
            }
        }
        Write-Error "Ran out of attempts while trying to establish a remote session with $VMName"
    }
    catch {
        $PSCmdlet.ThrowTerminatingError($_) 
    }
}