Search code examples
powershelljobs

PowerShell Start-Job not creating or amending files


I am new to PowerShell and this is the first time I am attempting to use a job. I am running into an issue where I have a part of a script that looks for a file, creates it if it doesn't exist and then amends the file, and when I run the script (not as a job) it executes correctly, but when I put it in a job, it doesn't amend the file.

A much simplified example of what I have is this:

Start-job -Name HostCheck -ScriptBlock {
     ForEach ($Host in (Get-Content -Path .\HostFile.txt) {
          Add-Content .\somefile.txt "`nWrite something on a new line for $Host"
     } | Out-Null
} 

# Removes job once it is finished
Get-Job -Name HostCheck | Wait-Job | Remove-Job

Now I have tried adding | Receive-Job after the | Out-Null, but that didn't seem to change anything.

I've seen people write the entire script-block to a variable and just use the variable instead, so I am curious if that is a requirement (but I wouldn't think so).

Also, this might matter, I open the script with a .bat file that escalates the PowerShell console to admin as well as setting the execution policy of the process to Bypass. Now it seems that everything that runs in that console session or is kicked off by that console session (several scripts get ran, this is just part of one of them) seems to inherit those settings, but being new with jobs, I don't know if it would also inherit those settings, or how I would force it to (if not).


Solution

  • I discovered the problem:

    -Your current working directory is lost when starting a job so my relative path .\somefile.txt would default to C:\Users\[Username]\Documents instead of the location where the .\somefile.txt resides.

    I can get around this by using an absolute path, or I think there is a way to pass arguments to a job, but if anyone knows a better way to do this, please feel free to comment.