是否可以在PowerShell中同时运行2个函数?

时间:2017-02-07 08:16:46

标签: function powershell

在PowerShell脚本中我有

function f1{ do something}
function f2{ do something else}
button1
button2
richtextbox

当我按button1时,它会运行f1并输出richtextbox中的数据。 当我按button2时,即使f2尚未完成,我也需要脚本运行f1。来自f2的数据我不需要在同一richtextbox中输出它,它可以是不同的。$print_equip_button.Add_Click({ print "link.php?data=$data" $file_location $type }.GetNewClosure()) 。 我的问题是:PowerShell中可以同时运行2个不同的函数吗?

更新: 对于我的PowerShell脚本,我已经完成了一个GUI,它有一堆按钮可以执行不同的操作。 当我按下一个按钮时,它开始连接到串行设备并将数据输出到richtextbox,并在某些时候将数据保存到文本文件中。 其他2个按钮具有以下功能:它从保存的文本文件中获取部分数据,打开临时php Web服务器,打开创建pdf文件的链接,然后将文件发送到正确的打印机/托盘进行打印。 这两个按钮我刚注意到它们有效。 我的问题是弹出窗体中的按钮。 我的主窗体中的另一个按钮会打开一个弹出窗体,并使用上面保存的文本文件中的数据填充它。

$print_equip_button.Add_Click({
    Start-Job -ScriptBlock {print "link.php?data=$data" $file_location $type}
}.GetNewClosure())

在主窗体中,上面的代码工作,从弹出窗口它没有。 也试过没有运气。

for($i=1;$i -le 100;$i++){
    [System.Windows.Forms.Application]::DoEvents()
    start-sleep -s 1
    $LogTextBox.Text = "$temp`n" + "Count $i"
}

我在函数的开头添加了

#include <Windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdline, int nCmdShow)
{
    MessageBox(NULL, "Hello!!", "Message", MB_OK);
    return 0;
}

当我按下弹出窗口中的按钮时,看看函数f1会发生什么,当我打开弹出窗口时,计数停止并在我关闭时继续。

更新: 我发现如果我在PowerShell ISE中打开脚本并从那里运行它,那么一切都按照我想要的方式运行而不需要“Start-Job”。 单独运行.ps文件时,它不起作用,甚至不能使用“Start-Job”

2 个答案:

答案 0 :(得分:0)

作业和运行空间都会为你做这个,记住你必须专门从函数中获取信息,只是在不同的线程中运行它不会给你一个返回,因为输出将是一个单独的线程。

单个函数的作业更好,这需要很长时间,例如部署ovf,并且运行空间更适合更广泛的功能,例如并行ping 1000台机器。

您可以使用receive-job从开始作业中获取结果。

答案 1 :(得分:0)

你可以通过使用runspaces的异步ui更新来完成这个:

  $button1_Click={

$ps = [powershell]::create()
$ps.AddScript(
     {
     #replace with your function definition
       while($true){
        $richtextbox1.appendtext("1")
        start-sleep 1
        }
    }
)

$ps.Runspace.SessionStateProxy.SetVariable("richtextbox1", $richtextbox1)
$ps.BeginInvoke()
}


$button2_Click={
$ps2 = [powershell]::create()
$ps2.AddScript(
     {
      #replace with your function definition
       while($true){
        $richtextbox2.appendtext("1")
        start-sleep 1
        }
    }
)


$ps2.Runspace.SessionStateProxy.SetVariable("richtextbox2", $richtextbox2)
$ps2.BeginInvoke()


    }
相关问题