dsccommunity / ComputerManagementDsc

DSC resources for for configuration of a Windows computer. These DSC resources allow you to perform computer management tasks, such as renaming the computer, joining a domain and scheduling tasks as well as configuring items such as virtual memory, event logs, time zones and power settings.
https://dsccommunity.org
MIT License
295 stars 81 forks source link

[DSC_Computer] Problem with Delete-ADSIObject #414

Closed rcarpenter79 closed 1 year ago

rcarpenter79 commented 1 year ago

Problem description

The constructor for 'System.DirectoryServices.DirectoryEntry' in Delete-ADSIObject is using the wrong variable. It is using $DomainName as the first argument instead of $Path

Verbose logs

This causes the machine to be added to the domain but the rename fails when there is an existing computer object in AD.

When running the code for Delete-ADSIObject directly DeleteTree() returns an unspecified error has occurred.

DSC configuration

# 'ComputerName' must exist in 'DomainName' for this problem to occur

Computer 'NameAndDomain'
{
    Name       = 'ComputerName'
    DomainName = 'DomainName'
    Credential = $Credential
}

Suggested solution

Replace $DomainName with $Path

function Delete-ADSIObject
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateScript( { $_ -imatch "LDAP://*" })]
        [System.String]
        $Path,

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $Credential
    )

    $params = @{
        TypeName     = 'System.DirectoryServices.DirectoryEntry'
        ArgumentList = @(
            $DomainName,
            $Credential.UserName
            $Credential.GetNetworkCredential().password
        )
        ErrorAction  = 'Stop'
    }
    $adsiObj = New-Object @params

    $adsiObj.DeleteTree()
}

Operating system the target node is running

Server 2022

PowerShell version and build the target node is running

Name                           Value
----                           -----
PSVersion                      5.1.20348.1850
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.20348.1850
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

ComputerManagementDsc version

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     9.0.0      ComputerManagementDsc