我需要在运行空间中执行Get-MailboxStatistics。我可以连接到Exchange online。如果我执行“Get-Pssession”,我可以看到Exchange会话。但是我如何将这个ExchangeOnline会话传递给运行空间来执行Get-MailboxStatistics呢?当前,它无法识别运行空间中的Get-MailboxStatistics命令。
下面是我的代码(这是一个更大的脚本的一部分):
# Connecting to Exchange Online
$AdminName = "hil119"
$Pass = "password"
$cred_cloud = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
Connect-ExchangeOnline -Credential $cred_cloud -Prefix Cloud
# Executing Get-MailboxStatistics in a Runspace
$Runspace = [runspacefactory]::CreateRunspace()
$PowerShell = [powershell]::Create()
$PowerShell.runspace = $Runspace
$Runspace.Open()
[void]$PowerShell.AddScript({Get-MailboxStatistics 'd94589'})
$PowerShell.BeginInvoke()发布于 2021-02-16 10:53:41
经过几天的研究,我发现您可以在本地系统或远程Exchange服务器上运行线程。如果您在本地系统上运行它,那么每个线程都需要自己调用Exchange会话,但是如果您在远程交换系统(onprem或cloud)上运行它,您只能获取交换会话一次,并将该会话传递给该线程。您可以使用Invoke命令获取远程会话。此外,我最终在Poshjob或runspace中编写了脚本。最终,从我所读到的内容来看,Poshjob是Start-job和runspace的组合。
下面是用于在远程服务器上运行Thread的代码片段。使用此脚本,您可以将相同的交换会话传递给所有线程。
Function Func_ConnectCloud
{
$AdminName = "r43667"
$AdminPassSecure = "pass"
$Cred_Cloud = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $AdminPassSecure
Connect-ExchangeOnline -Credential $Cred_Cloud
$CloudSession = Get-PSSession | Where { $_.ComputerName -like "outlook.office365*"}
Return $CloudSession
}
$script_Remote =
{
param(
$Alias,
$CloudSession
)
Invoke-Command -session $CloudSession -ArgumentList $Alias -ScriptBlock {param($Alias); Get-MailboxStatistics $Alias}
}
$CloudSession = Func_ConnectCloud
$Alias = 'h672892'
$Job1 = Start-RsJob -Name "job_$Alias" -ScriptBlock $ScriptRemote -ArgumentList $Alias, $CloudSession
Receive-RsJob $Job1
Remove-RsJob $Job1
您可以使用此脚本在onprem和cloud上运行线程,尽管当在云服务器上运行时,Microsoft将只允许两个线程。如果运行两个以上的线程,Exchange会话将被终止(这与限制不同)。因此,如果你有一个云环境,那么最好在本地运行你的线程。他在https://powershell.org/forums/topic/connecting-to-office-365-in-psjobs/上的脚本特别引用了@postanote
https://stackoverflow.com/questions/66070453
复制相似问题