【问题标题】:How to pass a parameter from Batch file to a function inside a Powershell script如何将批处理文件中的参数传递给Powershell脚本中的函数
【发布时间】:2009-07-08 19:49:27
【问题描述】:

我有一个批处理文件,它将调用一个 Powershell 脚本:

批处理文件: @ECHO 关闭 powershell ..\PowerShellScript.ps1

powershell 脚本又具有一个需要参数的函数:

POWERSHELL 脚本:

function PSFunction([string]$Parameter1)
{
Write-Host $Parameter1
}

假设我有一个值:VALUE1 需要在调用 PowerShellScript.ps1 时从批处理文件传递,我如何将它传递给函数 PSFunction 以便我的输出是 VALUE1?

【问题讨论】:

    标签: powershell batch-file parameter-passing


    【解决方案1】:

    修改你的脚本,如下所示

    function PSFunction([string]$Parameter1)
    {
      Write-Host $Parameter1
    }
    
    PSFunction $args[0]
    

    从批处理文件来看,它看起来像

    powershell ..\PowerShellScript.ps1 VALUE1
    

    【讨论】:

    • 以及如何从批处理文件中传递参数值“VALUE1”?
    【解决方案2】:

    使用 -Command 开关告诉 powershell.exe 解释字符串,就好像它是在 PowerShell 提示符下键入的一样。在您的情况下,该字符串可以点源 PowerShellScript.ps1(将其导入新的 powershell.exe 环境),然后使用 VALUE1 作为参数调用 PSFunction:

    set VALUE1=Hello World
    powershell.exe -command ". ..\PowerShellScript.ps1; PSFunction '%VALUE1%'"
    

    【讨论】:

      【解决方案3】:

      在 Powershell 脚本中定义函数并执行该函数。如果你想要这样,那么你的脚本可能需要看起来像这样:

      function PSFunction([string]$Parameter1)
      {
        Write-Host $Parameter1
      }
      PSFunction "some string"
      

      在脚本中,您仍然有一个动态的$args 变量,它可以获取您传递给脚本的任何参数。所以

      function PSFunction([string]$Parameter1)
      {
        Write-Host $Parameter1
      }
      PSFunction $args[0]
      

      会将您在命令行中提供的第一个参数传递给函数。

      【讨论】:

        【解决方案4】:

        在我看来,您应该简单地选择使用什么 - 批处理文件或 PowerShell:) PowerShell 更强大,但批处理文件更容易创建(尤其是使用 Dr.Batcher)并且可以在任何地方运行。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-23
          • 2011-09-15
          • 2013-02-16
          • 1970-01-01
          • 1970-01-01
          • 2011-12-14
          • 1970-01-01
          相关资源
          最近更新 更多