private/CreateOrSetNetgroup.ps1
function CreateOrSetNetGroup { [CmdletBinding(SupportsShouldProcess=$true)] Param ( [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [String]$Name, [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [String]$Description, [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [String]$Path, [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=3)] [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-warning ("NISNetgroupTriple count: {0}" -f $NISNetgroupTriple.count) $SetParams.Replace = @{NISNetgroupTriple = $NISNetgroupTriple} $NewParams.OtherAttributes = @{NISNetgroupTriple = $NISNetgroupTriple} } else{ Write-verbose "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-verbose " 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 ("Error creating {0} at {1}" -f $name,$path) throw $_ } } catch { 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 $sleepTimeout; $i+=$sleepLength) { $SearchCmd = $($ChangeTracking.getCommand -f $item) write-verbose "$SearchCmd" $itemExists = [bool](invoke-expression $SearchCmd) if ($itemExists) { break } write-host (" - {0} is missing, waiting (time: {1} / max {2})......." -f $ChangeTracking.Name, $i, $sleepTimeout) start-sleep -seconds $sleepLength } } } } |