Thursday, July 9, 2015

Powershell: Jobs - Search for shares in ad windows servers

Job script to search for shares in a active directory environment. Update $Domain to your domain and run
#Tony Unger 
#Tonyunger.com
#Scans all AD servers for Shares 
#50 servers at a time
#Will Prompt for creds
$i =0  
import-module activedirectory 
cls
$creds = Get-Credential 
$myCol = @()
$Domain = "microsoft.com"

$Servers = Get-ADComputer -server $Domain -Filter {(OperatingSystem -Like "Windows Server*")-and (enabled -eq "true")} -Property SamAccountName | Select -expand Name

$scriptblock = {
 param(
 [string]$server,
 $creds
 )
 Get-WmiObject Win32_Share -ComputerName $server -Credential $Creds | select *

}
foreach($server in $Servers){
$i++
    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
 Write-Progress -Activity "Gathering computer info" -status "Currently on $server -- $i of $Servers.count" -percentComplete ($i / $Servers.count*100)
 if ($running.Count -le 50) {
        Start-Job -ScriptBlock $scriptblock -Name $server -ArgumentList $server, $creds 
    } 
 else {
         $running | Wait-Job
    }
}

while ($running.Count -ge 1) {
      sleep 1 
    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
} 


foreach ($job in Get-Job ){

 $recjobs = Receive-Job -Keep -Job $job 
 foreach ($recjob in $recjobs){
    $Detail = New-Object PSObject 
  $Detail | Add-Member Noteproperty Name $recjob.name 
  $Detail | Add-Member Noteproperty Path $recjob.path 
  $Detail | Add-Member Noteproperty Server $recjob.__SERVER
  $myCol += $Detail
 }
}
$myCol
$myCol | export-csv -Path c:\TEMp\shares\output.csv -notype