[英]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.