Import-Pssession does not import cmdlets when used in a custom module

I have a PowerShell script / function that works fine when I use it in my PowerShell profile or manually copy / paste this function in a PowerShell window.

I am trying to make a function available to other members of my team as a module. I want the module to be stored in a central location, so we can all add it to our PSModulePath.

Here is a copy of the main function:

Connect-O365 Function {$ o365cred = Get-Credential username@domain.onmicrosoft.com $ session365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $ o365cred -Authentication Basic -AllowRedirection Import -PSSession $ session365 -AllowClobber}

If I save this feature in my PowerShell profile, it works fine. I can calculate the source of a * .ps1 script with this function in it, and it also works.

The problem is that I save this function as a * .psm1 PowerShell script module. The function works fine, but none of the exported commands from Import-PSSession are available. I think this may have something to do with the scope of the module.

I am looking for suggestions on how to get around this.

EDIT

When I create the next module and run Connect-O365, the imported cmdlets will not be available.

$ scriptblock = {Connect-O365 Function {$ o365cred = Get-Credential username@domain.onmicrosoft.com $ session365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri " https://ps.outlook.com/powershell/ " -Credential $ o365cred -Authentication Basic -AllowRedirection Import-PSSession $ session365 -AllowClobber}}

New-Module -Name "Office 365" -ScriptBlock $ scriptblock

When I import the next module without Connect-O365, the imported cmdlets are available.

$ scriptblock = {$ o365cred = Get-Credential username@domain.onmicrosoft.com $ session365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri " https://ps.outlook.com/powershell/ " -Credential $ o365cred -Authentication Basic -AllowRedirection Import-PSSession $ session365 -AllowClobber}

New-Module -Name "Office 365" -ScriptBlock $ scriptblock

This seems like a scope issue, just not sure how to get around it.

+4
source share
1 answer

With some help from TechNet, I managed to modify the script module to make it work as I expected.

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

TechNet Post

+8
source

Source: https://habr.com/ru/post/1447610/


All Articles