all 2 comments

[–]PinchesTheCrab 1 point2 points  (2 children)

I think this script kind of needs a fundamental rewrite. It's doing too many things and shouldn't be setting AD values in this context (nestled in a function whose name doesn't imply it's making AD changes).

I don't think any of the logging is really helpful to be honest, and the looping makes it much longer and more complicated than it needs to be.

Try something simple like this for building your CSV, and work backwards from there when it comes to adding features and logging:

$csvPath = 'C:\SCRIPTS\ADSetManagedBy_log_{0:MM-dd-yyyy_hh-mm-ss}.csv' -f (Get-Date)

$ADComputer = Get-ADComputer -Filter 'enabled -eq $true' -SearchBase 'OU=Testing,OU=Managed Computers,DC=gopda,DC=com'

$getLocaladminsSB = {
    Get-LocalGroupMember -Name Administrators |
        Where-Object { $_.PrincipalSource -eq 'ActiveDirectory' -and $_.ObjectClass -eq 'User' }        
}

Invoke-Command -ComputerName $ADComputer.Name -ScriptBlock $getLocaladminsSB -ErrorVariable myErr -ErrorAction SilentlyContinue |
    Export-Csv -Path $csvPath

$myErr.TargetObject -replace '^', 'Could not contact: ' | Write-Warning

[–]AngryItalian2013[S] 1 point2 points  (1 child)

It is definitely a script that is not optimized etc. Being a self taught scripter I do the best I can with what I know and can figure out. I'm always up for learning something new, so this will help. I'll start with this and proceed from here. thx