Search code examples
powershellscriptblock

Powershell call batch within scriptblock


I have the script below which is not working the way I want. Initially, I would like to pass install.cmd to function which will use the "Start-Job" in the background so that it doesn't freeze up the main Powershell window. But I can't get it to call the install.cmd.

$Appname = @("Adobe_FlashPlayer", "Acrobat_Reader", "Microsoft_RDP")

function BatchJob{

    Param (
        [ScriptBlock]$batchScript,
        $ArgumentList = $null)
    #Start the batch
    $batch = Start-Job -ScriptBlock $batchScript -ArgumentList $ArgumentList

}

Foreach($App in $Appname){
    $Install = "C:\test\$App\Install.cmd"
    Batchjob -batchscript {Invoke-Command (cmd / c)} -ArgumentList $install     
    Wait-Job $job
    Receive-Job $job
}

Solution

  • I believe you overkilled it (a bit). This works:

    $Appname = @("Adobe_FlashPlayer", "Acrobat_Reader")
    
    Foreach($App in $Appname){
        $Install = "C:\test\$App\Install.cmd"
        $job = Start-Job ([scriptblock]::create("cmd /C $Install"))
        Wait-Job $job
        Receive-Job $job
    }
    

    *mjolinor to the rescue: https://stackoverflow.com/a/25020293/4593649

    Also, this variation works fine:

    $Appname = @("Adobe_FlashPlayer", "Acrobat_Reader")
    
    Foreach($App in $Appname){
        $Install = "C:\test\$App\Install.cmd"
        $scriptBlock = ([scriptblock]::create("cmd /C $Install"))
        $job = Start-Job $scriptBlock
        Wait-Job $job
        Receive-Job $job
    }
    

    Tested with PShell ver4. Cheers!