Powershell pass arguments to script

If you wish to call a Powershell script with a certain argument (e.g. a directory), you can do so with the following example:

Snippet: add expected argument to script

# Define parameters that this script needs.
# -----------------------------------------
# 1. $BinDirectory = Full path to the bin directory that this script requires
param(
	[Parameter(Mandatory=$true)]
	[String] $BinDirectory
)

Write-Host "======"
Write-Host "Received the following argument: " $BinDirectory
Write-Host "======"

Providing the argument

Typing manually when prompted by calling script

If you now call the script from the command line with the code above, you should see it now prompts you for the argument:

PS C:\Scripts> ./test.ps1

cmdlet test.ps1 at command pipeline position 1
Supply values for the following parameters:
BinDirectory:

Calling script with argument provided via parameter

The value that you provide here can then be used within the script. E.g. if we type in “C:\TestDirectory” and then press <enter>, you will see that the value is printed back to us:

PS C:\Scripts> ./test.ps1

cmdlet test.ps1 at command pipeline position 1
Supply values for the following parameters:
BinDirectory: C:\TestDirectory
======
Received the following argument: C:\TestDirectory
======

However, you can also pass on the argument directly by calling the script with it in one line:

PS C:\Scripts> .\test.ps1 C:\TestDirectory
======
Received the following argument:  C:\TestDirectory
======

Published
Categorized as Powershell

By Leendert de Borst

Freelance software architect with 10+ years of experience. Expert in translating complex technical problems into creative & simple solutions.

Leave a comment

Your email address will not be published. Required fields are marked *