2

I was wondering if is possible to call a variable for use in a PowerShell script using the command line.

For instance, I have a script that I would like to run tonight. I want to run it at two times using a different input file (csv) each time.

Can I call...

powershell.exe -command {$input = <csv path>} -file <script path>

and discretely call a variable for use in the script from outside of the script? Do I just need to make two copies of the script with the variable change included in the script itself? Is there a way to do this that I am missing?

1 Answer 1

5

PowerShell scripts can have parameters, just as functions can. That way you can have one script and just call it with different input file names. Also see here for a similar question, here what more you can do with parameters and here for more commandline options.

Script

Param([Parameter(Mandatory=$True)] [string] $FileName)

Write-Output "Script called with $FileName"

Call

powershell.exe -file Untitled2.ps1 Test3.csv
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much. I am new to powershell and had heard about parameters, but I never understood what they were for or how to use them. Now at least I know what to look for help on. Thanks for the assist, I will look at your links.
@Acerbity I would also suggest doing a get-help about_function* in powershell to see the various help topics available at your fingertips, and read through them when you get a chance. I found about_Functions_Advanced_Parameters very helpful myself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.