Saturday, 20 December 2014

How to pass arguments to PowerShell script

In this article, I am going to explain about how to pass arguments into Powershell script and how to get input values dynamically from Powershell script. You can pass parameters in different ways either by unnamed parameters, named parameters and you can even force the user to enter specific parameter value.

Pass arguments by unnamed parameters:

You can just pass any no of values into script with separated by space, within a script you can refer unnamed arguments using the $args array and referring to the position (first, second..) of each argument.
#UnnamedArgs.ps1
#Usage:PS C:\Scripts> .\UnnamedArgs.ps1 arg1 arg2
"Your 1st argument is: " + $Args[0]
"Your 2nd argument is: " + $Args[1]

Pass arguments by named parameters:

In unnamed parameters method, you cannot have more control with inputs and powershel script itself look unclear to understand the process. To overcome this, you can pass arguments by named parameter. To get arguments by name, we need to use param statement.
#NamedArgs.ps1
#Usage:PS C:\Scripts> .\NamedArgs.ps1 -Name "Morgan" -City "Arlington"
param($Name, $City)
  "User name: " + $Name
  "City: " + $City
You can set default value for any argument, this default value will be taken as actual value if user doesn't pass the value for this argument.
#PassArgs.ps1
param($Name, $City="Los Angeles")
  "User name: " + $Name
  "City: " + $City

How to pass arguments to PowerShell script

You can set an argument as Mandatory parameter to force user to enter the specific argument to run script.
#MandatoryArgs.ps1
param( [Parameter(Mandatory=$true)] $Name, $City="Los Angeles" )
 "User name: " + $Name
 "City: " + $City

Ask dynamic arguments within Powershell script:

You can force user to enter input values dynamically from inside part of Powershell script using Read-Host cmdlet with respect to your dynamic need.
#DynamicArgs.ps1
param( $Name)
If ($Name -eq "Morgan") {
    $mobileno = Read-Host "Enter your mobile no"
}
else{
    $email = Read-Host "Enter your email"
}
Ask dynamic arguments within Powershell script

Ask password from user in Powershell script:

You can force user to enter password from inside part of Powershell script using Read-Host cmdlet, and you can mask the password string by setting a parameter -asSecureString in Read-Host cmdlet.
#PasswordArgs.ps1
param( $Name)
"Hi, " + $Name
$password = Read-Host "Enter Password" -asSecureString
$PwdPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
# Get the plain text version of the password.
$PlainTextPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto($PwdPointer)
# Free the pointer.
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($PwdPointer)
"Your have entered this password: " + $PlainTextPassword
Ask password from user in Powershell script

Advertisements
Advertisements

No comments:

Post a Comment