Move computer object in a SCCM Task Sequence using a PowerShell script

This script is useful if you re-image a machine which will re-use its AD computer name, or a new machine which needs to be moved to a specific OU chosen in a HTA.
Follow the steps in the script description to accomplish this and match the step in the image.

The script:

<#

    .SYNOPSIS
    Move PC object during a SCCM Task Sequence in WinPE.

    .DESCRIPTION
    1.Create a package containing this script
    2.Run the package in a 'Run Command Line' step after the 'Setup Windows and Configuration Manager Client' step
    3.Use this commandline:
    CMD.EXE /C %SYSTEMDRIVE%\windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File .\Move-ToOU.ps1 "%OSDOUName%"
    4.Run the step with a user with the needed previledges
    NOTE: The write-host will log to the smsts.log

    .PARAMETER

    .EXAMPLE

    .NOTES
    Author: Morten Rønborg
    Date: 29-10-2018
    Last Updated: 28-11-2018
    https://mroenborg.com

#>

################################################
param(
    $TargetOU
)

#Import all used modules (in some winPE versions this is not done automatically)
Import-Module -Name C:\windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Management
Import-Module -Name C:\windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Utility

Function Move-ComputerObject{
    param(
        $TargetOU # "OU=WIN10,OU=Workstations,OU=Copenhagen,DC=ad,DC=mutsdomain"
    )

    try {
        # Define object
        $SysInfo = New-Object -ComObject "ADSystemInfo"
        $ComputerDN = $SysInfo.GetType().InvokeMember("ComputerName", "GetProperty", $Null, $SysInfo, $Null)
        Write-Host "Current location of this PC : $ComputerDN"

        # Bind to computer object in AD.
        $Computer = [ADSI]"LDAP://$ComputerDN"

        # Bind to target OU.
        Write-Host "Moving PC to : $TargetOU"

        # Move computer to target OU.
        $Computer.psbase.MoveTo([ADSI]"LDAP://$($TargetOU)")
    }
    catch {
        Write-Host $_
    }

}
Write-Host "***********************************RUNNING MOVE TO OU***********************************"
Write-Host "Running in the context : $Env:USERNAME"

#Move the PC
Move-ComputerObject $TargetOU

Write-Host "***********************************FINISHED MOVE TO OU***********************************"

1 thought on “Move computer object in a SCCM Task Sequence using a PowerShell script”

Leave a comment