private/CreateOrSetNetgroup.ps1
function CreateOrSetNetGroup { [CmdletBinding(SupportsShouldProcess=$true)] Param ( [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [String]$Name, [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [String]$Description, [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [String]$Path, [Parameter(ValueFromPipelineByPropertyName)] [String[]]$NISNetgroupTriple = @() ) Begin{ #$ConfirmPreference = "none" <#$shouldProcess = @{ Confirm = [bool]($ConfirmPreference -eq "low") Whatif = [bool]($WhatIfPreference.IsPresent) verbose = [bool]($VerbosePreference -ne "SilentlyContinue") }#> $ChangeTracking = @{ ObjType = "Netgroups" New = [System.Collections.Generic.List[String]]::new() Modified = [System.Collections.Generic.List[String]]::new() getCommand = "get-adobject -filter `"distinguishedName -eq '{0}'`"" } } PROCESS { $SetParams = @{ Description = $Description } $NewParams = @{ Description = $Description } if (-not [string]::IsNullOrEmpty($NISNetgroupTriple)) { write-loghandler -level "warning" -message ("NISNetgroupTriple count: {0}" -f $NISNetgroupTriple.count) $SetParams.Replace = @{NISNetgroupTriple = $NISNetgroupTriple} $NewParams.OtherAttributes = @{NISNetgroupTriple = $NISNetgroupTriple} } else{ write-loghandler -level "Verbose" -message "NISNetgroupTriple was empty" } if ($PSCmdlet.ShouldProcess($Name,"Syncing netgroup settings and membership")) { try { set-adobject -identity "CN=$name,$path" -clear NISNetgroupTriple -passthru | set-adobject @SetParams -passthru $ChangeTracking.Modified.Add("CN=$name,$path") } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]{ write-loghandler -level "Verbose" -message " Didn't exist; creating" #write-host $_.Exception.InnerException try { new-adobject -type nisNetgroup -name $Name -path $Path @NewParams -passthru $ChangeTracking.New.add("CN=$name,$path") } catch { write-warning $_.exception.getType().fullname write-loghandler -level "warning" -message ("Error creating {0} at {1}" -f $name,$path) throw $_ } } catch { write-warning $_.exception.getType().fullname write-host "UNKNOWN ERROR" throw $_ } } } END{ if ($ChangeTracking.New.count -gt 0) {Write-Host ("Waiting for creation of any new {0} (Count: {1})" -f $ChangeTracking.Name, $changeTracking.New.count)} foreach ($item in $changeTracking.New) { write-Host " Checking $item" for ($i = 0; $i -lt $Settings.AppSettings.SleepTimeout; $i+=$Settings.AppSettings.SleepLength) { $SearchCmd = $($ChangeTracking.getCommand -f $item) write-loghandler -level "Verbose" -message "$SearchCmd" $itemExists = [bool](invoke-expression $SearchCmd) if ($itemExists) { break } write-host (" - {0} is missing, waiting (time: {1} / max {2})......." -f $ChangeTracking.Name, $i, $Settings.AppSettings.SleepTimeout) start-sleep -seconds $Settings.AppSettings.SleepLength } } } } |