Monday, October 13, 2014

Powershell: Find all shares on domain using Jobs


Purpose: This script will search AD for all servers and report any shares(includes printers)

This script will do 50 servers at a time
Requires RSAT tools powershell
cls

#Find Shares on all Domain computers 50 at a time
#www.tonyunger.com  
  
cls   
import-module activedirectory
  
#$Global:Servers = Get-Content "C:\temp\computers.txt"  
$Global:Servers = Get-ADComputer -Filter {(OperatingSystem -Like "Windows Server*")-and (enabled -eq "true")} -Property SamAccountName | Select -expand Name  
$Global:ReportPath = "C:\temp\Shares.txt"  
  
$scriptblock = {  
       param($server)  
    $pingResult = Test-Connection -count 1 -ErrorAction SilentlyContinue $server | select IPV4Address 
       $Shares = Get-WmiObject Win32_Share -ComputerName $Server | select name 
       $values = @()  
       if($Error){  
            if( $Error -like "*Access is denied*"){  
                return ($server+",AccessDenied")  
            }  
            $Error.Clear()  
            return ($server+",")  
       }  
     
     foreach ($Share in $shares) {            
  
         $values += ($Server + "," + $Share) 
             }  
       return $values  
}  
  
function getdata{  
    $jobs = Get-Job | ? { $_.State -eq "Completed" }  
     foreach( $job in $jobs){  
        $results = Receive-Job $job  
       Add-Content $ReportPath $results  
        Remove-Job $job  
     }     
}  
  
  
Add-Content $ReportPath "Server,share"  
foreach($server in $Servers){  
          
     while( (Get-Job).count -ge 50 ){ 
            sleep -Seconds 1  
            getdata  
     } 
  
     Start-Job -ScriptBlock $scriptblock -ArgumentList $server 
}  
  
while( (get-job).count -ne 0 ){  
      sleep -Seconds 1
            getdata  
              
 }