Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a Powershell script from the command line and pass a directory as a parameter

PowerShell -Command .\Foo.ps1 
  • Foo.ps1:

    Function Foo($directory) {     echo $directory }  if ($args.Length -eq 0) {     echo "Usage: Foo <directory>" } else {     Foo($args[0]) } 

    Despite Foo.ps1 being in the directory from where I am calling Powershell, this results in:

    The term '.\Foo.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program.  Check the spelling of the name, or if a path was included, verify that the path is correct and try again. 
    • EDIT: Wasn't working because PowerShell was changing directory due to profile.ps1 containing cd C:\


I then tried to call it specifying the full path to the script file, but no matter what I try, I can't get it to work. I believe I have to quote the path because it contains whitespaces, as does the file name I need to pass in an argument to the script.

  • Best guess so far:

    PowerShell -Command "'C:\Dummy Directory 1\Foo.ps1' 'C:\Dummy Directory 2\File.txt'" 

    Outputs error:

    Unexpected token 'C:\Dummy Directory 2\File.txt' in expression or statement.  At line:1 char:136. 
like image 972
Polyfun Avatar asked Dec 05 '12 14:12

Polyfun


People also ask

Can you run a PowerShell script from CMD?

Running a PowerShell script from the Command Prompt If you would like to run a PowerShell script in CMD, you'll need to execute it by calling the PowerShell process with the -File parameter, as shown below: PowerShell -File C:\TEMP\MyNotepadScript. ps1. PowerShell -File C:\TEMP\MyNotepadScript.

How do you pass a variable in PowerShell?

You can pass variables to functions by reference or by value. When you pass a variable by value, you are passing a copy of the data. In the following example, the function changes the value of the variable passed to it. In PowerShell, integers are value types so they are passed by value.

What is param () in PowerShell?

Parameters can be created for scripts and functions and are always enclosed in a param block defined with the param keyword, followed by opening and closing parentheses. param() Inside of that param block contains one or more parameters defined by -- at their most basic -- a single variable as shown below.


1 Answers

try this:

powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'" 
like image 78
CB. Avatar answered Sep 17 '22 12:09

CB.