Any time you are using a variable in a script that you (or someone else) may want to change in the future, use script parameters.
Instead of setting a bunch of variables in your script, put them in the Param() section at the top of your script to enable them to be set at runtime.
Instead of:
1 2 3 4 | [string] $TargetDN = "OU=Target,DC=example,DC=com" [sting] $TargetType = "Workstations" [int] $ComputerAge = 60 [string] $Pass = "Pass99" |
Use This:
1 2 3 | Param ( [alias("Target","DN","TDN")] [string] $TargetDN = "OU=Target,DC=example,DC=com", |
[alias("Type","TT")]
[ValidateSet("Workstations","Workstation","Servers","Server")]
[sting] $TargetType = “Workstations”,
[alias("Age","CA")]
[int] $ComputerAge = 60,
[alias("Password","PW","PWD","NewPassword")]
[ValidateLength(10,128)]
[string] $Pass,
)
Putting these variables into Param() (with options) enables the user running the script to change them at run-time.
scriptexample.ps1 -TargetDN “OU=Target2,DC=example,DC=com” -TargetType “Servers” -ComputerAge 45 -Pass “2355jigij54645″
Since there are aliases set for each variable in the Param section, we can also run this for the same result:
scriptexample.ps1 -Target “OU=Target2,DC=example,DC=com” -Type
“Servers” -Age 45 -PW “2355jigij54645″
Microsoft has some excellent documentation on Powershell Parameters
Some of my favorites:
Default Parameter
[Switch]$Enabled = $True
Mandatory Parameter
[parameter(Mandatory=$true)] [String]$Name
Validate Parameter Options in a set
[ValidateSet("TCP", "UDP")]
[string]$NewPortType
Validate Parameter Options in a range
[ValidateRange(1,65535)] [string]$NewPortNumber
Add Parameter Aliases
[alias("PortScope","Scope")]
[string] $NewPortScope