0

I am writing a script that presents the user with a menu of functions, but I also want to be able to run the script automatically from task scheduler which would mean I would need to skip the menu portion. Is there a way to do this with flags or arguments when starting the script (like "script.ps1 -auto" to skip the coding containing the menu, or just "script.ps1" to start)

I've performed internet searches for this, but have not yet found anything that I think is applicable. I'm not even sure if this is possible given the lack of information I've found (or not found).

script.ps1 script.ps1 -auto

Not to the point where error messages are applicable

Ken
  • 125
  • 1
  • 12

1 Answers1

2

You can use the [switch] parameter type in your param block.

param( [switch] $auto ) 

if ($auto) {
   # here goes the code if the parameter auto is set
} 
else {

}

See also this answer on SO, on how to handle command-line parameters with PowerShell.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Peter Schneider
  • 2,879
  • 1
  • 14
  • 17
  • Just to clarify the edit: generally, something like `[switch]` is a _type literal_ in PowerShell. Placed before a parameter variable, it _type-constrains_ (types) that variable; placed before an expression (e.g., `[int] '3'`), it acts as a _cast_ / flexible type conversion. – mklement0 Oct 10 '19 at 19:22