Thursday, August 16, 2018

Few useful powershell scripts I have worked with

Some useful powershell scripts
--------------------------------

Check file created before date range
-------------------------------------

$lastWrite = (get-item "D:\MYdirectory\myExcel.xls").LastWriteTime
$timespan = new-timespan -days 7 -hours 0 -minutes 0

if (((get-date) - $lastWrite) -gt $timespan)
{
   Write-Host "old";
} else
{
   Write-Host "new";
}





Send mails
-----------


$lastModifiedDate = (Get-Item "D:\Revenue_FTP_Files\FTP_Bottom_Up_Revenue.xls").LastWriteTime;
Write-Host $lastModifiedDate;

$table1 = Get-Childitem D:\Revenue_FTP_Files | where {$_.LastwriteTime -le (Get-date).AddDays(-7)}|where {$_.Name -like "FTP_Bottom_Up_Revenue.xls" }| Select Name,LastWriteTime |ConvertTo-Html -head $a -Property Name,LastWriteTime
Write-Host $table1;


### get details
$Today = Get-Date
$FileDate = (Get-ChildItem "D:\Revenue_FTP_Files\FTP_Bottom_Up_Revenue.xls").LastWriteTime
if ($FileDate -ge $Today){"ok"} else {"not ok"}

Write-Host $Today;
Write-Host $FileDate;

$day = (get-date 10/04/2017).DayOfWeek
Write-Host $day;
$lastWriteshort = (get-item "D:\Revenue_FTP_Files\FTP_Bottom_Up_Revenue.xls").LastWriteTime.ToShortDateString();
Write-Host $lastWriteshort;
Write-Host "------------";
$dateValue = (get-date).ToShortDateString();
Write-Host $dateValue;

if (((get-date) - $lastWrite) -gt $timespan)
{
   Write-Host "old";
} else
{
   Write-Host "new";
}

$lastWrite = (get-item "D:\MyDirectory\myFile.xls").LastWriteTime
$tuesdayTimespan = new-timespan -days 2 -hours 0 -minutes 0
$wednesdayTimespan = new-timespan -days 1 -hours 12 -minutes 0
$thursdayTimespan = new-timespan -days 2 -hours 0 -minutes 0
$fridayTimespan = new-timespan -days 3 -hours 0 -minutes 0
$saturdayTimespan = new-timespan -days 4 -hours 0 -minutes 0
$sundayTimespan = new-timespan -days 6 -hours 0 -minutes 0
$mondayTimespan = new-timespan -days 6 -hours 0 -minutes 0



$day = (get-date).DayOfWeek

if($day -eq "Tuesday" ){
if ((get-date).ToShortDateString() -ne $lastWrite.ToShortDateString())
{
   Write-Host "sending mail";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}
if($day -eq "Wednesday" ){
if (((get-date) - $lastWrite) -ge $wednesdayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}
if($day -eq "Thursday" ){
if (((get-date) - $lastWrite) -ge $thursdayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}

}
if($day -eq "Friday" ){
if (((get-date) - $lastWrite) -ge $fridayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}
if($day -eq "Saturday" ){
if (((get-date) - $lastWrite) -ge $saturdayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}
if($day -eq "Sunday" ){
if (((get-date) - $lastWrite) -ge $sundayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}
if($day -eq "Monday" ){
if (((get-date) - $lastWrite) -ge $mondayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}






Server Availability
--------------------


 
#### Spreadsheet Location
 $DirectoryToSaveTo = "C:\project\"
 $date=Get-Date -format "yyyy-MM-d"
 $Filename="serverinfo-$($date)"
 $FromEmail="
 $ToEmail="
 $SMTPMail="
 
 ###InputLocation
 $Computers = Get-Content "C:\project\servers.txt"
 
 
# before we do anything else, are we likely to be able to save the file?
# if the directory doesn't exist, then create it
if (!(Test-Path -path "$DirectoryToSaveTo")) #create it if not existing
  {
  New-Item "$DirectoryToSaveTo" -type directory | out-null
  }
 


#Create a new Excel object using COM 
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)

$sheet.Name = 'Server Inventory'
#Create a Title for the first worksheet
$row = 1
$Column = 1
$Sheet.Cells.Item($row,$column)= 'Server Inventory'

$range = $Sheet.Range("a1","s2")
$range.Merge() | Out-Null
$range.VerticalAlignment = -4160

#Give it a nice Style so it stands out
$range.Style = 'Title'

#Increment row for next set of data
$row++;$row++

#Save the initial row so it can be used later to create a border
#Counter variable for rows
$intRow = $row
$xlOpenXMLWorkbook=[int]51

#Read thru the contents of the SQL_Servers.txt file

$Sheet.Cells.Item($intRow,1)  ="Name"
$Sheet.Cells.Item($intRow,2)  ="status"
$Sheet.Cells.Item($intRow,3)  ="OS"
$Sheet.Cells.Item($intRow,4)  ="Domain Role"
$Sheet.Cells.Item($intRow,5)  ="ProcessorName"
$Sheet.Cells.Item($intRow,6)  ="Manufacturer"
$Sheet.Cells.Item($intRow,7)  ="Model"
$Sheet.Cells.Item($intRow,8)  ="SystemType"
$Sheet.Cells.Item($intRow,9)  ="Last Boot Time"
$Sheet.Cells.Item($intRow,10) ="Bios Version"
$Sheet.Cells.Item($intRow,11) ="CPU Info"
$Sheet.Cells.Item($intRow,12) ="NoOfProcessors"
$Sheet.Cells.Item($intRow,13) ="Total Physical Memory"
$Sheet.Cells.Item($intRow,14) ="Total Free Physical Memory"
$Sheet.Cells.Item($intRow,15) ="Total Virtual Memory"
$Sheet.Cells.Item($intRow,16) ="Total Free Virtual Memory"
$Sheet.Cells.Item($intRow,17) ="Disk Info"
$Sheet.Cells.Item($intRow,18) ="FQDN"
$Sheet.Cells.Item($intRow,19) ="IPAddress"

for ($col = 1; $col –le 19; $col++)
     {
          $Sheet.Cells.Item($intRow,$col).Font.Bold = $True
          $Sheet.Cells.Item($intRow,$col).Interior.ColorIndex = 48
          $Sheet.Cells.Item($intRow,$col).Font.ColorIndex = 34
     }

$intRow++


Function GetStatusCode

    Param([int] $StatusCode) 
    switch($StatusCode)
    {
        0         {"Success"}
        11001   {"Buffer Too Small"}
        11002   {"Destination Net Unreachable"}
        11003   {"Destination Host Unreachable"}
        11004   {"Destination Protocol Unreachable"}
        11005   {"Destination Port Unreachable"}
        11006   {"No Resources"}
        11007   {"Bad Option"}
        11008   {"Hardware Error"}
        11009   {"Packet Too Big"}
        11010   {"Request Timed Out"}
        11011   {"Bad Request"}
        11012   {"Bad Route"}
        11013   {"TimeToLive Expired Transit"}
        11014   {"TimeToLive Expired Reassembly"}
        11015   {"Parameter Problem"}
        11016   {"Source Quench"}
        11017   {"Option Too Big"}
        11018   {"Bad Destination"}
        11032   {"Negotiating IPSEC"}
        11050   {"General Failure"}
        default {"Failed"}
    }
}


Function GetUpTime
{
    param([string] $LastBootTime)
    $Uptime = (Get-Date) - [System.Management.ManagementDateTimeconverter]::ToDateTime($LastBootTime)
    "Days: $($Uptime.Days); Hours: $($Uptime.Hours); Minutes: $($Uptime.Minutes); Seconds: $($Uptime.Seconds)" 
}

   
   



foreach ($Computer in $Computers)
 {

 TRY {
 $OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
 $Bios = Get-WmiObject -Class Win32_BIOS -ComputerName $Computer
 $sheetS = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer
 $sheetPU = Get-WmiObject -Class Win32_Processor -ComputerName $Computer
 $drives = Get-WmiObject -ComputerName $Computer Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3}
 $pingStatus = Get-WmiObject -Query "Select * from win32_PingStatus where Address='$Computer'"
 $IPAddress=(Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | ? {$_.IPEnabled}).ipaddress
 $FQDN=[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
 $OSRunning = $OS.caption + " " + $OS.OSArchitecture + " SP " + $OS.ServicePackMajorVersion
 $NoOfProcessors=$sheetS.numberofProcessors
 $name=$SheetPU|select name -First 1
 $Manufacturer=$sheetS.Manufacturer
 $Model=$sheetS.Model
 $systemType=$sheetS.SystemType
 $ProcessorName=$SheetPU|select name -First 1
 $DomainRole = $sheetS.DomainRole
 $TotalAvailMemory = $OS.totalvisiblememorysize/1kb
 $TotalVirtualMemory = $OS.totalvirtualmemorysize/1kb
 $TotalFreeMemory = $OS.FreePhysicalMemory/1kb
 $TotalFreeVirtualMemory = $OS.FreeVirtualMemory/1kb
 $TotalMem = "{0:N2}" -f $TotalAvailMemory
 $TotalVirt = "{0:N2}" -f $TotalVirtualMemory
 $FreeMem = "{0:N2}" -f $TotalFreeMemory
 $FreeVirtMem = "{0:N2}" -f $TotalFreeVirtualMemory
 $date = Get-Date
 $uptime = $OS.ConvertToDateTime($OS.lastbootuptime)
 $BiosVersion = $Bios.Manufacturer + " " + $Bios.SMBIOSBIOSVERSION + " " + $Bios.ConvertToDateTime($Bios.Releasedate)
 $sheetPUInfo = $name.Name + " & has " + $sheetPU.NumberOfCores + " Cores & the FSB is " + $sheetPU.ExtClock + " Mhz"
 $sheetPULOAD = $sheetPU.LoadPercentage
 
 if($pingStatus.StatusCode -eq 0)
    {
        $Status = GetStatusCode( $pingStatus.StatusCode )
    }
else
    {
    $Status = GetStatusCode( $pingStatus.StatusCode )
       }
   
   
 if (($DomainRole -eq "0") -or ($DomainRole -eq "1"))
 {
 $Role = "Work Station"
 }
 elseif (($DomainRole -eq "2") -or ($DomainRole -eq "3"))
 {
 $Role = "Member Server"
 }
 elseif (($DomainRole -eq "4") -or ($DomainRole -eq "5"))
 {
 $Role = "Domain Controller"
 }
 else
 {
 $Role = "Unknown"
 }
 }
 CATCH
 {
 $pcnotfound = "true"
 }
 #### Pump Data to Excel
 if ($pcnotfound -eq "true")
 {
 $sheet.Cells.Item($intRow, 1) = "$($computer) Not Found "
 }
 else
 {
 $sheet.Cells.Item($intRow, 1) = $computer
 $sheet.Cells.Item($intRow, 2) = $status
 $sheet.Cells.Item($intRow, 3) = $OSRunning
 $sheet.Cells.Item($intRow, 4) = $Role
 $sheet.Cells.Item($intRow, 5) = $name.name
 $Sheet.Cells.Item($intRow, 6) = $Manufacturer
 $Sheet.Cells.Item($intRow, 7) = $Model
 $Sheet.Cells.Item($intRow, 8) = $SystemType
 $sheet.Cells.Item($intRow, 9) = $uptime
 $sheet.Cells.Item($intRow, 10)= $BiosVersion
 $sheet.Cells.Item($intRow, 11)= $sheetPUInfo
 $sheet.Cells.Item($intRow, 12)=$NoOfProcessors
 $sheet.Cells.Item($intRow, 13)= "$TotalMem MB"
 $sheet.Cells.Item($intRow, 14)= "$FreeMem MB"
 $sheet.Cells.Item($intRow, 15)= "$TotalVirt MB"
 $sheet.Cells.Item($intRow, 16)= "$FreeVirtMem MB"
 $sheet.Cells.Item($intRow, 19)=$IPAddress
 $sheet.Cells.Item($intRow, 18)=$FQDN

 
$driveStr = ""
 foreach($drive in $drives)
 {
 $size1 = $drive.size / 1GB
 $size = "{0:N2}" -f $size1
 $free1 = $drive.freespace / 1GB
 $free = "{0:N2}" -f $free1
 $freea = $free1 / $size1 * 100
 $freeb = "{0:N2}" -f $freea
 $ID = $drive.DeviceID
 $driveStr += "$ID = Total Space: $size GB / Free Space: $free GB / Free (Percent): $freeb % ` "
 }
 $sheet.Cells.Item($intRow, 17) = $driveStr
 }

 
$intRow = $intRow + 1
 $pcnotfound = "false"
 }

$erroractionpreference = “SilentlyContinue” 

$Sheet.UsedRange.EntireColumn.AutoFit()



$filename = "$DirectoryToSaveTo$filename.xlsx"
if (test-path $filename ) { rm $filename } #delete the file if it already exists
$Sheet.UsedRange.EntireColumn.AutoFit()
$Excel.SaveAs($filename, $xlOpenXMLWorkbook) #save as an XML Workbook (xslx)
$Excel.Saved = $True
$Excel.Close()
$Excel.DisplayAlerts = $False
$Excel.quit()


Function sendEmail([string]$emailFrom, [string]$emailTo, [string]$subject,[string]$body,[string]$smtpServer,[string]$filePath)
{
#initate message
$email = New-Object System.Net.Mail.MailMessage 
$email.From = $emailFrom
$email.To.Add($emailTo)
$email.Subject = $subject
$email.Body = $body
# initiate email attachment 
$emailAttach = New-Object System.Net.Mail.Attachment $filePath
$email.Attachments.Add($emailAttach) 
#initiate sending email 
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($email)
}

#Call Function 

$message = @" 
Hi Team,

The Discovery of Windows Server and Disk Space information for all the listed instances.

Autogenerated Email!!! Please do not reply.

Thank you, 
xyz.com

"@       
$date=get-date

sendEmail -emailFrom $fromEmail -emailTo $ToEmail -subject "Windows Server Inventory & Disk Details -$($date)" -body $message -smtpServer $SMTPMail -filePath $filename




Create Check sum
-----------------

If the content is a string:

$someString = "Hello World!"
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = new-object -TypeName System.Text.UTF8Encoding
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($someString)))
If the content is a file:

$someFilePath = "C:\foo.txt"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))


No comments:

Post a Comment