将参数传递给Workflow(powershell)

时间:2016-12-22 16:56:23

标签: powershell

我知道您无法在工作流程中使用Read-Host。但我需要通过Read-Host提示用户,然后在工作流中使用该输入数据。我们需要在远程机器上执行MSG.EXE(因为NetSend再见)

我有这个代码。它运行没有错误,但它不发送任何消息。如何将我的论证传递给工作流程以使其有效?

$Computers = @("mg2014","cclab2","MG11751","mg10462","mg11768","mg11786","mg11741","mg13244","mg13434","mg14464", "mg10257")

workflow Test-WFConnection {
    param(

         [Parameter (Mandatory = $true)]
        [object[]]$message
    )

foreach -parallel ($computer in $computers) {
if (Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue) {msg /SERVER:$computer * $msg}

  }
}

$msg = Read-host "Enter your message here"
Test-WFConnection -message $msg

问题是$ msg永远不会被发送到任何机器。

4 个答案:

答案 0 :(得分:0)

要处理工作流程,您必须了解工作流程中的范围。这里, $ msg 的值与范围无关,这就是为什么该值根本不在块内。所以你必须使用 $ Using:msg ,然后它才可用。

我将在下面举一个小例子来澄清你的疑问:

workflow sample_test
{
    $variable1 = 5

    # Changes to variable value in an InlineScript do not affect
    # the value of the workflow variable.
    InlineScript {$variable1 = $Using:variable1 + 1; "Inline Variable1 = $variable1"}
    "Workflow variable1 = $variable1"
    # To change the value in workflow scope, return the new value.
     $a = InlineScript {$variable1 = $Using:variable+1; $variable1}
     "Workflow New variable1 = $variable1"
}

以下是供您参考的屏幕截图:

enter image description here

希望它有所帮助...... !!!

答案 1 :(得分:0)

如何在工作流程中声明计算机?

workflow send-message {
param(
  [Parameter (Mandatory = $true)]
  [string]$message
)

$computers = "mg2014","cclab2","MG11751","mg10462","mg11768","mg11786","mg11741","mg13244","mg13434","mg14464", "mg10257"
foreach -parallel ($computer in $computers){
if (Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue){
  msg /SERVER:$computer * $message
}}}

send-message -message (read-host 'Enter message')

当我测试它时,这工作正常。 正如此处所述:https://community.spiceworks.com/topic/1951356-pass-argument-to-workflow

答案 2 :(得分:0)

您可以将计算机作为参数传递,或者是否有任何限制阻止您这样做:

$Computers = @("mg2014","cclab2","MG11751","mg10462","mg11768","mg11786","mg11741","mg13244","mg13434","mg14464", "mg10257")

workflow Test-WFConnection {
    param(

         [Parameter (Mandatory = $true)]
        [object[]]$message,[object[]]$computers
    )

foreach -parallel ($computer in $computers) {
if (Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue) {msg /SERVER:$computer * $msg}

  }
}

$msg = Read-host "Enter your message here"
Test-WFConnection -message $msg  -computers $Computers

答案 3 :(得分:0)

我不确定这些答案是怎么回事-它们有点晦涩。

Neal5的答案是正确的答案,但没有真正说明原因(尽管我也建议像Abhijith pk的答案一样将计算机列表作为参数添加。)

问题是在满足条件的情况下运行的语句:

if (Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue) {
  msg /SERVER:$computer * $msg
}

您在此处使用$msg,但是您已将参数命名为$message

param(
    [Parameter (Mandatory = $true)]
    [object[]]$message
    )

因此,您的声明应为:

  msg /SERVER:$computer * $message