PowerShell 5.1 到 PowerShell 7 引发 ActiveDirectory 错误

问题描述 投票:0回答:1

我们正在将 PowerShell 5.1 升级到 PowerShell 7,并且遇到一些有关模块“ActiveDirectory”的问题。

Import-Module ActiveDirectory -SkipEditionCheck

$adGroup = New-Object Microsoft.ActiveDirectory.Management.ADGroup Identity -Property @{
    Description    = 'ROL group'
    CanonicalName  = 'contoso.com/Groups/test'
    SamAccountName = 'test'
    GroupCategory  = 'Security'
    GroupScope     = 'Universal'
}

这会引发 2 个错误:

无法从程序集“System.Management.Automation,版本=7.3.8.500,Culture=neutral,PublicKeyToken=31bf3856ad364e35”加载类型“System.Management.Automation.PSSnapIn”。 新对象:

未找到指定 .NET 对象的成员“Description”。

当我们使用

$adGroup | Get-Member
检查此对象时,似乎属性
Description
CanonicalName
在此对象上不可用。

在 PowerShell 5.1 中,这段代码可以完美运行。模拟在两个 PowerShell 版本中都有效的 AD 安全组的最佳方法是什么?

powershell active-directory
1个回答
0
投票

这可能行不通,我现在这个时候没有环境可以测试。

要解决此问题并创建可在两个 PowerShell 版本中运行的脚本,您可以利用

System.DirectoryServices.AccountManagement
命名空间,它提供了一种在不同 PowerShell 版本之间与 Active Directory 交互的更一致的方式。以下是如何使用此命名空间创建新 AD 组的示例:

# Required for compatibility between PowerShell 5.1 and 7
Add-Type -AssemblyName System.DirectoryServices.AccountManagement

# Establish the context for the domain
$contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $contextType

# Create a new group principal
$groupPrincipal = New-Object System.DirectoryServices.AccountManagement.GroupPrincipal -ArgumentList $principalContext

# Set the properties for the group
$groupPrincipal.Description = 'ROL group'
$groupPrincipal.Name = 'test'
$groupPrincipal.SamAccountName = 'test'
$groupPrincipal.Save()

# Get the newly created group
$newGroup = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($principalContext, 'test')

# Output the group details
$newGroup | Format-List *

使用

System.DirectoryServices.AccountManagement
命名空间有助于创建跨不同版本的 PowerShell 管理 Active Directory 的一致方法。在运行脚本之前,请确保您拥有创建 AD 对象所需的权限。

此方法应该在 PowerShell 5.1 和 PowerShell 7 中无缝工作。

© www.soinside.com 2019 - 2024. All rights reserved.