我正在处理几个Powershell函数,它们连接到Office365服务,并自动执行我的许多常规任务。当我在psm1中运行函数以连接到ExchangeOnline时,我发现这些函数不会向控制台公开,只有同一模块中的函数才会公开。
虽然我知道我可以导出模块成员,但这只适用于模块加载时的函数,发生在我连接之前-Office365 -exchangeonline。
是否可以导出在连接后连接到Office 365时加载的命令?
通过将以下函数放置在psm1中而不是ps1中并加载它,然后运行connect-off365 -exchangeonline,所有与Exchange Online相关的命令在控制台中都不可用。然而,在ps1中拥有相同的函数并加载它,ExchangeOnline函数就可以工作了。
Function Connect-Office365 {
Param(
[Switch]$ExchangeOnline,
[Switch]$EO
)
if ($EO) { $ExchangeOnline = $true }
elseif ($EO -and $ExchangeOnline) { Write-Warning "No need to declare ExchangeOnline and EO" }
$Credential = Get-Credential -message "Enter Office 365 credentials,`r`nor cancel to not connect to Office 365"
if ($null -eq $Credential) { Write-Host "Skipped entering credentials"; $TryAgain = $False }
if ($ExchangeOnline) {
Write-Host "Connecting to Exchange Online Services"
$global:ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Credential -Authentication Basic -AllowRedirection -EA stop
Import-PSSession $global:ExchangeSession -AllowClobber -DisableNameChecking
}
}例如
PS C:\Users\TechWithAHammer> import-module C:\scripts\Connect-Office365.psm1
PS C:\Users\TechWithAHammer> connect-office365 -eo Connecting to MSOL Services Connecting to Exchange Online Services
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 1.0 tmp_3zvdxnnc.gd0 {Add-AvailabilityAddressSpace, Add-DistributionGroupMember...
PS C:\Users\TechWithAHammer> get-mailbox
get-mailbox : The term 'get-mailbox' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ get-mailbox
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (get-mailbox:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException发布于 2020-02-22 04:26:05
根据Commands from implicit remoting module not available when created from another module's function中的答案,我发现我必须使用导入模块将Exchange Online以及合规性和安全中心模块导入到全局会话中。
导入-模块(导入-PSSession $global:ExchangeSession -AllowClobber -DisableNameChecking) -Global
https://stackoverflow.com/questions/60332988
复制相似问题