Skip to content

PowerShell to Get All Windows Servers and Operating Systems From Active Directory

by on July 14, 2016

So you need a quick way to inventory the servers in your domain? Here is an easy way to get this with PowerShell.

You would modify for your environment and can tweak the details and properties as needed.

Since most of my scripts require a report to be emailed to end users and/or sharepoint, this includes the step and a cleanup of the file that was created on the local machine, so data does not get duplicated and left on the local system.

In general, this setup works great for my needs and meet management requirements!

——————————-

######## TO USE ##################
## c:\ps_scripts\get-allservers.ps1 -email “ebruce@mydomain.com” -reportname “All_Windows_Servers”
#############Define input parameters – must be at top
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$reportname,

[Parameter(Mandatory=$True,Position=2)]
[string]$email

)

########### Load AD module for powershell, if run in  PowerShell, not AD powershell
import-module activedirectory

############# Set Variables
$a = Get-Date -format yyyy-MM-dd-HH-mm
$filepath = “c:\ps_output\”+$reportname+”_”+$a+”.csv”$mailsubject = “$reportname Report from AD”
$mailfrom = “bounceNotice@mydomain.com”  #this should be an email address you check for bad email addresses and bouncebacks – for example if an end user changes the SharePoint library email, or a user leaves the company

$smtp = “mail.mydomain.com”
$mailsubject = “$reportname Report from AD”

##############create file
Get-ADComputer -Filter {OperatingSystem -like “*Server*”} -Properties OperatingSystem |
Select Name,OperatingSystem |
Sort Name,OperatingSystem |
Export-csv $filepath -notypeinformation

#############Email
write-host “Mailing $filepath”
$body = “Report attached – $Reportname – contact ebruce@mydomain.com if there are any questions”
send-mailmessage -to “$email” -from “$mailfrom” -smtpserver “$smtp” -subject “$mailsubject” -body “$body” -attachments “$filepath”

###########Delete created csv file
write-host “deleting $filepath”
Remove-Item “$filepath”
#While(Test-Path $filepath) {Remove-Item $filepath}

 

ENJOY!

Advertisements
Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: