Repository navigation
Running a script in a headless environment #20291
|
PowerShell is supposed to be primarily an automation language, right? It is supposed to work in a headless environment. Hence, every cmdlet must proceed with absolutely zero user input. If it doesn't have enough info to proceed, it must return an error. The question is: How do we achieve that? Please consider the following script. The last cmdlet requires a user input. But in a headless environment, the script must simply return an error message. And not just for How do we achieve that? I've done some experiments with |
Replies: 1 comment 1 reply
|
Start PowerShell with pwsh -NoProfile -NonInteractive -File ./script.ps1This makes PowerShell host prompts fail instead of waiting for input. I tested your nonempty-directory example on PowerShell 7.6.5: See If the caller also requires a nonzero exit status, wrap the automation commands inside the script: $ErrorActionPreference = 'Stop'
try {
# Your automation commands here
} catch {
Write-Error $_ -ErrorAction Continue
exit 1
}I also tested this wrapper with the same |
Start PowerShell with
-NonInteractive:This makes PowerShell host prompts fail instead of waiting for input. I tested your nonempty-directory example on PowerShell 7.6.5:
Remove-ItemreportedPowerShell is in NonInteractive mode. Read and Prompt functionality is not available., and the directory remained intact.See
about_Pwsh -NonInteractive. It applies to PowerShell prompts, includingRead-Hostand confirmation prompts; external programs can have their own input behavior.If the caller also requires a nonzero exit status, wrap the automation commands inside the script: