![](/img/trans.png)
[英]How to pass a parameter with parentheses to Powershell from command line?
[英]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.
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.