在函数中执行时,Powershell 会话连接 cmdlet 不起作用

powershell session connection cmdlets not work when executed in function

我通过发出一系列 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, ....

我以为会话已获得,但在函数完成其 运行 后立即与函数的 "sub-shell" 一起消失了。因此我尝试了

PS> . get-365session

但是没有用。

希望有办法,有人可以帮助我。非常感谢!

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

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

我上面链接的文章详细介绍了更高级的用例,但是您的脚本似乎不需要任何参数。请注意,这需要使用 Invoke-Command 到 运行 另一个会话中的代码, 来自定义函数的会话 ,所以我不是如果您已经完成 Enter-PSSession 并且当前处于远程会话中,请确定如何获取函数体。

您需要使用带有 -Global 标志的 Import-Module 在当前范围内导入会话。

你的 Import-PSSession 行应该看起来像

Import-Module (Import-PSSession $session365 -AllowClobber) -Global

这是一个工作示例:

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

参考

This technet forum thread from 2012