繁体   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