Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Start-Job Working Directory

Is there a way to specify a working directory to the Start-Job command?

Use-case:

I'm in a directory, and I want to open a file using Emacs for editing. If I do this directly, it will block PowerShell until I close Emacs. But using Start-Job attempts to run Emacs from my home directory, thus having Emacs open a new file instead of the one I wanted.

I tried to specify the full path using $pwd, but variables in the script block are not resolved until they're executing in the Start-Job context. So some way to force resolving the variables in the shell context would also be an acceptable answer to this.

So, here's what I've tried, just for completeness:

Start-Job { emacs RandomFile.txt } Start-Job { emacs "$pwd/RandomFile.txt" } 
like image 684
jdmichal Avatar asked Feb 08 '10 19:02

jdmichal


People also ask

How do I Start a PowerShell job?

The Start-Job cmdlet starts a PowerShell background job on the local computer. A PowerShell background job runs a command without interacting with the current session. When you start a background job, a job object returns immediately, even if the job takes an extended time to finish.

How do I see running jobs in PowerShell?

You can use Get-Job to get jobs that were started by using the Start-Job cmdlet, or by using the AsJob parameter of any cmdlet. Without parameters, a Get-Job command gets all jobs in the current session. You can use the parameters of Get-Job to get particular jobs.

How do I Start a thread in PowerShell?

It can also be installed from the PowerShell Gallery for Windows PowerShell 5.1. To start a thread job on the local computer, use the Start-ThreadJob cmdlet with a command or script enclosed in curly braces ( { } ). The following example starts a thread job that runs a Get-Process command on the local computer.


2 Answers

There is nice solution from comments section of some dude's post. Commenter suggests to use Init parameter to setup working directory of script block.

function start-jobhere([scriptblock]$block) {     Start-Job -Init ([ScriptBlock]::Create("Set-Location '$pwd'")) -Script $block } 
like image 103
asavartsov Avatar answered Sep 20 '22 15:09

asavartsov


A possible solution would be to create a "kicker-script":

Start-Job -filepath .\emacs.ps1 -ArgumentList $workingdir, "RandomFile.txt" 

Your script would look like this:

Set-Location $args[0] emacs $args[1] 

Hope this helps.

like image 41
Filburt Avatar answered Sep 18 '22 15:09

Filburt