In this post, I will show you how to use Powershell for enabling or disabling OU protection in Active Directory.
In my last post, we have seen how to query Organization Units in Active Directory that has protection enabled. Now we will see how to enable or disable this protection option using PowerShell.
As I said earlier, the ProtectedFromAccidentalDeletion property of OU object stores the status of protection. In the below script I am using Set-ADOrganizationalUnit cmdlet from ActiveDirectory module to set this property.
The script takes DN of the OU object as input and verifies if it exists (see my previous post). It does it as part of parameter validation so that script can exit if a wrong OU path is provided. Rest of the code is very simple, and I hope it doesn’t require any explanation. However, please feel free to post questions if you have any.
Test this script in your test environment before you decide to use in production.
CODE:
function Set-OUProtection { [cmdletbinding()] param( [parameter(ParameterSetName="Enable")] [parameter(ParameterSetName="Disable")] [ValidateScript({[ADSI]::Exists("LDAP://$_")})] [string]$DN, [parameter(ParameterSetName="Enable")] [switch]$Enable, [parameter(ParameterSetName="Disable")] [switch]$Disable ) try { Import-Module ActiveDirectory -ErrorAction Stop } catch { Write-Error "Failed to Import the active directory module" exit(1) } Switch ($PsCmdlet.ParameterSetName) { "Enable" { try { Set-ADOrganizationalUnit -Id $DN -ProtectedFromAccidentalDeletion $true -ErrorAction Stop Write-Host "Successfully enabled Protection on OU : $DN" break } catch { Write-Host "Failed to enabled Protection on OU : $DN" } } "Disable" { try { Set-ADOrganizationalUnit -Id $DN -ProtectedFromAccidentalDeletion $false -ErrorAction Stop Write-Host "Successfully disabled Protection on OU : $DN" break } catch { Write-Host "Failed to disable Protection on OU : $DN" } } } }
Comments on this entry are closed.
Pardon me !
But I don’t understand the usefulness of this Function ….eventually the following is doing the work:
Set-ADOrganizationalUnit -Id $DN -ProtectedFromAccidentalDeletion $true -ErrorAction Stop
Why don’t we call it directly..it does have try/catch to handle error but apart from that the advantage ?
It would have been better if somehow this could have been achieved using .NET rather than the AD module..is that possible ?