Monday, October 14, 2013

Powershell: Add NFS Exports to ESXi Hosts

Purpose:  Batch add all NFS exports to all ESXi hosts listed in $HostsToAddNFS variable.

#Add all ESXi Hosts names
$HostsToAddNFS = "hostname1","hostname2"

foreach ($Current_Host in $HostsToAddNFS )

{
connect-viserver $Current_Host
#add all NFS exports here
New-Datastore -Nfs -Name Volume1 -Path "/vol/volume1" -NfsHost x.x.x.x
New-Datastore -Nfs -Name Volume2 -Path "/vol/volume2" -NfsHost x.x.x.x


}

Monday, October 7, 2013

VMware: Change Load Balance Policy to IP Hash on ESXi Host Console

This command changes the vSwitch Load Balance Policy to iphash

esxcli network vswitch standard policy failover set -l iphash -v vSwitch0

This command changes the Port Group Management Network Load Balance Policy iphash

esxcli network vswitch standard portgroup policy failover set -p "Management Network" -l iphash

Wednesday, May 29, 2013

Batch - Get time from remote server write to csv audit log



Purpose: needed a hacked up batch file that was able to read time from a remote server and log to a CSV for user logon auditing. They may have been a better way to do this in batch, but after about 5 hours of looking i decided to just write my own. Wish i could have used powershell. Note:I found that using the net time //x.x.x.x command against a server can return different formatted results I think this script is able to handle the differences but i can not be certain without further testing
@echo off
REM Tony Unger
REM
REM login audit script
REM For Log In
Rem Writes to a CSV file
REM Thanks to http://brisray.com/comp/batch3.htm for length checking in batch


setlocal EnableDelayedExpansion
for /f "delims=" %%i in ('net time \\servername') do (
    if "!CurrentTime!"=="" (set CurrentTime=%%i) else (set CurrentTime=!CurrentTime!#%%i)

)

echo %CurrentTime%
Echo parse the Net Time command
FOR /f "tokens=6,7,8" %%a IN ("%CurrentTime%") DO (
SET _date=%%a
SET _time=%%b
SET _AMPM=%%c
Echo after read ampm is %_AMPM%
If %_AMPM% ==AM#Local (
FOR /f "tokens=14,15,16" %%a IN ("%CurrentTime%") DO (
SET _date=%%a
SET _time=%%b
SET _AMPM=%%c
)
)
If %_AMPM% ==PM#Local (
FOR /f "tokens=14,15,16" %%a IN ("%CurrentTime%") DO (
SET _date=%%a
SET _time=%%b
SET _AMPM=%%c
)
)
Echo Now it is equal to: %_AMPM%

if %_HourUpdate% == 01 (set _HourUpdate=13)
Echo Break up the date to Day Month Year
for /f "tokens=1,2,3 delims=/ " %%A in ("%_date%") DO (
SET _Month=%%A
SET _Day=%%B
SET _Year=%%C
)
Echo Breakup Time to Hour Min Sec
for /f "tokens=1,2,3 delims=: " %%A in ("%_time%") DO (
SET _Hour=%%A
SET _Min=%%B
SET _Sec=%%C
)
Echo Removing spaces
set _Year=%_Year: =%
set _MonthUpdate=%_MonthUpdate: =%
set _Day=%_Day: =%
set _Hour=%_Hour: =%
set _Min=%_Min: =%
set _Sec=%_Sec: =%
REM
Echo Convert Month to two digits
set c=%_Month%
:Monthloop
if defined c (set c=%c:~1%&set /A _MonthCount += 1&goto Monthloop)
Echo Found %_MonthCount% in Month string
if "%_MonthCount%" LSS "2" (set _MonthUpdate=0%_Month%)
IF "%_MonthCount%" GTR "1" (set _MonthUpdate=%_Month%)
Echo %_MonthUpdate%
REM
Echo Convert Day to Two Digits
echo %_Day%
set c=%_Day%
:Dayloop
if defined c (set c=%c:~1%&set /A _DayCount += 1&goto Dayloop)
Echo Found %_DayCount% in day string
if "%_DayCount%" LSS "2" (set _DayUpdate=0%_Day%)
IF "%_DayCount%" GTR "1" (set _DayUpdate=%_Day%)
Echo %_DayUpdate%
REM
Echo Convert Hour to two digits
set c=%_Hour%
:Hourloop
if defined c (set c=%c:~1%&set /A b += 1&goto Hourloop)
Echo Found %b% in hour string
if "%b%" LSS "2" (set _HourUpdate=0%_Hour%)
IF "%b%" GTR "1" (set _HourUpdate=%_Hour%)
REM
Echo %_HourUpdate%
Echo Convert Hour to 24Hour
if %_AMPM%==PM#Local (
  if %_HourUpdate% == 01 (set _HourUpdate=13)
  if %_HourUpdate% == 02 (set _HourUpdate=14)
  if %_HourUpdate% == 03 (set _HourUpdate=15)
  if %_HourUpdate% == 04 (set _HourUpdate=16)
  if %_HourUpdate% == 05 (set _HourUpdate=17)
  if %_HourUpdate% == 07 (set _HourUpdate=19)
  if %_HourUpdate% == 08 (set _HourUpdate=20)
  if %_HourUpdate% == 09 (set _HourUpdate=21)
  if %_HourUpdate% == 10 (set _HourUpdate=22)
  if %_HourUpdate% == 11 (set _HourUpdate=23)
  ) ELSE (
  if %_HourUpdate% == 12 (set _HourUpdate=00)
  )
if %_AMPM%==PM#The (
  if %_HourUpdate% == 01 (set _HourUpdate=13)
  if %_HourUpdate% == 02 (set _HourUpdate=14)
  if %_HourUpdate% == 03 (set _HourUpdate=15)
  if %_HourUpdate% == 04 (set _HourUpdate=16)
  if %_HourUpdate% == 05 (set _HourUpdate=17)
  if %_HourUpdate% == 07 (set _HourUpdate=19)
  if %_HourUpdate% == 08 (set _HourUpdate=20)
  if %_HourUpdate% == 09 (set _HourUpdate=21)
  if %_HourUpdate% == 10 (set _HourUpdate=22)
  if %_HourUpdate% == 11 (set _HourUpdate=23)
  ) ELSE (
  if %_HourUpdate% == 12 (set _HourUpdate=00)
  )
REM
Echo  Convert Mins to two digits
set c=%_Min%
:Minloop
if defined c (set c=%c:~1%&set /A _MinCount += 1&goto Minloop)
Echo Found %_MinCount% in minute string
if "%_MinCount%" LSS "2" (set _MinUpdate=0%_Min%)
IF "%_MinCount%" GTR "1" (set _MinUpdate=%_Min%)
Echo %_MinUpdate%
REM This is done incase seconds doesn't return as in older versions of windowss
if "%_Sec%"==" " SET _Sec=00
REM Remove Spaces from Strings
set _Year=%_Year: =%
set _MonthUpdate=%_MonthUpdate: =%
set _DayUpdate=%_DayUpdate: =%
set _HourUpdate=%_HourUpdate: =%
set _MinUpdate=%_MinUpdate: =%
set _Sec=%_Sec: =%
if not %_MonthUpdate%==is echo Log Off,%_Year%-%_MonthUpdate%-%_DayUpdate% %_HourUpdate%:%_MinUpdate%:%_Sec%,%COMPUTERNAME%,%USERNAME%  >> \\servername\audit\%USERNAME%.csv
if %_MonthUpdate%==is echo %date:~10,4%-%date:~4,2%-%date:~7,2%,%COMPUTERNAME%,%USERNAME% >> \\servername\audit\errors.txt

Tuesday, May 28, 2013

Powershell: Get permissions on each vfiler cifs share.

Purpose: Get a list of all shares on each vfiler on each filer Notes: This script needs some work with the nested foreach loops and some error check cleanup.

Import-Module dataontap

Function Get-ACLPermissions($Share){
 $acl = Get-Acl -Path $Share
return $ACL
}

$myCol = @()

$AllNetappFiler = "filer03","filer02"

foreach ($NetappFiler In $AllNetappFiler){


  write-host "Scanning $NetappFiler"   
 connect-nacontroller $NetappFiler | out-null
    $Vfilers = get-navfiler * | Select -expand Name
 foreach ($Vfiler in $Vfilers){
  connect-nacontroller $Vfiler 
  $vfiler
  $Shares = get-nacifsshare | Select -expand ShareName
  foreach ($Share in $Shares){
   Write-Host "$Vfiler insideloop"
   
   #If $Vfiler Blank then scan shares on filer.. Need to add logic
   $fullpath = "\\$Vfiler\$Share"
   
   
   
   $ShareACL = Get-ACLPermissions $fullpath
   $o = 0
   $ShareACL.Access | ForEach-Object {
    $Detail = New-Object PSObject  
    $Detail | Add-Member Noteproperty SystemName $NetappFiler
    $Detail | add-member Noteproperty Vfiler $Vfiler
    $Detail | Add-Member noteProperty Share $Share 
    
    $FileSystemRights = $ShareACL.Access[$o] | Select -ExpandProperty FileSystemRights #Example ReadAndExecute 
    $AccessControlType = $ShareACL.Access[$o] | Select -ExpandProperty AccessControlType #Example Allow/Deny
    $IdentityReference = $ShareACL.Access[$o] | Select -ExpandProperty IdentityReference #Example Everyone,Username
    $IsInherited = $ShareACL.Access[$o] | Select -ExpandProperty IsInherited #Are Permissions inherited
    $InheritanceFlags = $ShareACL.Access[$o] | Select -ExpandProperty InheritanceFlags #Type of Inheritance ContainerInherit
    $PropagationFlags = $ShareACL.Access[$o] | Select -ExpandProperty PropagationFlags #PropagationFlags
    
    switch -wildcard ($FileSystemRights) 
        { 
            "268435456*" {$FileSystemRights = "FullControl"} 
            "-536805376*" {$FileSystemRights = "Modify, Synchronize"} 
            "-1610612736*" {$FileSystemRights = "ReadAndExecute, Synchronize"} 
        }
     
    $Detail | Add-Member noteProperty IdentityReference $IdentityReference  
    $Detail | Add-Member noteProperty FileSystemRights $FileSystemRights
    $Detail | Add-Member noteProperty AccessControlType $AccessControlType
    $Detail | Add-Member noteProperty IsInherited $IsInherited
    $Detail | Add-Member noteProperty InheritanceFlags $InheritanceFlags  
    $Detail | Add-Member noteProperty PropagationFlags $PropagationFlags 
    $o++
    
    $myCol += $Detail
    }
  }


 } 
}
$myCol | Export-Csv -Path "c:\temp\Audit_NetappVfilerCifis.csv" -NoTypeInformation

Tuesday, May 21, 2013

Powershell: Gather all user objects and report lastlogon and lastlogontimestamp to CSV file


Purpose:
Connects to active directory and pulls a list of all user objects and create a report of lastlogon and lastlogontimestamp values

Note: This is something i did around midnight so i need to do further testing on this script to ensure the data is correct and the lastlogon value will only be from the DC the script is running against

  
#Tony Unger
#Scans all user accounts and reports lastlogon and lastlogontimestamp attr.

Import-Module ActiveDirectory

$AllUsers = get-aduser -Filter * -SearchBase "DC=microsoft,DC=Com" -Property SamAccountName,Lastlogon,LastlogonTimeStamp | Select Name,UserPrincipalname,SamAccountName,@{Name='Last Logon Timestamp';Expression={[System.DateTime]::FromFileTime($_.LastLogonTimestamp).ToString('g')}},@{Name='Last Logon';Expression={[System.DateTime]::FromFileTime($_.LastLogon).ToString('g')}}

$AllUsers | Export-Csv -Path "c:\Audit_UsersLastLogon.csv" -NoTypeInformation




Thursday, May 9, 2013

Powershell: Read servers from AD and search for shares and return ACL permissions


Purpose:
Connects to active directory and pulls a list of all computer objects that are servers and check ACL permissions

  
Import-Module ActiveDirectory
#Most of the information to do this was from this site.
#http://blogs.technet.com/b/heyscriptingguy/archive/2009/09/14/hey-scripting-guy-september-14-2009.aspx

Function Get-ACLPermissions($Share){

    $acl = Get-Acl -Path $Share

return $ACL

}


function Get-MyShares

{
#Function by
#http://www.peetersonline.nl/2008/11/finding-shares-with-powershell/

     param([string]$Server)
     $Shares = Get-WmiObject -Class Win32_Share -ComputerName $Server
     $output = @()
         ForEach ($Share in $Shares)
         {
              $fullpath = “\\{0}\{1}” -f $server, $share.name
              Add-Member -MemberType NoteProperty -InputObject $Share -Name FullPath -Value $fullpath
              $output += $Share
         }
         Return $output
}

#Path to where the CSV file is written to
$PathtoCSV = "C:\temp\AuditACL.csv"

#Create Header in CSV
"Server;Share;Username;FileSystemRights;AccessControlType;IsInherited;InheritanceFlags" > $PathtoCSV 
#Get all computers that are servers from AD
$Servers = Get-ADComputer -Filter {OperatingSystem -Like "Windows Server*"} -Property * | Select -Expand Name
$i = 0
foreach ($Server in $Servers)
# update counter and write progress
{
   $i++
   Write-Progress -activity "Scanning Machine $Server" -status "Scanned: $i of $($Servers.Count)" -percentComplete (($i / $Servers.Count)  * 100)
   
# Get all Shares on server
    $Shares = Get-MyShares $Server | Select -ExpandProperty Name 
        foreach ($Share_Current in $Shares){
        #Process all Shares on Server
            $fullpath = "\\$Server\$Share_Current"
            $ShareACL = Get-ACLPermissions $fullpath
            $o = 0
            $ShareACL.Access | ForEach-Object {
            $FileSystemRights = $ShareACL.Access[$o] | Select -ExpandProperty FileSystemRights #Example ReadAndExecute
            $AccessControlType = $ShareACL.Access[$o] | Select -ExpandProperty AccessControlType #Example Allow/Deny
            $IdentityReference = $ShareACL.Access[$o] | Select -ExpandProperty IdentityReference #Example Everyone,Username
            $IsInherited = $ShareACL.Access[$o] | Select -ExpandProperty IsInherited #Are Permissions inherited
            $InheritanceFlags = $ShareACL.Access[$o] | Select -ExpandProperty InheritanceFlags #Type of Inheritance ContainerInherit
            $PropagationFlags = $ShareACL.Access[$o] | Select -ExpandProperty PropagationFlags #PropagationFlags
            $o++

            switch -wildcard ($FileSystemRights) 
            { #Should be a better way to do this via function
                "268435456*" {$FileSystemRights = "FullControl"} 
                "-536805376*" {$FileSystemRights = "Modify, Synchronize"} 
                "-1610612736*" {$FileSystemRights = "ReadAndExecute, Synchronize"} 
            }
            $Combine = $Server,$fullpath,$IdentityReference,$FileSystemRights,$AccessControlType,$IsInherited,$InheritanceFlags
            Write-Host "$Combine to $PathtoCSV"
            $Combine -join ";" >> $PathtoCSV
        } 
}
}





Wednesday, April 24, 2013

Enable USB that has been disabled via GPO


Save the following as a batch file and run as a local admin account:


REM
REM


icacls c:\Windows\inf\usbstor.inf /reset
icacls c:\Windows\inf\usbstor.pnf /reset
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies" /v WriteProtect /t REG_DWORD /d 00000000 /f


REM
REM
REM
REM


Note:
This will fix the installation of SP1 for Win7/2008r2 that fails because of usb being disabled.

Thursday, March 14, 2013

CF-29 Intel wifi driver gnu/linux backtrack


CF-29 Toughbook

I received an old Toughbook CF-29 laptop from a friend and decided to install backtrack 5.3. An issue i was having was getting the intel driver to install.

I verified the firmware was in the correct location via

root@bt:~# ls /lib/firmware/ | grep ipw
ipw2100-1.3.fw
ipw2100-1.3-i.fw
ipw2100-1.3-p.fw
ipw2200-bss.fw
ipw2200-ibss.fw
ipw2200-sniffer.fw
ipw_firmware

Next i ran the following command

root@bt:~# dmesg | grep ipw2200
[   26.409354] ipw2200: Intel(R) PRO/Wireless 2200/2915 Network Driver, 1.2.2kmprq
[   26.409359] ipw2200: Copyright(c) 2003-2006 Intel Corporation
[   26.409494] ipw2200 0000:02:01.0: PCI INT A -> Link[LNKD] -> GSI 9 (level, low) -> IRQ 9
[   26.409520] ipw2200: Detected Intel PRO/Wireless 2915ABG Network Connection
[   26.509132] ipw2200: ipw2200-bss.fw request_firmware failed: Reason -2
[   26.509141] ipw2200: Unable to load firmware: -2
[   26.509146] ipw2200: failed to register network device
[   26.509193] ipw2200 0000:02:01.0: PCI INT A disabled
[   26.509242] ipw2200: probe of 0000:02:01.0 failed with error -5
[   39.384317] ipw2200: Intel(R) PRO/Wireless 2200/2915 Network Driver, 1.2.2kmprq
[   39.384323] ipw2200: Copyright(c) 2003-2006 Intel Corporation
[   39.384455] ipw2200 0000:02:01.0: PCI INT A -> Link[LNKD] -> GSI 9 (level, low) -> IRQ 9
[   39.384483] ipw2200: Detected Intel PRO/Wireless 2915ABG Network Connection
[   39.387815] ipw2200: ipw2200-bss.fw request_firmware failed: Reason -2
[   39.387822] ipw2200: Unable to load firmware: -2
[   39.387827] ipw2200: failed to register network device
[   39.387870] ipw2200 0000:02:01.0: PCI INT A disabled
[   39.387907] ipw2200: probe of 0000:02:01.0 failed with error -5



Searched google and found
http://ubuntuforums.org/showthread.php?t=2100934
Ran this command the the issue was corrected
sudo modprobe -r ipw2200 && sudo modprobe ipw2200

Thursday, February 21, 2013

Powershell - Find VM raw disk path to netapp lun


Purpose:
I needed a way get raw disk mappings from a vmware vm to the lun it is using on a netapp filer. One thing that needs to be edited is the SearchFilers function. Just add your runtime names and what filers they correspond to.Run this from powercli. and this requires the dataontap module which you can get from your now.netapp.com site Note: this script could be improved by gather all lun information from each filer instead of what i did the in the search filer function

              
param([string]$VC)
Import-Module DataONTAP
#########################
####Tony Unger
#########################


#################Functions##############################################
function GetNetappPath([string]$VMHost,[string]$VMHDLunID,[string]$RuntimeName) {
$stor = get-view (Get-VMHostStorage -VMHost $VMHost)
$IscsiWWN = $stor.StorageDeviceInfo.HostBusAdapter | where {$_.GetType().Name -eq "HostInternetScsiHba"} | Select -First 1 -expandproperty IScsiName
Write-Host "Found ISCSI NAME: $IscsiWWN on Host $VMHost"
$c = SearchFilers $IscsiWWN $RuntimeName
Write-Host "Netapp path: $c"
return $c
}

function SearchFilers([string]$IscsiWWN,[string]$RuntimeName){

switch -wildcard ($RuntimeName) 
    { 
       #Add all you runtime names here with what filer
        "vmhba40:C0:T0*" {$NetappFiler = "x.x.x.x"} 
        
        default {Write-host "Error! determining filer - $RuntimeName not found";read-host}
    }
 
 Write-host "Connecting to $NetappFiler"
connect-nacontroller $NetappFiler | out-null

$Igroup = get-nalun | Get-Nalunmap | Select Name,Initiators | Where {$_.Initiators -like $IscsiWWN} | Select -First 1 -expandproperty Name
$a = get-nalunbyigroup $Igroup $VMHDLunID | Select -ExpandProperty Path
Write-Host "SearchFilers function: $a"
$a = "$NetappFiler$a"
 return $a
 }
 
#################Functions##############################################
########################
$PathtoCSV = "C:\temp\VMlunID.csv"
########################
If ($VC){$strVC = $VC}
ELSE{$strVC = Read-Host "What is the Vcenter hostname?"}
If (!$strVC){Write-Host "Error: Vcenter not entered";exit}
Connect-VIServer -Server $strVC  #Enter your vCenter Server
"Hostname,DiskID,CapacityG,HD Path,ScsiCanonicalName,LunID,ESX Host,Netapp Path" > $PathtoCSV
Write-Host "Getting VM Information from Vcenter. This can take awhile based on how many VM you have"
$Disks = Get-VM | Get-HardDisk | Where {"RawPhysical","RawVirtual" -contains $_.DiskType}
Write-Host "Completed getting VM Information from Vcenter"
Write-Host ""
Write-Host "Querying SCSI Information for Vcenter"
#Adding all hosts Canonicalnames and runtimes names to a hash table 
#thanks http://communities.vmware.com/people/LucD
$lunTab = @{}
Get-VMHost  | Get-ScsiLun | %{
  $lunTab.Add($_.VMHost.Name + $_.CanonicalName, $_.RuntimeName)
}
Write-Host "Completed SCSI Information for Vcenter"

Foreach ($Disk in $Disks) {
$VMName = $Disk.Parent
write-host "VM Name: $VMName"
$VMHDname = $Disk.Name
write-host "Hard drive ID: $VMHDname"
$VMCapacityGB = $Disk.capacityGB
write-host "Lun Capacity(GB): $VMCapacityGB"
$VMHDPath = $Disk.filename
write-host "RAW VMDK Path: $VMHDPath"
$VMScsiCanonicalName = $Disk.ScsiCanonicalName
write-host "$ScsiCanonicalName: $VMScsiCanonicalName"
$VMHost = Get-VM $VMName | Select -ExpandProperty VMHost
write-host "ESX Host: $VMHost"
$RuntimeName = $lunTab[$VMHost.Name + $Disk.SCSICanonicalName]
write-host "RuntimeName: $RuntimeName"
$VMHDLunID = $RuntimeName.Substring($RuntimeName.LastIndexof(“L”)+1)
Write-Host "LunID: $VMHDLunID"
$NetappPath = GetNetappPath $VMHost $VMHDLunID $RuntimeName
Write-host "PathtoNetapp: $NetappPath"
$Combine = $VMName,$VMHDname,$VMCapacityGB,$VMHDPath,$VMScsiCanonicalName,$VMHDLunID,$VMHost,$NetappPath
Write-Host "Writing to $PathtoCSV"
$Combine -join "," >> $PathtoCSV
}

Tuesday, January 22, 2013

Netapp Replace disk on sans


I would suggest that you be on the line for support for this one (but that being said it was easy to do.)
Once the drive is replace and you need to move the data from the Large 450 drive to the 300 drive do this
Command line
Run the  sysconfig -r
This will give you a list of the drives and the spares will show up in the end
If a spare shows up as NON Zero you must Zero it.
Run this command (it will not hurt anything to run this if there is no disk to Zero)
disk zero spares

Run this command to move the data.
disk replace start  (from drive) (to drive)
Example  disk replace start 1a.44 1a.17        this will move the data from drive 1a.44  to drive 1a.17
Once the data is move the drive will be available for a spare.
 

Powershell Netapp - Total Volume size using get-navol


Purpose:
I needed a way to query a netapp filer to give all the volumes and their total size with snapshot reserve.This is my second powershell script so be easy on me :-) Also this requires dataontap powershell toolkit


              
param([string]$NetAppHost, [string]$username)

Import-module DataOnTap

$PathtoCSV = "C:\NetappTotalVolume.csv"

If ($NetAPPHost){$strNetAPPHost = $NetAPPHost}
ELSE{$strNetAPPHost = Read-Host "What is the Netapp hostname/IP?"}
If (!$strNetAPPHost){Write-Host "Error: Netapp hostname/ip not entered";exit}


If ($username){$strusername = $username}
ELSE{$strusername = Read-Host "What username?"}
If (!$strusername){Write-Host "Error: Username not entered";exit}

Connect-NAController $strNetAPPHost –cred $strusername

$allvolumesnames = get-navol | Select-Object Name,Available,TotalSize,snapshotpercentreserved

#set headers of CSV file
"Hostname,Available Space(GB),Used Space(GB),Total Volume Space(GB)" > $PathtoCSV
foreach ($netapp_vol in $allvolumesnames) {

$CurrentVolname = $netapp_vol.name
$VolumeSizeTotal = [math]::Round([decimal]((($netapp_vol.snapshotpercentreserved * 100) * $netapp_vol.TotalSize) + $netapp_vol.TotalSize)/1gb,2)
$VolumesAvailable =  [math]::Round([decimal]$netapp_vol.available/1gb,2)

#Create/add to CSV file
$Combine = $CurrentVolname,$VolumeAvailable1GB,$VolumeUsedSpace1GB,$VolumeSizeTotal1GB
$Combine -join "," >> $PathtoCSV
                 
    }               

Thursday, January 17, 2013

Powershell VMware NTP


Purpose:
This is my first powershell script. It connects to a esxi host and removes all NTP servers dynamically then sets the new ones.

param([string]$VC, [string]$NTP1, [string]$NTP2)

If ($VC){$strVC = $VC}
ELSE{$strVC = Read-Host "What is the Vcenter hostname?"}
If (!$strVC){Write-Host "Error: Vcenter not entered";exit}

If ($NTP1){$strNTP1 = $NTP1}
ELSE{$strNTP1 = Read-Host "What is the first NTP server?"}
If (!$strNTP1){Write-Host "Error: NTP1 not entered need at least one NTP server";exit}

If ($NTP2){$strNTP2 = $NTP2}
ELSE{$strNTP2 = Read-Host "What is the second NTP server?"}


Connect-VIServer -Server $strVC  #Enter your vCenter Server

$NtpServers = @($strNTP1,$strNTP2)
#http://day2dayadmin.blogspot.com/2009/10/ntp-powershell-its-about-time.html
$ESXHosts = Get-VMHost | Select-Object Name,@{Name="NTP Server";Expression={$_ | Get-VMHostNtpServer}}, @{Name="NTP Running";Expression={($_ | Get-VMHostService | Where-Object {$_.key -eq "ntpd"}).Running}} | Sort-Object -Property "NTP Running", "NTP Server"



ForEach ($ESXHost in $ESXHosts) {
   
   
#Write-Host $ESXHost

   #remove current NTP servers
   Write-Host "Removing NTP servers" -BackgroundColor "Green" -ForegroundColor "Black"
   Remove-VMHostNtpServer -NtpServer $ESXHost."NTP Server" -VMHost $ESXHost.Name
   #Add new NTP servers
   Write-Host "Adding New NTP servers" -BackgroundColor "Green" -ForegroundColor "Black"
   Add-VmHostNtpServer -NtpServer $NtpServers -VMHost $ESXHost.Name
   #Stop NTP service   
   Write-Host "Stopping NTP Service" -BackgroundColor "Green" -ForegroundColor "Black"
   Get-VmHostService -VMHost $ESXHost.Name | Where-Object {$_.key -eq "ntpd"} | Restart-VMHostService
 
}
Write-Host "Done!"