Determine when each user in the domain last logged on.

Run the following powershell script to determine the last logon date from the AD users.

Output will be written to c:\users.txt

# PSLastLogon.ps1
# PowerShell script to determine when each user in the domain last
# logged on.
#
# ----------------------------------------------------------------------
# Copyright (c) 2011 Richard L. Mueller
# Hilltop Lab web site - http://www.rlmueller.net
# Version 1.0 - March 16, 2011
#
# This program queries every Domain Controller in the domain to find the
# largest (latest) value of the lastLogon attribute for each user. The
# last logon dates for each user are converted into local time. The
# times are adjusted for daylight savings time, as presently configured.
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the copyright owner above has no warranty, obligations,
# or liability for such use.

Trap {"Error: $_"; Break;}
$file = "c:\users.txt"
$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"

$Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.PropertiesToLoad.Add("distinguishedName") > $Null
$Searcher.PropertiesToLoad.Add("lastLogon") > $Null

# Create hash table of users and their last logon dates.
$arrUsers = @{}

# Enumerate all Domain Controllers.
ForEach ($DC In $D.DomainControllers)
{
    $Server = $DC.Name
    $Searcher.SearchRoot = "LDAP://$Server/" + $Domain.distinguishedName
    $Results = $Searcher.FindAll()
    ForEach ($Result In $Results)
    {
        $DN = $Result.Properties.Item("distinguishedName")
        $LL = $Result.Properties.Item("lastLogon")
        If ($LL.Count -eq 0)
        {
            $Last = [DateTime]0
        }
        Else
        {
            $Last = [DateTime]$LL.Item(0)
        }
        If ($Last -eq 0)
        {
            $LastLogon = $Last.AddYears(1600)
        }
        Else
        {
            $LastLogon = $Last.AddYears(1600).ToLocalTime()
        }
        If ($arrUsers.ContainsKey("$DN"))
        {
            If ($LastLogon -gt $arrUsers["$DN"])
            {
                $arrUsers["$DN"] = $LastLogon
            }
        }
        Else
        {
            $arrUsers.Add("$DN", $LastLogon)
        }
    }
}

# Output latest last logon date for each user.
$Users = $arrUsers.Keys
ForEach ($DN In $Users)
{
    $Date = $arrUsers["$DN"]
    "$DN;$Date" | Out-File $file -Append
}

Original script (without export to file) from: http://www.rlmueller.net/PowerShell/PSLastLogon.txt

Sample PowerShell Scripts with OMSA

(http://en.community.dell.com/techcenter/systems-management/w/wiki/sample-powershell-scripts-with-omsa.aspx)

sample Function to launch DRAC, based on computer name

Below are sample PowerShell scripts for querying data from OMSA – download the attached .txt file for all the examples.

get-wmiobject -namespace root\cimv2\dell -computer Server1 -list | sort-object name Displays all classes int he root\cimv2\dell namespace on Server1
$a = get-wmiobject dell_chassis -namespace root\cimv2\dell -computer Server1
$a | select-object AmpStatus, EsmLogStatus, FanRedStatus, FanStatus, MemStatus, Model, ProcStatus, PsRedStatus, PsStatus, SecurityBreach, SerialNumber, Status, SystemClass, TempStatus, VoltStatus, VrmStatus
Displayoverall hardware status based on info from Dell_Chassis
$a = get-wmiobject Dell_baseboard -namespace root\cimv2\dell -computer Server1
$a.PartNumber, $a.BaseBoardTypeDescString
Display the part number of the motherboard
$a = get-wmiobject cim_PhysicalMemory -namespace root\cimv2\dell -computer Server1
$a | select-object capacity, datawidth, formfactor, memorytype, name, speedasstring, status, tag, totalwidth | format-table
Displays Physical Memory information (speed, type, etc)
$a = get-wmiobject cim_temperaturesensor -namespace root\cimv2\dell -computer Server1
$a | select-object baseunits, CurrentReading, LowerThresholdCritical, LowerThresholdNonCritical, name, status, unitmodifier, upperthresholdcritical,upperthresholdnoncritical
Show Current Temperature sensor information (CurrentReading in Celsius)
get-wmiobject cim_tachometer -namespace root\cimv2\dell -computer Server1 | select-object Name, CurrentReading Displays Current Fan Speed
get-wmiobject cim_fru -namespace root\cimv2\dell -computer Server1 | select-object DeviceID, FRUManufacturerName, FRUPartNumberName, FRUSerialNumberName Displays “Field Replaceable Units” (FRU) information for specific components
get-wmiobject cim_powersupply -namespace root\cimv2\dell -computer Server1 | select-object name, DeviceID, Status, TotalOutputPower Displays the total output power of the supply – in milliwatts
get-wmiobject cim_processor -namespace root\cimv2\dell -computer Server1 | select-object CoreCount, CoreEnabledCount, CPUStatus, CurrentClockSpeed, DeviceID, MaxClockSpeed, Name | ft -autosize Displays processor information
get-wmiobject dell_networkport -namespace root\cimv2\dell -computer Server1 | select-object OSAdapterDescription, IsTOEEnable Displays if TCP Offload Engine (TOE) is enabled
$a = get-wmiobject DELL_PowerConsumptionData -namespace root\cimv2\dell -computer Server1
$a | select-object Name, CumulativePowerReading, maxPowerConsumption, minPowerConsumption, parStartTime, parTime, peakAmpReading, peakHeadRoom, peakWattReading, powerCap, powerCapCapabilities, pwrStartTime, pwrTime, Status
Displays valuable power consumption information – shows “CumulativePowerReading based from pwrStartTime, as well as min/max power consumption, and peak amps, watts, etc.
get-wmiobject CIM_BIOSElement -namespace root\cimv2\dell -computer Server1 | select-object InstallDate, Name, Version Displays BIOS Version, and installation date
get-wmiobject CIM_BIOSElement -namespace root\cimv2\dell -computer Server1 | % {$_.ConvertToDateTime($_.InstallDate), $_.Name, $_.Version} Convert BIOS Install Date time to a friendly date/time
get-wmiobject DELL_Firmware -namespace root\cimv2\dell -computer Server1 | select-object Name, Version Displays DRAC Version information
get-wmiobject Dell_SoftwareFeature -namespace root\cimv2\dell -computer Server1 | select-object Description, OmsaURL, Version Displays the OMSAURL used to connect to DRAC
function LaunchDrac($strComputerName)
{
$a = get-wmiobject Dell_SoftwareFeature -namespace root\cimv2\dell -computer $strComputerName | select-object Description, OmsaURL, Version
$ie = new-object -comobject InternetExplorer.Application
$ie.visible = $true
$ie.navigate(($a.omsaurl.split(‘,’))[0])
}
sample Function to launch DRAC, based on computer name

PowerCLI: Windows Disk Alignment on VMware

Searching for disk alignments off the windows 2003 servers on VMware ESX i found a CLI script which can automate the search. The original site: http://ict-freak.nl/2009/12/15/powercli-check-partition-alignment-windows-vms-only/

Script:

$myCol = @()
$vms = get-vm | where {$_.PowerState -eq "PoweredOn" -and `
$_.Guest.OSFullName -match "Microsoft Windows*" } | Sort Name 

foreach($vm in $vms){
$wmi = get-wmiobject -class "Win32_DiskPartition" `
-namespace "root\CIMV2" -ComputerName $vm            

    foreach ($objItem in $wmi){
        $Details = "" | Select-Object VMName, Partition, Status
            if ($objItem.StartingOffset -eq "65536"){
                $Details.VMName = $objItem.SystemName
                   $Details.Partition = $objItem.Name
                $Details.Status = "Partition aligned"
            }
            else{
                $Details.VMName = $objItem.SystemName
                   $Details.Partition = $objItem.Name
                $Details.Status = "Partition NOT aligned"
            }
    $myCol += $Details
    }
}
$myCol | Export-Csv -NoTypeInformation "C:\PartitionAlignment.csv"
#$myCol | Export-Clixml "C:\PartitionAlignment.xml"

PowerCLI: VMware Backup Script

Searching for way’s to create easy backup’s of a few virtual machines, i came on the website gestalt it (http://gestaltit.com/all/tech/virtualization/simon/vmware-backup-powercli-script/).

On this website there is a script which will create a snapshot of a VM, then clone it (thin provisioned) and finally remove the snapshot off the original VM.

Backup Script

# Import Backup CSV
$backupinfo =  Import-Csv C:\scripts\mybackups.csv

#Set Date format for clone names
$date = Get-Date -Format "yyyyMMdd"

#Set Date format for emails
$time = (Get-Date -f "HH:MM")

#Connect to vCenter
Connect-VIServer ""

foreach ($customer in $backupinfo)
{
	$vm = Get-VM $customer.MasterVM

	#Send Start Email
	C:\scripts\backupstartedemail.ps1

	# Create new snapshot for clone
	$cloneSnap = $vm | New-Snapshot -Name "Clone Snapshot"

	# Get managed object view
	$vmView = $vm | Get-View

	# Get folder managed object reference
	$cloneFolder = $vmView.parent

	# Build clone specification
	$cloneSpec = new-object Vmware.Vim.VirtualMachineCloneSpec
	$cloneSpec.Snapshot = $vmView.Snapshot.CurrentSnapshot

	# Make linked disk specification
	$cloneSpec.Location = new-object Vmware.Vim.VirtualMachineRelocateSpec
	$cloneSpec.Location.Datastore = (Get-Datastore -Name $customer.BackupDS | Get-View).MoRef
	$cloneSpec.Location.Transform =  [Vmware.Vim.VirtualMachineRelocateTransformation]::sparse

	$cloneName = "$vm-$date"

	# Create clone
	$vmView.CloneVM( $cloneFolder, $cloneName, $cloneSpec )

	# Write newly created VM to stdout as confirmation
	Get-VM $cloneName

	# Remove Snapshot created for clone
	Get-Snapshot -VM (Get-VM -Name $customer.MasterVM) -Name $cloneSnap | Remove-Snapshot -confirm:$False

	#Send Complete Email
	C:\scripts\backupcompletedemail.ps1
}
#Disconnect from vCentre
Disconnect-VIServer -Confirm:$false

Send Started Email Script

#Set Date format for emails
$timestart = (Get-Date -f "HH:MM")

$emailFrom = ""
$emailTo = ""
$subject = "[$vm - Backup Started]"
$body = "Backup Details
-------------
VM Name:",$vm,"
Clone Name:","$vm-$date","
Target Datastore:", $customer.BackupDS,"
Time Started:", $timestart

$smtpServer = ""
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom,$emailTo,$subject,$body)

Send Completed Email Script

#Set Date format for emails
$timecomplete = (Get-Date -f "HH:MM")

$emailFrom = ""
$emailTo = ""
$subject = "[$vm - Backup Complete]"
$body = "Backup Details
-------------
VM Name:",$vm,"
Clone Name:","$vm-$date","
Target Datastore:", $customer.BackupDS,"
Time Started:", $timestart,"
Time Completed:", $timecomplete
$smtpServer = ""
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom,$emailTo,$subject,$body)

CSV File

The content of the csv file is very simple. This is what mine looks like:

MasterVM,BackupDS
VM1,BackupDataStore
VM2,BackupDataStore

Automating VMware with PowerShell

LAB Summary
Welcome to the Automating VMware with PowerShell: Hands-On Lab. This lab will provide you hands-on experience in writing PowerShell scripts for managing VMware using the VI Toolkit (for Windows). Each participant will create scripts that will show you how to more effectively manage your virtual infrastructure. Some familiarity with PowerShell is helpful, but is not required. 
 
LAB Objective
The objective of this lab is to introduce you to the VI Toolkit (for Windows) and show you how easy automating VMware Virtual Infrastructure management is when you use PowerShell. We will cover a wide range of topics, including things like provisioning, storage, networking and monitoring. 

 Link: http://blogs.vmware.com/vipowershell/files/vmworld_europe_2008_powershell_lab_7_manual.pdf

Or local download: [wpdm_file id=”15″]

Get Daily CPU statistics in your mail

Thanks to the previous post (http://lucd.info/?p=1455) and a little extra scripting, i am able to run a script which will run daily scheduled and email the results to my mailbox.

This script will mail a CSV file with all cpu averages in 5 minutes samples between 7.30 and 19:30 off a specific Virtual machine.

If other counters are needed, you can find them in the following document: http://www.vmware.com/support/developer/vc-sdk/visdk25pubs/visdk25programmingguide.pdf

Beneath is the script i’m using (change all bold items):

Add-PSSnapin VMware.VimAutomation.Core

# Mail variables
$enablemail="yes"
$smtpServer = "smtpserver"
$mailfrom = "emailadres"
$mailto = "emailadres1,emailadres2"

# Server Variables
$VIServer = "viserver"
$vmName = "vmname"

# Log File Location
$log = "path\CPU_Stats" + "_" + $VMname+ ".csv"

# Connect to the VI Server
Connect-VIServer $VIServer

# Script
$esxImpl = Get-VM -Name $vmName
$todayMidnight = (Get-Date -Hour 0 -Minute 0 -Second 0).AddMinutes(-1)
$workingDays = "Monday","Tuesday","Wednesday","Thursday","Friday"
$dayStart = New-Object DateTime(1,1,1,7,30,0)     # 07:30 AM
$dayEnd = New-Object DateTime(1,1,1,19,30,0)      # 07:30 PM

$stats = Get-Stat -Entity $esxImpl -Stat cpu.usage.average -Start $todayMidnight.AddDays(-0) -Finish $todayMidnight.AddDays(+1)
$report = $stats | Where-Object {
	$workingDays -contains $_.Timestamp.DayOfWeek -and
	$_.Timestamp.TimeOfDay -gt $dayStart.TimeOfDay -and
	$_.Timestamp.TimeOfDay -lt $dayEnd.TimeOfDay
}

$report | Export-Csv $log -NoTypeInformation

if ($enablemail -match "yes")
{
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($log)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $mailfrom
$msg.To.Add($mailto)
$msg.Subject = “CPU Statistics $VMname”
$msg.Body = “Business-hours CPU Statistics are attached   ”
$msg.Attachments.Add($att)
$smtp.Send($msg)
}

$VIServer | Disconnect-VIServer -Confirm:$false

Get ESX host CPU and Memory stats

Use the following CLI to get the state of your ESX hosts, the cpu and memory usage:

t-Datacenter | Sort | Get-VMHost | Sort | Get-View |`
Select Name, OverallStatus, `
@{N="CPU Usage (GHz)";E={[math]::round(
$_.Summary.QuickStats.OverallCpuUsage/1024,2)}}, `
@{N="Memory Usage (GB)";E={[math]::round(
$_.Summary.QuickStats.OverallMemoryUsage/1024,2)}}

Add line 7 to it to get all status except green:

Get-Datacenter | Sort | Get-VMHost | Sort | Get-View | `
Select Name, OverallStatus, `
@{N="CPU Usage (GHz)";E={[math]::round(
$_.Summary.QuickStats.OverallCpuUsage/1024,2)}}, `
@{N="Memory Usage (GB)";E={[math]::round(
$_.Summary.QuickStats.OverallMemoryUsage/1024,2)}} | `
Where { $_.OverallStatus -ne "green" }

source: http://laez.nl/quick-and-simple-vmware-esx-host-statistics/