CompTIA A+ Core 2 (220-1202)Operational ProceduresMedium
A technician is developing a PowerShell script to automate a routine task. The script needs to accept a file path as an input from the user. Which of the following is the BEST way to define a parameter for this input, ensuring it is mandatory and clearly identifiable?
- A[string]$FilePath = Read-Host 'Enter file path:'
- B$FilePath = $args[0]
- Cparam ( [Parameter(Mandatory=$true)][string]$FilePath )
- DGet-Content $FilePath
Show answer & explanationAnswer & explanation
Correct answer: C. param ( [Parameter(Mandatory=$true)][string]$FilePath )
Using the 'param' block with the '[Parameter(Mandatory=$true)]' attribute explicitly defines a mandatory parameter named 'FilePath' of type string. This provides clear input definition, type checking, and ensures the script cannot run without the required input, which is best practice for robust scripting.
Why the other options are wrong
- A. This uses 'Read-Host' which prompts for input during script execution but doesn't define it as a formal script parameter that can be passed at runtime or appear in help documentation.
- B. $args[0] is for accessing untyped, unnamed positional arguments, which is less robust and less clear than defined parameters, especially for complex scripts.
- D. Get-Content is a cmdlet for reading file content, not for defining script input parameters.
PowerShell Parameters
Variables defined in a PowerShell script's 'param' block that accept input values when the script is run.
- Defined using 'param' block
- Can be mandatory or optional
- Allow for type checking and validation
Memory trick: Parameters are how scripts get their orders.