Find rights on a group of NT shares

Ran like this: 

#List of shares:

$shares = @( "\\share1\this\that" "\\share2\this\that\also" ) 
    foreach ($share in $shares) { $filename = $share -replace '\\','_' 
       Get-Acl $share | select -exp Access | Export-Csv $filename".csv" -Append -NoTypeInformation }
@1 year ago

Satiating PCI Compliance for contractor accounts expiring later than 90 days from today…

The PCI police jumped us today to make sure we kept our vendors and contractors in the scope of PCI compliance.  Many were over the 90 day cutoff to be in Active Directory, and many were up and coming to cross the plateau.  I fixed it like this: 

Right now tumblr is upset with the ‘pre’ and ‘code’ tags, so this is looking like a giant block, but, so it is for now:

 #actually could do this easier and only run through it ONE time based off the stuff in $greaterthan90days #that way it doesn't search 5 separate times through the dir. # Check the QAD snapins are installed if ( (Get-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction silentlycontinue) -eq $null ) { # The QAD snapin is not active. Check it's installed if ((Get-PSSnapin -Name Quest.ActiveRoles.ADManagement -Registered -ErrorAction SilentlyContinue) -eq $null) { Write-Error "You must install Quest ActiveRoles AD Tools to use this script!" } else { Write-Host "Importing QAD Tools" Add-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction Stop } } $firsttime=get-date #no EXCLUDETHISGROUP1/EXCLUDETHISGROUP2 and the account is NOT disabled/termed. $everyone=Get-QADuser -sl 0 -DontUseDefaultIncludedProperties -IncludedProperties lastlogon,lastlogontimestamp,pwdlastset,mail,employeeid,accountexpires,distinguishedname -LdapFilter '(&(|(employeeid=c*)(employeeid=v*))(accountexpires=*))'| Where-Object {$_.distinguishedname -notmatch "testaccounts" -and $_.distinguishedname -notmatch "EXCLUDETHISGROUP4" -and $_.distinguishedname -notmatch "EXCLUDETHISGROUP2" -and $_.distinguishedname -notmatch "EXCLUDETHISGROUP3" -and $_.mail -notmatch "disabled"} #prior to the filter$everyone=Get-QADuser -sl 0 -DontUseDefaultIncludedProperties -IncludedProperties employeeid,accountexpires,distinguishedname -LdapFilter '(&(|(employeeid=c*)(employeeid=v*))(accountexpires=*))'| Where-Object {$_.ParentContainer -notmatch "EXCLUDETHISGROUP2" -or $_.Parentcontainer -notmatch "EXCLUDETHISGROUP4"}|select samaccountname,accountexpires,employeeid,manager,distinguishedname #$everyone=Get-QADuser -sl 0 -DontUseDefaultIncludedProperties -IncludedProperties mail,employeeid,accountexpires,distinguishedname -LdapFilter '(&(|(employeeid=c*)(employeeid=v*))(accountexpires=*))'| Where-Object {$_.distinguishedname -notmatch "testaccounts" -and $_.distinguishedname -notmatch "EXCLUDETHISGROUP3" -and $_.mail -notmatch "disabled"} $noexpire = $everyone | where-object {$_.accountexpires -eq $null} | select samaccountname,mail,accountexpires,employeeid,manager,distinguishedname,lastlogon,lastlogontimestamp,pwdlastset $90plus = $everyone | where-object {$_.accountexpires -gt (get-date).adddays(90)} | select samaccountname,mail,accountexpires,employeeid,manager,distinguishedname,lastlogon,lastlogontimestamp,pwdlastset $80to90 = $everyone | where-object {$_.accountexpires -gt (get-date).adddays(80) -and $_.accountexpires -lt (get-date).adddays(90)}|select samaccountname,mail,accountexpires,employeeid,manager,distinguishedname,lastlogon,lastlogontimestamp,pwdlastset $70to80 = $everyone | where-object {$_.accountexpires -gt (get-date).adddays(70) -and $_.accountexpires -lt (get-date).adddays(80)}|select samaccountname,mail,accountexpires,employeeid,manager,distinguishedname,lastlogon,lastlogontimestamp,pwdlastset $60to70 = $everyone | where-object {$_.accountexpires -gt (get-date).adddays(60) -and $_.accountexpires -lt (get-date).adddays(70)}|select samaccountname,mail,accountexpires,employeeid,manager,distinguishedname,lastlogon,lastlogontimestamp,pwdlastset $50to60 = $everyone | where-object {$_.accountexpires -gt (get-date).adddays(50) -and $_.accountexpires -lt (get-date).adddays(60)}|select samaccountname,mail,accountexpires,employeeid,manager,distinguishedname,lastlogon,lastlogontimestamp,pwdlastset $40to50 = $everyone | where-object {$_.accountexpires -gt (get-date).adddays(40) -and $_.accountexpires -lt (get-date).adddays(50)}|select samaccountname,mail,accountexpires,employeeid,manager,distinguishedname,lastlogon,lastlogontimestamp,pwdlastset #since you can't pipe directly to a csv file, send the file now to a csv $noexpire | export-csv doesnotexpire.csv -notypeinformation $90plus | export-csv expiresInGreaterThan90.csv -notypeinformation $80to90 | export-csv expiresin80to90days.csv -notypeinformation $70to80 | export-csv expiresin70to80days.csv -notypeinformation $60to70 | export-csv expiresin60to70days.csv -notypeinformation $50to60 | export-csv expiresin50to60days.csv -notypeinformation $40to50 | export-csv expiresin40to50days.csv -notypeinformation #first let's wrangle the folks that NEVER expire. Everyone that is NOT EXCLUDETHISGROUP3 or an FTE needs an expiration date. The filter ALREADY set to uninclude EXCLUDETHISGROUP3 folks above, so we just need to set them. $cutoffDate = (get-date).adddays(90) write-host -ForegroundColor green "The following folks never expire! Let's set their accountexpires attribute to $cutoffdate!" $noexpire | get-qaduser -identity {$_.samaccountname} | set-qaduser -accountexpires $cutoffDate #now let's validate what we did with the $noexpire people was right $noExpireFIXED = $noexpire | get-qaduser -identity {$_.samaccountname} -sl 0 -DontUseDefaultIncludedProperties -IncludedProperties mail,employeeid,accountexpires,distinguishedname -LdapFilter '(&(|(employeeid=c*)(employeeid=v*))(accountexpires=*))'| Where-Object {$_.distinguishedname -notmatch "testaccounts" -and $_.distinguishedname -notmatch "EXCLUDETHISGROUP4" -and $_.distinguishedname -notmatch "EXCLUDETHISGROUP2" -and $_.distinguishedname -notmatch "EXCLUDETHISGROUP3" -and $_.mail -notmatch "disabled"} | select samaccountname,accountexpires $noExpireFIXED | export-csv noExpireFIXED.csv -notypeinformation #now let's change the dates on the folks over 90 days: $cutoffDate = (get-date).adddays(90) write-host -ForegroundColor green "The following folks expire in 
@1 year ago

Contractors that expire 90 days from today?

We need to find out all the users that have an “accountexpires” attribute greater than 90 days from today, so:


Get-QAduser -sl 0 -DontUseDefaultIncludedProperties -IncludedProperties employeeid,accountexpires -LdapFilter '(&(|(employeeid=c*)(employeeid=v*))(accountexpires=*))'|where-object {$_.accountexpires -gt (get-date).adddays(91)}|select samaccountname,accountexpires,employeeid
@1 year ago

Creating a Distro List via Powershell

I couldn’t figure out, in the 20 seconds I spent, how to create a DL with a valid email address in the ADUC GUI, so I went to my friend Powershell with this one:


$user='sentryXMLNotifs'
new-qadGroup -ParentContainer 'OU=distribution groups,OU=user accounts,DC=AWebsite,DC=org' -name 'sentryXMLNotification' -samAccountName $user -grouptype 'Distribution' -groupscope 'global'

Set-QADgroup -Identity $user -IncludedProperties proxyAddresses -ObjectAttributes @{proxyAddresses="SMTP:"+$user+"@aWebsite.com"}

@1 year ago

Finding Stale/Empty Groups in Active Directory

At the day job, we routinely clean out the stale users, but seem to neglect the stale groups - I think the fairest way to start cleaning them up is to see which groups have no members in them, and email their manager asking if they want to keep it. So I came up with something like this: *NOTE: As usual I kept my #commented out code in the script to be able to learn where I had hiccups and how I worked around it.*


#I need to get a list of managers email addresses AND the Dl/Security Group name at the end

#get qad groups with NO managers listed>>:
#Get-QADgroup -sl 0 -Empty $true -ldapFilter '(&(!(managedby=*)))' | Export-Csv noowners.csv

#get a list of all groups with no members that have both a manager and an email addy
$EmptyDLs=get-qadgroup -sl 0 -Empty $true -ldapFilter '((managedby=*)(mail=*))' | select managedby,mail
$DLmail=$EmptyDLs | select mail
$DLmanager=$EmptyDLs |select managedby

#grabs user name from managedby field: 
# (get-qaduser (($peeps[3] -split(",*..="))[2])).mail

#this will pull from the pipe
#get-qaduser (($peeps[3]) -split(",*..="))[2]

#give the csv file we're building a header
$details = New-Object psobject
$details | add-member -name username -value userName -membertype noteproperty
$details | add-member -name ownerEmail -value ownerEmail -membertype noteproperty
$details | add-member -name userOwns -value userOwns -membertype noteproperty
$details |  ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File emptygroups.csv

#start a count:
$i=0

#this loop will grab the email address of each manager based on a split
 foreach ($DLManagerName in $DLManager){
 $DLManagerName=(([string]$DLManagername).split(",*..=")[2])
$DLManagerInfo=get-qadobject $DLManagerName -IncludedProperties mail |select mail,samaccountname
$DLmanagerEmail=$DLManagerInfo | select mail
$DLManagerSAMAccountName=$DLManagerInfo | select samaccountname
$justName=$dlmanagersamaccountname -replace ("@{SAMAccountName=") -replace ("}")
$justEmail=$dlmanageremail -replace ("@{mail=") -replace ("}")
$theDLowned=$DLmail[$i] -replace ("@{mail=") -replace ("}")
write "$i) hello $justName, I see your email addy is $justEmail and you own $theDLowned"
$i=$i+1

#put these all in a PSObject and export to a CSV that appends with each loop
$details = New-Object psobject
$details | add-member -name username -value $justName -membertype noteproperty
$details | add-member -name ownerEmail -value $justEmail -membertype noteproperty
$details | add-member -name userOwns -value $theDLowned -membertype noteproperty
$details |  ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File emptygroups.csv -Append

# used this just to output to a text file and could work, but want it in a more readable CSV like above
#$justname | Out-File ed.txt -Append
#$justemail | Out-File ed.txt -Append 
#$theDLowned | Out-File ed.txt -Append
#"***next entry***" | Out-File ed.txt -append
}

#now I need to put that into an email format that ties the manager name to the DL name.
@1 year ago

Changing HomeDirectory paths…

I was given a text file with NTIDs that needed their HomeDirectory attribute change, so I did this: 

 #import users $users = gc d*.lst #put them in a list for backup 
$x=foreach ($duser in $dusers){
get-qaduser $duser -DontUseDefaultIncludedProperties -IncludedProperties homedirectory,samacc | select samaccountname, homedirectory} 

$x | export-csv changeme_DENVER.csv –NoTypeInformation 
#change their HOMEDIR foreach ($duser in $dusers) {
set-qaduser $duser -HomeDirectory \\drive001\HOME} 

$y=foreach ($duser in $dusers){get-qaduser $duser -DontUseDefaultIncludedProperties -IncludedProperties homedirectory,samacc | select samaccountname, homedirectory} 
$y | export-csv changeme_DENVER_DONE.csv –NoTypeInformation 
@1 year ago

Counting text file differences and similarities in Powershell

I have 2 lists in text files, and I want to know which are similar and different in each list.  So do this: 


#pull in rons list and sort it/remove whitespace
#pull in andys list and sort it/remove whitespace
#if it's in rons list, remove it from andys list
#the ones left in andys list will be ones ron doesn't have

$content = ""; 
$ron=gc "c:\ron.txt";
$andy=gc "c:\andy.txt";
$total=$ron+$andy;

#sort rons stuff
$count = 0; 
Write-Progress -Activity "Processing file" -CurrentOperation "Line = 0" -PercentComplete 0 -Status "Starting" -Id 1; 
$percent_complete = 0;   # trim line by line 
foreach($line in $ron) 
{ $line = $line.TrimEnd(); 
$contentron += "$line`n" # Add a newline 
$count++; 
$percent_complete = [int][Math]::Ceiling((($count / $ron.Count) * 100)); 
Write-Progress -Activity "Processing file" -CurrentOperation "Line = $count" -PercentComplete $percent_complete -Status "Running" -Id 1; }   
$contentron | Set-Content -Path "c:\ronSorted.csv"; 
Write-Progress -Activity "Finished processing file" -CurrentOperation "All lines processed" -PercentComplete 100 -Status "Complete" -Id 1; 
$ronSorted=gc c:\ronsorted.csv|sort

#sort andys stuff
$count = 0; 
Write-Progress -Activity "Processing file" -CurrentOperation "Line = 0" -PercentComplete 0 -Status "Starting" -Id 1; 
$percent_complete = 0;   # trim line by line 
foreach($line in $andy) 
{ $line = $line.TrimEnd(); 
$contentandy += "$line`n" # Add a newline 
$count++; 
$percent_complete = [int][Math]::Ceiling((($count / $andy.Count) * 100)); 
Write-Progress -Activity "Processing file" -CurrentOperation "Line = $count" -PercentComplete $percent_complete -Status "Running" -Id 1; }   
$contentandy | Set-Content -Path "c:\andySorted.csv"; 
Write-Progress -Activity "Finished processing file" -CurrentOperation "All lines processed" -PercentComplete 100 -Status "Complete" -Id 1; 

$andysorted=gc c:\andysorted.csv|sort


#join both andys and rons new stuff
$joinedtotal=$ronSorted+$andySorted|sort


$nodupes=($joinedtotal | sort | gu ).count
$dupes=($joinedtotal | sort).count
$joinedtotalUnique= $joinedtotal | sort | gu
write-host "Here are all unique servers: $joinedtotalUnique"
write-host "Total number of servers is: $dupes"
write-host "Total number of UNIQUE servers is: $nodupes"


#ron does not have these in his list:
$notInRons=$joinedtotal+$ronsorted|group |Where-Object {$_.count -eq "1"} |out-file ronjustonce.csv
$ronjustonce=gc ronjustonce.csv
write-host "these aren't in ron's list: $notinRons"
write-host $ronjustonce


#andy does not have these in his list:
$notInandys=$joinedtotal+$andysorted|group |Where-Object {$_.count -eq "1"} | out-file andyjustonce.csv
$andyjustonce=gc andyjustonce.csv
write-host "these aren't in andy's list: $notinandys"
write-host $andyjustonce


@1 year ago

Adding Users To a DL via Quest CMDLETS

So you’ve got ways of adding people to DLs, but be careful when do it.  You need to specify EVERYONE you want in it and doing this is bad:


Set-QADGroup -Identity $group -Member $sean

So don’t do it.

However, do a get-qaduser for each person you want to add and then you can do something like this: 


Set-QADGroup -Identity $user -Member $sean,$john,$jesse,$ron,$andy
@1 year ago

Saving Certain Attachments in Outlook via Powershell

I came across a situation today where I got bombarded with 100s of PDF attachments in email that I needed saved to save each to a folder to process.  Opening each, right clicking and saving them individually would have taken hours.

Thanks to TheOldDog for getting me started, but needed to modify it on the last line here:


$_.saveasfile((Join-Path $filepath “WHATYOUWANTTOCALLEACHFILE_$i.pdf”))

as it was just overwriting the file each time, so I needed to add a counter to increment and save a new file each time like this: 


$i=$i+1

The full script is here:


#set a counter
$i=1

#set outlook to open
$o = New-Object -comobject outlook.application
$n = $o.GetNamespace(“MAPI”)

#you'll get a popup in outlook at this point where you pick the folder you want to scan
$f = $n.pickfolder()

#where do you want to save the files?
$filepath = “c:\bin\cards\”

#now loop through them and grab the attachments
$f.Items | foreach {
$i=$i+1
    $_.attachments | foreach {
    Write-Host $_.filename
    $a = $_.filename
    If ($a.Contains(“pdf”)) {
    $_.saveasfile((Join-Path $filepath “WHATYOUWANTTOCALLEACHFILE_$i.pdf”))
      }
  }
}
@1 year ago

Many Ways of Adding Bulk Users to Active Directory With Powershell

There are again, a handful of ways to do anything with Powershell, and here are a few different ways to create bulk users in AD. Way #1: Use the native DSAdd call:

$count = 1
while ($count -le 20)
{$Username = "User_$count"
$password = "Password123!"
cmd /c "dsadd user cn=$Username,ou=TESTUSERS,dc=contoso,dc=com -pwd $Password"
$count = $count + 1}

Or perhaps you fancy a simple one-liner with the NET USE command:

1..20 | ForEach-Object { Net User "TestUser$_" '@Password1' /ADD /Domain} 

Or finally one with a little more interactive hand-holding, and strict use of only Powershell Cmdlets:


# Get the logged-on user's domain in DN form
$whoami=cmd /c whoami
$youAre = get-qaduser $whoami
$yourDN=$youARe.dn
$domain1=($yourDN -split(","))[-1]
$domain2=($yourDN -split(","))[-2]
$baseOU="OU=Test Users,$domain2,$domain1"

# Specify the OU we want to create the users in
$ouName=read-host 'What OU will these accts live in (to be nested under TEST ACCOUNTS OU)?'

# Build the full DN of the target OU
$ouDN = "ou=$ouName,ou=Test Users,$domain2,$domain1"

# ask the number of users to create
$usercount=read-host 'how many users do you want to create?'

# Specify the description attribute for the users
$datetime = get-date -format G 
$desc = "Test user created by $whoami @ $datetime"

#Search if users/OUs already exist
$LDAPF="(&(ObjectCategory=OrganizationalUnit)(name=$ouName))"
$OU= get-qadobject -ldapfilter $LDAPF
if($OU -eq $null)
{write-host -foregroundcolor green "that OU does not exist, I'll make it for you!"
New-QADObject -Type OrganizationalUnit -Name $OUName -parentContainer $baseOU -Description "created by $whoami via script on $datetime" 
write-host -foregroundcolor yellow "------------OU created! Now to add users to it!--------------"} 
else 
{write-host -foregroundcolor yellow "The OU $ou already exists - we'll just put people in it now!"}

# Create users
$i = 1
While ($i -le $usercount)
{
$Uname = "User" + $i
$UDdname = "Test User" + $i
$doesUserExist=get-qaduser $uname
if ($doesUserExist -eq $null)
{
$DomainName=($baseou.split(",DC=")[-5])
$dotName=($baseou.split(",DC=")[-1])
$UPN="$uname"+'@'+"$domainName"+'.'+"$dotname"
New-QADUser –Name $Uname –SamAccountName $Uname –DisplayName $UDdname -UserPrincipalName $UPN -ParentContainer $oudn -description $desc -UserPassword '@Password1'}
else
{
$DomainName=($baseou.split(",DC=")[-5])
$dotName=($baseou.split(",DC=")[-1])
write-host -foregroundcolor red "$uName@$domainName.$dotName already exists, we'll try to create the next user in line"}
$i = $i + 1
}
write-host -foregroundcolor yellow "--------------ALL DONE!--------------"

There were a few extra bits in this one, but made use of the Quest Cmdlets and no native Windows tools - all Powershell. It also adds some error checking and OU creation, but is it worth it? Well, for you maybe now since you have all the code you need, but it was a good learning experience for me too.

@1 year ago