2017-05-29 45 views
0

我试图从调用PowerShell脚本的Windows运行时传递一些参数。看起来像这样: myscript“一些参数”,“其他” 这甚至可能吗?如果是这样,我怎么能从它的参数到powershell脚本并使用它们? 到目前为止,我得到了如何通过使用参数的“ValueFromPipelineByPropertyName”选项通过cmd询问用户输入参数,但它不是我想要的。 在此先感谢。从powershell中运行的窗口参数

回答

1

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(少量参数按照定义良好的顺序)。完整的参数定义使您可以更好地控制参数处理(可以使参数可选或强制,定义参数类型,定义默认值,进行验证等)。

+0

这正是我所寻找的。谢谢:) –

0

我几乎不明白你的问题。下面是一个试图接近你想要的东西..

您尝试通过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" 
+0

上命名参数进一步阅读:http://powershell-guru.com/powershel l-best-practice-2-use-named-parameters-not-positions-and-partial-parameters/ –

0

在脚本的声明你要传递的参数上,这里是从我的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 
+0

我试过这样做,但没有奏效。也许我错过了什么 –

相关问题