簡體   English   中英

將參數傳遞給powershell腳本

[英]Passing parameters to powershell script

我正在嘗試從運行對話框運行一個powershell腳本(將用作計划任務),並且我遇到了傳遞參數的麻煩。

該腳本將接受兩個參數,名為title和msg。 該腳本位於: D:\\Tasks Scripts\\Powershell\\script.ps1

這就是我想要做的:

powershell.exe -noexit 'D:\Tasks Scripts\Powershell\script.ps1' -title 'Hello world' -msg 'This is a test message'

但是在讀取參數時失敗了。

正在運行.\\script.ps1 -title 'Hello world' -msg 'This is a test message'關於powershell .\\script.ps1 -title 'Hello world' -msg 'This is a test message'正常工作。

在腳本路徑之前使用-file

powershell.exe -noexit -file 'D:\Tasks Scripts\Powershell\script.ps1' etc...

我通常從cmd.exe運行powershell腳本,因為它是可移植的(在開發人員或客戶端的其他計算機上開箱即用):無需擔心Set-ExecutionPolicy或關聯.ps1擴展名。

我創建擴展名為.cmd(而不是.ps1)的文件,並將一個簡短的常量代碼復制並粘貼到調用powershell.exe的第一行,並將其余的文件傳遞給它。
傳遞參數很棘手。 我有常量代碼的多種變體,因為一般情況很痛苦。

  1. 不傳遞參數時,.cmd文件如下所示:

     @powershell -c ".(iex('{#'+(gc '%~f0' -raw)+'}'))" & goto :eof # ...arbitrary PS code here... write-host hello, world! 

    這使用powershell.exe的-Command參數。 Powershell將.cmd文件作為文本讀取,將其放在ScriptBlock中,並將第一行注釋掉,並使用'。'對其進行評估。 命令。 可以根據需要將更多命令行參數添加到Powershell調用中(例如-ExecutionPolicy Unrestricted,-Sta等)

  2. 當傳遞不包含空格或“單引號”的參數(在cmd.exe中是非標准的)時,單行是這樣的:

     @powershell -c ".(iex('{#'+(gc($argv0='%~f0') -raw)+'}'))" %* & goto :eof write-host this is $argv0 arguments: "[$($args -join '] [')]" 

    也可以使用param()聲明, $args不是強制性的。
    $argv0用於補償缺少的$MyInvocation.PS*信息。
    例子:

     G:\\>lala.cmd this is G:\\lala.cmd arguments: [] G:\\>lala.cmd "1 2" "3 4" this is G:\\lala.cmd arguments: [1] [2] [3] [4] G:\\>lala.cmd '1 2' '3 4' this is G:\\lala.cmd arguments: [1 2] [3 4] 
  3. 當傳遞“雙引號”但不包含&和'字符的參數時,我使用雙線代替所有“with”

     @echo off& set A= %*& set B=@powershell -c "$argv0='%~f0';.(iex('{' %B%+(gc $argv0|select -skip 2|out-string)+'}'))" %A:"='%&goto :eof write-host this is $argv0 arguments: "[$($args -join '] [')]" 

    (請注意,在無參數情況的A= %*賦值中,空格很重要。)
    結果:

     G:\\>lala.cmd this is G:\\lala.cmd arguments: [] G:\\>lala.cmd "1 2" "3 4" this is G:\\lala.cmd arguments: [1 2] [3 4] G:\\>lala.cmd '1 2' '3 4' this is G:\\lala.cmd arguments: [1 2] [3 4] 
  4. 最常見的情況是通過環境變量傳遞參數,因此Powershell的param()聲明不起作用。 在這種情況下,參數應該是“雙引號”並且可以包含'或&(除了.cmd文件本身的路徑):

     ;@echo off & setlocal & set A=1& set ARGV0=%~f0 ;:loop ;set /A A+=1& set ARG%A%=%1& shift& if defined ARG%A% goto :loop ;powershell -c ".(iex('{',(gc '%ARGV0%'|?{$_ -notlike ';*'}),'}'|out-string))" ;endlocal & goto :eof for ($i,$arg=1,@(); test-path -li "env:ARG$i"; $i+=1) { $arg += iex("(`${env:ARG$i}).Trim('`"')") } write-host this is $env:argv0 arguments: "[$($arg -join '] [')]" write-host arg[5] is ($arg[5]|%{if($_){$_}else{'$null'}}) 

    (注意,在第一行A=1&並且不得包含空格。)
    結果:

     G:\\>lala.cmd "ab" "cd" "e&f" 'g' "h^j" this is G:\\lala.cmd arguments: [ab] [cd] [e&f] ['g'] [h^j] arg[5] is $null 

暫無
暫無

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

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