When writing a PowerShell script, you can output the desired result by assigning a value to the variable, but you need to change the script content. You can also define parameters in the script, and then assign values to the parameters when you execute the script without altering the script content.
In a PowerShell script, you can declare parameters using Param (), as follows:
Param ($a, $b)
Write-host "Hello, $a"
Write-host "Nihao, $b"
Save the above content in the F-packing directory, named Hello.ps1.
Run the script at the command prompt and specify a value of "Lily" and "Lucy" for the parameter $ A and $b, respectively, in the following manner:
C:\users\administrator>powershell.exe F:\hello.ps1 Lily Lucy
The result of the script execution is:
Hello,lily
Nihao,lucy
If you need to change the position of the parameter, you need to specify a value for a different parameter, such as specifying a value of $ A to "Lucy", $b the specified value is "Lily", as follows:
C:\users\administrator>powershell.exe F:\hello.ps1-b lily-a Lucy
The result of the script execution is:
Hello,lucy
Nihao,lily
When declaring a parameter, you can also specify the parameter type, as follows:
Param ([string] $a, [int] $b)
$a + $b
When passing parameters to the script, if you specify a parameter type of string for $ A and $b, the error is as follows:
C:\users\administrator>powershell.exe F:\hello.ps1-a lilei-b Lin
F:\HELLO.PS1: Could not handle parameter conversion to parameter ' B '. The value "Lin" cannot be converted to type "System."
Int32 ". Error: "The input string is not properly formatted. ”
Location Line: 1 characters: 25
+ F:\hello.ps1-a Lilei-b <<<< Lin
+ Categoryinfo:invaliddata: (:) [Hello.ps1], Parameterbindin ...
Mationexception
+ FULLYQUALIFIEDERRORID:PARAMETERARGUMENTTRANSFORMATIONERROR,HELLO.PS1
It is only possible to give it an int type value, as follows:
C:\users\administrator>powershell.exe F:\hello.ps1-a 5-b 6
11
Category: PowerShell
PowerShell Script Pass Parameters