繁体   English   中英

如何将参数从批处理文件传递到Powershell脚本中的函数

[英]How to pass a parameter from Batch file to a function inside a Powershell script

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

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

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

POWERSHELL SCRIPT:

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

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

将脚本修改为如下所示

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

PSFunction $args[0]

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

powershell ..\PowerShellScript.ps1 VALUE1

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

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

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

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

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

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

将您在命令行上给出的第一个参数传递给该函数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM