I have the following PowerShell module called module.psm1. This is a simplified example. I am doing actions against SharePoint 2013 so I need the snapin for SharePoint in my module
function Test() {
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Write-Verbose "Adding" -Verbose
Add-PSSnapin "Microsoft.SharePoint.PowerShell" -Verbose
}
else {
Write-Verbose "Already loaed" -Verbose
}
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -ne $null) {
Write-Verbose "Removing" -Verbose
#Remove-PSSnapin "Microsoft.SharePoint.PowerShell" -Verbose
}
else {
Write-Verbose "Already removed" -Verbose
}
Get-PSSnapin "Microsoft.SharePoint.PowerShell"
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null) {
Write-Verbose "Adding" -Verbose
Add-PSSnapin "Microsoft.SharePoint.PowerShell" -Verbose
}
else {
Write-Verbose "Already loaded" -verbose
}
}
Export-ModuleMember -Function 'Test'
In my moduletest.ps1 I have a call to Test and the same logic
Import-Module "$PSScriptRoot\module.psm1" -Force
Test
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Write-Verbose "Adding" -Verbose
Add-PSSnapin "Microsoft.SharePoint.PowerShell" -Verbose
}
else {
Write-Verbose "Already loaed" -Verbose
}
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -ne $null) {
Write-Verbose "Removing" -Verbose
Remove-PSSnapin "Microsoft.SharePoint.PowerShell" -Verbose
}
else {
Write-Verbose "Already removed" -Verbose
}
Get-PSSnapin "Microsoft.SharePoint.PowerShell"
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null) {
Write-Verbose "Adding" -Verbose
Add-PSSnapin "Microsoft.SharePoint.PowerShell" -Verbose
}
else {
Write-Verbose "Already loaded" -verbose
}
When I run function Test from the module the output is:
VERBOSE: Adding
VERBOSE: Removing
VERBOSE: Performing the operation "Remove-PSSnapin" on target "Microsoft.SharePoint.PowerShell".
VERBOSE: Already loaded
So in the module when I remove the SNapIn somehow its not really gone. When I run the code directly form the ps1 file I get:
VERBOSE: Adding
VERBOSE: Removing
VERBOSE: Performing the operation "Remove-PSSnapin" on target "Microsoft.SharePoint.PowerShell".
VERBOSE: Adding
When in my ps1 file the Remove does actually completely remove the SnapIn. Is this normal behavior? I see same behavior for other SnapIns.
Another question I have is:
When I import the module from the console and when I load the SnapIn from my module and execute a command from the snapin in the console then no cmdlets are recognized. When I load the snapin in the module is that being done in a different scope or context?