How to run a ps1 file in foreground? I noticed when I execute my ps1 file, instead of view the log of the ps1 file execution, a Background job is started. Is there anyway to run a ps1 file and get the same behavior we have when executing a sh or batch file?
Updates:
- My ps1 file:
$scratchOrgName=$args[0]
Write-Host "Hello " & $scratchOrgName
CodePudding user response:
The & starts a new process. (It's called the background operator)
Change the code into something like
Write-Host "Hello" $scratchOrgName
or
Write-Host "Hello $scratchOrgName"
CodePudding user response:
tl;dr
Unless you explicitly request that commands be run in the background (as you accidentally did, see next section), PowerShell commands do run in the foreground.
To achieve what you were (presumably) trying to do:
$scratchOrgName=$args[0]
"Hello $scratchOrgName"
Michaël Hompus' helpful answer provides the crucial pointers, but let me attempt a systematic overview:
Write-Host "Hello " & $scratchOrgName is composed of two statements:
Write-Host "Hello " &submits commandWrite-Host "Hello "as a background job, in PowerShell (Core) v6 (in Windows PowerShell (v5.1-), you'd get an error, saying that&is reserved for future use).The post-positional use of
&- i.e. placed after a command - is indeed the background operator, and is therefore equivalent toStart-Job { Write-Host "Hello " }This contrasts with pre-positional use of
&, which then acts as the call operator, for invoking command names or paths that are potentially quoted or contain / are variable values.
$scratchOrgName- by virtue of PowerShell's implicit output behavior - outputs the value of that variable, which prints to the screen by default.
As for what you intended:
&is VBScript's string-concatenation operator; its PowerShell equivalent isA string-concatenation operation is an expression, and as such it must be enclosed in
(...)in order to be passed as an argument to a command such asWrite-Host.
Therefore, the direct PowerShell expression of your intent would be:
Write-Host ("Hello " $scratchOrgName)
But, as also shown in Michaël's answer, this is more easily expressed via an expandable (double-quoted) string ("..."):
Write-Host "Hello $scratchOrgName"
Taking a step back: Write-Host is typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file.
To output a value, use it by itself, taking advantage of the aforementioned implicit output behavior (or use Write-Output, though that is rarely needed):
"Hello $scratchOrgName"
See this answer for more information.

