[英]PowerShell module installed manually. cmdlets found with help but not recognized when executed
[英]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, ....
我以为会话已获得,但是一旦函数完成运行,该函数的“子外壳”就消失了。 因此我试过
PS> . get-365session
但这无济于事。
希望有办法,有人可以帮助我。 非常感谢!
您需要使用带有-Global
标志的Import-Module
在当前范围内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
参考
本地函数和变量在其他会话中不可用。 但是,您可以使用以下技巧将您的函数指定为脚本块:
Invoke-Command -Session $session -ScriptBlock ${Function:My-FunctionName}
我上面链接的文章详细介绍了更高级的用例,但因为您的脚本似乎不需要任何参数。 请注意,这需要使用Invoke-Command
在另一个会话中运行代码,从定义函数的会话开始,所以我不确定如何(如果可以)获取函数主体(如果您已经完成) Enter-PSSession
并且当前处于远程会话中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.