我試圖從調用PowerShell腳本的Windows運行時傳遞一些參數。看起來像這樣: myscript「一些參數」,「其他」 這甚至可能嗎?如果是這樣,我怎麼能從它的參數到powershell腳本並使用它們? 到目前爲止,我得到了如何通過使用參數的「ValueFromPipelineByPropertyName」選項通過cmd詢問用戶輸入參數,但它不是我想要的。 在此先感謝。從powershell中運行的窗口參數
回答
PowerShell的本質提供了處理腳本參數有兩種方式:
的automatic variable
$args
持有的所有參數的列表,然後可以通過索引來訪問:腳本:
"1st argument: " + $args[0] "2nd argument: " + $args[1] "3rd argument: " + $args[2]
調用:
powershell.exe -File .\script.ps1 "foo" "bar"
輸出:
1st argument: foo 2nd argument: bar 3rd argument:
一個
Param()
section在腳本的開頭獲取分配給各個變量的參數值:腳本:
Param( [Parameter()]$p1 = '', [Parameter()]$p2 = '', [Parameter()]$p3 = '' ) "1st argument: " + $p1 "2nd argument: " + $p2 "3rd argument: " + $p3
調用:
powershell.exe -File .\script.ps1 "foo" "bar"
輸出:
1st argument: foo 2nd argument: bar 3rd argument:
但是,如果您希望能夠在不顯式運行powershell.exe
命令的情況下調用PowerShell腳本,則需要更改註冊表中Microsoft.PowerShellScript.1
類型的默認操作。您可能還需要調整系統上的執行策略(Set-ExecutionPolicy RemoteSigned -Force
)。
通常情況下,您只能對非常簡單的場景使用$args
(少量參數按照定義良好的順序)。完整的參數定義使您可以更好地控制參數處理(可以使參數可選或強制,定義參數類型,定義默認值,進行驗證等)。
我幾乎不明白你的問題。下面是一個試圖接近你想要的東西..
您嘗試通過Windows CMD調用PowerShell腳本,像這樣:
powershell.exe myscript.ps1 parameter1 parameter2 anotherparameter
以上是你如何利用未命名參數。 你也可以看看命名參數,就像這樣:
Powershell.exe myscript.ps1 -param1 "Test" -param2 "Test2" -anotherparameter "Test3"
您可以使用「設置」,在CMD接受來自用戶的輸入,像這樣:
set /p id="Enter ID: "
在PowerShell中您可以使用閱讀-host,像這樣:
$answer = Read-Host "Please input the answer to this question"
上命名參數進一步閱讀:http://powershell-guru.com/powershel l-best-practice-2-use-named-parameters-not-positions-and-partial-parameters/ –
在腳本的聲明你要傳遞的參數上,這裏是從我的build.ps1
param (
[string] $searchTerm,
[ValidateSet('Remote', 'Local')][string] $sourceType = 'local',
[switch] $force
)
Write-Host $searchTerm
一個例子吧,您可以將您的參數或者由順序:
build.ps1 '1234' local -force
或與名爲paramters
build.ps1 -searchTerm '1234' -sourceType local -force
我試過這樣做,但沒有奏效。也許我錯過了什麼 –
- 1. 從父窗口中的子窗口運行函數
- 2. 腳本從PowerShell窗口運行,但不是從文件
- 3. 使用Powershell中的參數運行TextTransform.exe
- 4. 在現實的PowerShell運行PowerShell腳本窗口
- 5. 從命令行參數製作窗口
- 6. Powershell從多個參數運行.ps1中的函數
- 7. 從運行窗口以管理員身份打開PowerShell
- 8. 窗口的容器2016運行PowerShell中的域用戶
- 9. 如何從主窗口powershell腳本傳遞參數到sqlps
- 10. 在命令窗口中運行rcp時如何從命令行獲取參數?
- 11. 從批處理文件運行Powershell腳本中的參數
- 12. 從第二個窗口在主窗口中運行Sub
- 13. 如何從運行PowerShell腳本的Windows服務中顯示彈出窗口
- 14. PowerShell代碼時粘貼到正在以管理員身份運行PowerShell窗口運行在窗口中的確定,但不能從名爲.ps1文件
- 15. 在.NET窗口應用程序中運行powershell腳本
- 16. PowerShell配置強制批處理文件在PowerShell窗口中運行?
- 17. 從java中的輸入窗口運行一個函數
- 18. PowerShell命令行參數丟失,如果從CMD運行直接
- 19. 從命令行運行Powershell作爲參數
- 20. Qt的獲取從主窗口UI參數在主窗口場
- 21. 使用vb.net參數運行powershell腳本
- 22. Powershell:運行msiexec動態創建參數
- 23. 隱藏窗口的命令行參數
- 24. 從Powershell腳本運行帶參數的.bat文件
- 25. 從RunOnce運行PowerShell
- 26. 從C運行powershell#
- 27. 從Powershell運行NServiceBusHost.exe
- 28. 運行的MSBuild從PowerShell的
- 29. 運行的java.exe從PowerShell的
- 30. 我可以運行對從「窗口」機
這正是我所尋找的。謝謝:) –