Passing a variable to a powershell script via command line
I am new to powershell, and trying to teach myself the basics. I need to write a ps script to parse a file, which has not been too difficult.
Now I want to change it to pass a variable to the script. that variable will be the parsing string. Now, the variable will always be 1 word, and not a set of words or multiple words.
This seems uber simple yet is posing a problem for me. Here is my simple code:
$a = Read-Host Write-Host $a
When I run the script from my command line the variable passing doesn't work:
.\test.ps1 hello .\test.ps1 "hello" .\test.ps1 -a "hello" .\test.ps1 -a hello .\test.ps1 -File "hello"
As you can see, I have tried many methos with no success, of the script taking the value an outputting it.
The script does run, and waits for me to type a value, and when I do, it echos that value.
I just want it to output my passed in value, what minuscule thing am I missing?
Here's a good tutorial on Powershell params:
Basically, you should use a
param statement on the first line of the script
param([type]$p1 = , [type]$p2 = , ...)
or use the $args built-in variable, which is auto-populated with all of the args.
Read more... Read less...
Declare the parameter in test.ps1:
Param( [Parameter(Mandatory=$True,Position=1)] [string]$input_dir, [Parameter(Mandatory=$True)] [string]$output_dir, [switch]$force = $false )
Run the script from Run OR Windows Task Scheduler:
powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"
powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"
Passed parameter like below,
Param([parameter(Mandatory=$true, HelpMessage="Enter name and key values")] $Name, $Key)
.\script_name.ps1 -Name name -Key key
Using param to name the parameters allows you to ignore the order of the parameters:
# Show how to handle command line parameters in Windows PowerShell param( [string]$FileName, [string]$Bogus ) write-output 'This is param FileName:'+$FileName write-output 'This is param Bogus:'+$Bogus
rem Notice that named params mean the order of params can be ignored powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"