簡體   English   中英

如何從命令行運行 Powershell 腳本並將目錄作為參數傳遞

[英]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]) }

    盡管Foo.ps1位於我調用 Powershell 的目錄中,但這會導致:

     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.
    • 編輯:無法正常工作,因為 PowerShell 正在更改目錄,因為profile.ps1包含cd C:\\


然后我嘗試調用它指定腳本文件的完整路徑,但無論我嘗試什么,我都無法讓它工作。 我相信我必須引用路徑,因為它包含空格,我需要將參數傳遞給腳本的文件名也是如此。

  • 迄今為止最好的猜測:

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

    輸出錯誤:

     Unexpected token 'C:\\Dummy Directory 2\\File.txt' in expression or statement. At line:1 char:136.

試試這個:

powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"

您正在調用腳本文件而不是命令,因此您必須使用 -file 例如:

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

PS V2

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

(檢查此技術網頁面的底部http://technet.microsoft.com/en-us/library/ee176949.aspx

使用標志-Command您可以執行整個 powershell 行,就像它是 PowerShell 提示符中的命令一樣:

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

這解決了我在 Visual Studio Post-Build 和 Pre-Build 事件中運行 PowerShell 命令的問題。

將您的代碼更改為以下內容:

Function Foo($directory)
    {
        echo $directory
    }

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

然后調用它:

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

在 ps1 文件的頂部添加參數聲明

測試.ps1

param(
  # Our preferred encoding
  [parameter(Mandatory=$false)]
  [ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
  [string]$Encoding = "UTF8"
)

write ("Encoding : {0}" -f $Encoding)

結果

C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII

您輸入並按 Enter 鍵:

PowerShell - 命令

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM