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

前端 未结 6 1078
醉梦人生
醉梦人生 2020-12-24 04:40
PowerShell -Command .\\Foo.ps1
  • Foo.ps1:

    
    
            
相关标签:
6条回答
  • 2020-12-24 05:11

    Change your code to the following :

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

    And then invoke it as:

    powershell -ExecutionPolicy RemoteSigned -File "c:\foo.ps1" "c:\Documents and Settings" "c:\test"

    0 讨论(0)
  • 2020-12-24 05:12

    try this:

    powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"
    
    0 讨论(0)
  • 2020-12-24 05:12

    Add the param declation at the top of ps1 file

    test.ps1

    param(
      # Our preferred encoding
      [parameter(Mandatory=$false)]
      [ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
      [string]$Encoding = "UTF8"
    )
    
    write ("Encoding : {0}" -f $Encoding)
    

    result

    C:\temp> .\test.ps1 -Encoding ASCII
    Encoding : ASCII
    
    0 讨论(0)
  • 2020-12-24 05:14

    you are calling a script file not a command so you have to use -file eg :

    powershell -executionPolicy bypass -noexit -file "c:\temp\test.ps1" "c:\test with space"
    

    for PS V2

    powershell.exe -noexit &'c:\my scripts\test.ps1'
    

    (check bottom of this technet page http://technet.microsoft.com/en-us/library/ee176949.aspx )

    0 讨论(0)
  • 2020-12-24 05:27

    you have type and hit enter :

    PowerShell -Command

    0 讨论(0)
  • 2020-12-24 05:31

    Using the flag -Command you can execute your entire powershell line as if it was a command in the PowerShell prompt:

    powershell -Command "& '<PATH_TO_PS1_FILE>' '<ARG_1>' '<ARG_2>' ... '<ARG_N>'"
    

    This solved my issue with running PowerShell commands in Visual Studio Post-Build and Pre-Build events.

    0 讨论(0)
提交回复
热议问题