powershell - 在 Powershell 中使用带有 BeginInvoke 的 PSDataCollection

标签 powershell powershell-2.0

我正在尝试在我的 PowerShell 脚本中处理来自管道的输出。现在我看到输出的唯一方法是当我发出 EndInvoke管道的方法,但由于我的一些调用可能会长时间运行并且可能有很多输出,所以我希望能够在进程运行时显示输出。

看起来我可以通过将输入和输出参数传递给 BeginInvoke 来做到这一点。方法,但我似乎无法获得正确的语法。有什么建议么?我正在尝试的一个例子如下:

$scriptBlock = {param([int]$pauseTime = 10); Write-Output "Test"; Start-Sleep -Seconds $pauseTime; Write-Output "Test 2"}

# Create objects and set stuff up
$initialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$runspacepool = [Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1, 4, $initialSessionState, $Host)
$runspacepool.Open()
$pipeline = [powershell]::Create().AddScript($scriptBlock).AddParameter("pauseTime", 30)
$pipeline.RunspacePool = $runspacepool

# These two lines are not correct
$inputStream = New-Object [System.Management.Automation]
$outputStream = New-Object [System.Management.Automation.PSDataCollection]

$async = $pipeline.BeginInvoke($inputStream, $outputStream)

# Do something with the $outputStream here???

$pipeline.EndInvoke($async)

# Clean-up code    
$pipeline.Dispose()
$async = $null
$pipeline = $null
if ($runspacepool -ne $null) {$runspacepool.Close()}

最佳答案

我不知道您要完成什么(对于处理脚本输出的简单目的,它看起来过于复杂)但是通过对 PowerShell 脚本的这个小修改,至少您会得到一个输出:

` $scriptBlock = {
参数([int]$pauseTime = 1)
写输出“测试 1”
开始- sleep -秒 $pauseTime
写输出“测试 2”
}

# 创建对象并设置东西
$initialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$runspacepool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1, 4, $initialSessionState, $Host)
$runspacepool.Open()
$pipeline = [powershell]::Create().AddScript($scriptBlock).AddParameter("pauseTime", 5)
$pipeline.RunspacePool = $runspacepool

$outputStream = New-Object -Typename System.Management.Automation.PSDataCollection[PSObject]

$async = $pipeline.BeginInvoke()
1..10 | Foreach { "我在等待...";开始 sleep - 毫秒 500 }

$outputStream = $pipeline.EndInvoke($async)

# 清理代码
$pipeline.Dispose()
$异步 = $null
$管道 = $null
if ($runspacepool -ne $null) {$runspacepool.Close()}

$输出流
`

关于powershell - 在 Powershell 中使用带有 BeginInvoke 的 PSDataCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11000801/

相关文章:

visual-studio - 如何将参数转义到在 VS 构建后事件中运行的 PS 脚本

Regex Group,捕获 IP 的问题

arrays - 使用数组和脚本 block 安装多个应用程序的 Powershell 脚本

powershell - 如何使用PowerShell为MSBuild属性设置值

powershell - 将两次或多次调用 Get-ChildItem 的结果加入一个数组的最简洁方法是什么?

powershell - Powershell中的Out-File -append不会产生新行,并且会将字符串分成字符

powershell - PowerShell 中是否有字符串连接快捷方式?

c# - ImportPS 模块故障检测

powershell - 使用 PowerShell 合并多个文本文件并生成一个新的单个文本文件?

powershell - 获取日期格式/文化