Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background Job in Powershell

I'm trying to run a job in a background which is a .exe with parameters and the destination has spaces. For example:

$exec = "C:\Program Files\foo.exe"

and I want to run this with parameters:

foo.exe /param1 /param2, etc.

I know that Start-Job does this but I've tried tons of different combinations and it either gives me an error because of the white space or because of the parameters. Can someone help me out with the syntax here? I need to assume that $exec is the path of the executable because it is part of a configuration file and could change later on.

like image 518
Brian Avatar asked Jan 04 '12 01:01

Brian


People also ask

Is PowerShell a good career?

Powershell is a task automation and configuration management framework by Microsoft.. If you are interested in Scripting languages/ good at scripting you can easily go for it.. Several vacancies are also for script writers with sufficient experience... Cant predict the future as there are rivals for powershell..

What are jobs in PowerShell?

In PowerShell, a job is a piece of code that is executed in the background. It's code that starts but then immediately returns control to PowerShell to continue processing other code. Jobs are great for performance and when a script doesn't depend on the results of prior code execution.

How do I stop PowerShell from running in the background?

You can use Stop-Job to stop background jobs, such as those that were started by using the Start-Job cmdlet or the AsJob parameter of any cmdlet. When you stop a background job, PowerShell completes all tasks that are pending in that job queue and then ends the job.


1 Answers

One way to do this is use a script block with a param block.

If there is a single argument with a space in it such as a file/folder path it should be quoted to treat it as a single item. The arguments are an array passed to the script block.

This example uses a script block but you can also use a PowerShell script using the -FilePath parameter of the Start-Job cmdlet instead of the -ScriptBlock parameter.

Here is another example that has arguments with spaces:

$scriptBlock = {
    param (
        [string] $Source,
        [string] $Destination
    )
    $output = & xcopy $Source $Destination 2>&1
    return $output
}

$job = Start-Job -scriptblock $scriptBlock -ArgumentList 'C:\My Folder', 'C:\My Folder 2'
Wait-Job $job
Receive-Job $job

Here is an example using the $args built-in variable instead of the param block.

$scriptBlock = {
    $output = & xcopy $args 2>&1
    return $output
}

$path1 = "C:\My Folder"
$path2 = "C:\My Folder 2"

"hello world" | Out-File -FilePath  "$path1\file.txt"

$job = Start-Job -scriptblock $scriptBlock -ArgumentList $path1, $path2
Wait-Job $job
Receive-Job $job
like image 63
Andy Arismendi Avatar answered Oct 10 '22 07:10

Andy Arismendi