Run Script with Arguments in Windows PowerShell


How to write a script that take argument from the command line in Windows PowerShell?



You can use the automatic variable $Args to take arguments from the command line where the script is launched.

The $Args variable contains an array of all argument provided at the command line where this script was launched.

Here is sample script on how to use $Args variable:

<# My-Ping.ps1 - Tests network connection to a remote server
If ($Args.Length -eq 2) {
   Test-Connection $Args[0] -Count $Args[1]
} Else {
   "Usage: "
   "   My-Ping server_name test_count"

If you run it without argument, you will get

PS C:\fyicenter> .\My-Ping.ps1

   My-Ping server_name test_count

If you run it with correct arguments, you will get

PS C:\fyicenter> .\My-Ping.ps1 2

Destination     IPV4Address      Bytes    Time(ms)
-----------     -----------      -----    --------    32       52    32       51


Introduction of Windows PowerShell Script

⇒⇒Windows PowerShell Tutorials

2016-10-27, 421👍, 0💬