我有以下名为 module.psm1 的 PowerShell 模块。这是一个简化的例子。我正在针对 SharePoint 2013 执行操作,因此我需要模块中的 SharePoint 管理单元
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'
在我的 moduletest.ps1 中,我调用了 Test 和相同的逻辑
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
}
当我从模块运行功能测试时,输出是:
VERBOSE: Adding
VERBOSE: Removing
VERBOSE: Performing the operation "Remove-PSSnapin" on target "Microsoft.SharePoint.PowerShell".
VERBOSE: Already loaded
所以在模块中,当我以某种方式移除 SNapIn 时,它并没有真正消失。当我直接从 ps1 文件运行代码时,我得到:
VERBOSE: Adding
VERBOSE: Removing
VERBOSE: Performing the operation "Remove-PSSnapin" on target "Microsoft.SharePoint.PowerShell".
VERBOSE: Adding
在我的 ps1 文件中,Remove 实际上完全删除了 SnapIn。这是正常行为吗?我看到其他 SnapIn 的行为相同。
我的另一个问题是:
当我从控制台导入模块并从模块加载管理单元并从控制台中的管理单元执行命令时,不会识别任何 cmdlet。当我在模块中加载管理单元时,是在不同的范围或上下文中完成的吗?