如何使用powershell模块在runspacepool中使用参数调用powershell ps1文件



我正在学习powershell。目前我有一个严格的要求。我需要从一个powershell模块(psm1)并行调用一个powershell脚本(ps1)。ps1任务类似于下面的

param(
[Parameter(Mandatory=$true)]
[String] $LogMsg,
[Parameter(Mandatory=$true)]
[String] $FilePath
)
Write-Output $LogMsg
$LogMsg | Out-File -FilePath $FilePath -Append

文件路径像"C:UsersuserDocumentsloglog1.log"在psm1文件中,我使用runspacepool来执行异步任务。就像下面的演示

$MaxRunspaces = 5
$RunspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxRunspaces)
$RunspacePool.Open()
$Jobs = New-Object System.Collections.ArrayList
Write-Host $currentPath
Write-Host $lcmCommonPath
$Filenames = @("log1.log", "log2.log", "log3.log")
foreach ($File in $Filenames) {
Write-Host "Creating runspace for $File"
$PowerShell = [powershell]::Create()
$PowerShell.RunspacePool = $RunspacePool
$FilePath = -Join("C:UsersuserDocumentslog",$File)
$PowerShell.AddScript("C:UsersuserDocumentsfoo.ps1").AddArgument($FilePath) | Out-Null

$JobObj = New-Object -TypeName PSObject -Property @{
Runspace = $PowerShell.BeginInvoke()
PowerShell = $PowerShell  
}
$Jobs.Add($JobObj) | Out-Null
}

但是有两个严重的问题。

  1. 无法将参数传递给ps1文件我只是尝试在ps1文件端创建文件路径,它工作和文件创建。但是当我尝试从psm1文件传递参数时。没有创建文件。我也尝试使用脚本块,它可以传递参数。但由于我的ps1代码太大(以上只是其中的一部分),使用脚本块是不真实的。我需要一个方法来传递参数到ps1文件。
  2. 当psm1仍在运行时,无法在ps1文件中获取write-host信息

如果runspacepool对传递参数到ps1文件有限制,是否有其他解决方案来处理powershell脚本的异步任务?谢谢。

无法将参数传递给ps1文件

使用AddParameter()而不是AddArgument()-这将允许您通过名称将参数绑定到特定的形参:

$PowerShell.AddScript("C:UsersuserDocumentsfoo.ps1").
AddParameter('FilePath', $FilePath).
AddParameter('LogMsg', 'Log Message goes here') | Out-Null

当psm1仍在运行时,无法在ps1文件中获取write-host信息

正确-你不能从没有附加到主机应用程序的默认运行空间的脚本中获得主机输出-但如果你使用的是PowerShell 5或更新版本,可以$PowerShell实例收集结果信息并中继,如果你想:

# Register this event handler after creating `$PowerShell` but _before_ calling BeginInvoke()
Register-ObjectEvent -InputObject $PowerShell.Streams.Information -EventName DataAdded -SourceIdentifier 'WriteHostRecorded' -Action {
$recordIndex = $EventArgs.Index
$data = $PowerShell.Streams.Information[$recordIndex]
Write-Host "async task wrote '$data'"
}

刚刚在这里得到了同样的问题,我不能将参数传递给ps1文件与。addscript(),但它工作良好与。addcommand ():

$csv_obj = Import-Csv mailboxList.csv
$MaxRunspaces = 5
$RunspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxRunspaces)
$RunspacePool.Open()
$StartDateTime = Get-Date
#$actionparams = $StartDateTime,$EndDateTime,$MessageId
$Jobs = New-Object System.Collections.ArrayList
foreach($line in $csv_obj){
$Mailbox = $line.recipient
write-verbose $Mailbox -verbose
if( [string]::IsNullOrWhiteSpace($Mailbox) ){continue}
$PowerShell = [powershell]::Create()
$PowerShell.RunspacePool = $RunspacePool
$PowerShell.AddCommand("D:runspacetest.ps1").AddParameter("Mailbox","$Mailbox")
$PowerShell.BeginInvoke()
}

最新更新