【问题标题】:Encapsulate the output of invoke command in a variable - PowerShell将调用命令的输出封装在一个变量中 - PowerShell
【发布时间】:2017-07-23 15:09:41
【问题描述】:

我有一个脚本可以在远程机器上安装远程桌面服务(来自 DC)。

我现在处于检查 RDS 是否安装在连接代理(服务器)和连接主机(服务器)上的阶段。

我想使用调用命令,因为远程 powershell 会话似乎太复杂了。

这是我的代码:

$res = Invoke-Command -ComputerName "testpc.eil.local" -ScriptBlock {
if((Get-WindowsFeature -Name "Remote-Desktop-Services").Installed -eq 1)
{
   #i need this output (true or false or a string)
}
else
{
     #i need this output (true or false or a string)
}
}


Write-Host $res

但我的问题是,如何将调用命令中脚本块的输出封装在 DC 可以访问的变量中?如果 RDS 成功安装或未能写入日志文件,我正在尝试写掉

我们如何封装函数的输出并将其传递给运行它的机器?

谢谢

【问题讨论】:

    标签: powershell variables scripting invoke-command storing-data


    【解决方案1】:

    通常对于 powershell 从命令\函数返回一些东西,你想要产生任何类型的输出。因此,代码中的“bla-bla”将返回“bla-bla”给调用者。这样你的情况就简化了:

    $res = Invoke-Command -ComputerName "testpc.eil.local" -ScriptBlock {
        (Get-WindowsFeature -Name "Remote-Desktop-Services").Installed
    }
    
    do something with $res here
    

    【讨论】:

    • 非常感谢,奇怪的是你的方法有效,而我的方法不行嘿嘿!
    • 就像我说的,你的不是因为你实际上没有输出任何东西。你需要输出东西才能捕捉到一些东西
    • 好的,但是当我将它包含在我的第一个脚本中时,我想知道为什么我不能只写 Write-Host "Installed!"。 (如果测试)但如果我理解正确,那是因为它打印在远程服务器的“窗口”中,而不是来自 DC 的那个?
    • 是的,不要使用write-host,一般来说,它搞砸了,使用write-output
    • 感谢您的回答!多亏了你的解释,我明白了
    猜你喜欢
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2022-01-22
    • 2022-06-23
    • 2022-08-14
    相关资源
    最近更新 更多