在函数中执行powershell会话连接cmdlet时不工作

在函数中执行powershell会话连接cmdlet时不工作,powershell,office365,Powershell,Office365,我通过发出一系列powershell命令连接到云中的Exchange: $credential = new-object -typename ... -argumentList ... $session = New-PSSession -configurationName ... -connectionUri ... -credential $credential ... Import-PSSession $session ... 然后,我可以发出命令来做我需要做的事情,例如 get-mail

我通过发出一系列powershell命令连接到云中的Exchange:

$credential = new-object -typename ... -argumentList ...
$session = New-PSSession -configurationName ... -connectionUri ... -credential $credential ...
Import-PSSession $session ...
然后,我可以发出命令来做我需要做的事情,例如

get-mailbox | ? {$_.aliast -like "*[.]*"} | select alias

alias
-----
john.public
jane.doe
...
但是,用于获取PSSession的cmdlet很长,即使我能够正确地记住它们,输入它们也很容易出错。因此,我将所有三条长命令行逐字保存在一个函数中:

function get-365session() {
   $credential = new-object -typename ... -argumentList ...
   $session = New-PSSession -configurationName ... -connectionUri ... -credential $credential ...
   Import-PSSession $session ...
}
但结果并不像预期的那样:

PS> get-365session
ModuleType Version    Name             ExportedCommands
---------- -------    ----             -----------------
...

PS> get-mailbox 
get-mailbox: The term 'get-mailbox' is not recognized as the name of a cmdlt, function, script file, ....
我原以为会话已获得,但在函数完成运行后,它就随函数的“子shell”一起消失了。因此,我努力了

PS> . get-365session
但是没有用


希望有办法,有人能帮我。非常感谢

本地函数和变量在其他会话中不可用。但是,可以使用将函数指定为脚本块:

Invoke-Command -Session $session -ScriptBlock ${Function:My-FunctionName}

我在上面链接的文章更详细地介绍了更高级的用例,但是您的脚本似乎不需要任何参数。请注意,这需要使用
Invoke命令
从定义函数的会话在另一个会话中运行代码,因此如果可以,我不确定如何,如果您已经执行了
输入PSSession
并且当前处于远程会话中,则获取函数体。

您需要使用带有
-Global
标志的
导入模块导入当前范围内的会话

您的
Import PSSession
行应该如下所示

导入模块(导入PSSession$session365-AllowClobber)-全局

以下是一个工作示例:

function Connect-O365{
    $o365cred = Get-Credential username@domain.onmicrosoft.com
    $session365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $o365cred -Authentication Basic -AllowRedirection 
    Import-Module (Import-PSSession $session365 -AllowClobber) -Global
}

Connect-O365
参考


谢谢萨奇·波尔普。这正是我们想要的。非常感谢。非常感谢Bender分享这个技巧。当我有时间转身时,我会试试看。