Powershell to sequentially shutdown VM guests, then restart the host

A little while back, I developed a script that read in server names from a text file and rebooted them. It was pretty straightforward, but I realised that this would never work for virtual machines because it’s not the best idea just to shut down the host without taking the guests into consideration. So I cam e up with the following script; it essentially does the same thing twice, but against two different text files (guest and host). This is important primarily because it shuts the guests down, but only restarts the host (there are other minor differences but the script is heavily commented). The sequence is as follows: repeatedly shut guests down with 2-minute intervals until the list runs out, then wait 3 minutes and restart the host. It also performs some logging and emailing (tho’ of course, each server still logs the normal EventLog entries). Schedule this, and you can gracefully restart your virtual hosts on a routine basis.

———————————————————————————————

#Script to reboot selected virtual servers
#Define hub transport server

 $smtp_server = “xxxx.someDomain.com”
#Define email sender and recipient.
#The intital text after the quotes after $sender are free-form;
#you can specify whatever name you want. This doesn’t work for $recipient
#as the system puts the real name on the email address.

 $sender = “senderEmail <senderEmail@somedomain.com>”
 $recipient = “recipientEmail <recipientEmail@somedomain.com>”
  #reads the contents of the specified text file one line at a time

  get-content someDrive:\someFolder\Scripts\rebootHVGuests.txt | Foreach-Object {
   #assigns $computerName to value from get-content

   $ComputerName=$_
#THIS SCRIPT DOES NOT LOG OR NOTIFY ABOUT SHUTTING DOWN VIRTUAL GUESTS
   #shuts the virtual guest down

   stop-computer -computername $ComputerName -force
#Script waits for 2 minutes before shutting down next guest

Start-Sleep -Seconds 120
}
#Script waits for 3 minutes before restarting hosts
Start-Sleep -Seconds 180
  #reads the contents of the specified text file one line at a time

  get-content someDrive:\someFolder\Scripts\rebootHVHosts.txt | Foreach-Object {
   #Define date and time variables

   $dateNow = get-date -displayhint date
   #assigns $computerName to value from get-content

   $ComputerName=$_
   #Define email subject and body

    $msg_subject = “Planned system reboot of $ComputerName”
    $msg_body_text = “Server $ComputerName is being forcibly rebooted at: $dateNow”
    #Send it

    Send-MailMessage -to $recipient -from $sender -subject $msg_subject -body $msg_body_text -smtpserver $smtp_server
   # Writing an event log entry

    $EventLog = New-Object System.Diagnostics.EventLog(‘Application’)
    $EventLog.MachineName = “.”
    $EventLog.Source = “someCustomEvent”
    $EventLog.WriteEntry(“Now rebooting $ComputerName”,”Information”, $EventID)
   #restarts the virtual host

   restart-computer -computername $ComputerName -force
}

———————————————————————————————

Avoid NMAP OS detection

Hmmm…. someone asked me if there was any way to protect a target from, say, NMAP OS detection. I didn’t know and a bit of searching pointed me here:

http://www.irongeek.com/i.php?page=security/osfuscate-change-your-windows-os-tcp-ip-fingerprint-to-confuse-p0f-networkminer-ettercap-nmap-and-other-os-detection-tools

Which sounded interesting, but also gave me a few pointers. I trawled HKLM\System\CurrentControlSet\Services\Tcpip but couldn’t see anything that looked like it was really usefully editable (or I was worried that it would completely mess up the networking). I tried changing this value- …\Parameters\TcpWindowSize and it looks like this has done it. If the value is set to (Decimal) 64240, my test box is Windows XP. It also lists 21 open ports in green. Change the value to 64241, NMAP no longer has any real idea what OS I’m running (although it does think maybe it’s an i686 Windows OS) and the number of open ports in green drops to 17.

Of course, I have no idea what impact this has on a machine- this link http://technet.microsoft.com/en-us/library/bb463205.aspx– explains what that value does but it could be doing something ‘orrible so change it at your own risk. However, it’s quite an easy way to hide your machine from NMAP OS scans- I’ve tried NMAP with a few aggressive scan options and none of them seem to work. At the very least, it’s a quick way to guard against casual port scans.

Automated file deletion #01

————————————————————————————————————-

new-psdrive -name SomeFolder -psprovider FileSystem -root \\SomeShare\SomeFolder
$drive = new-object -com wscript.network
$drive.MapNetworkDrive(“x:”, “\\SomeShare\SomeFolder”)

$EnumerateOpen = Get-ChildItem o:\ -recurse -include .DS_Store -force
foreach($FileName in $EnumerateOpen)
 {
  $FileName.Delete()
 }

remove-psdrive -name SomeFolder

$drive.RemoveNetworkDrive(“x:”)

—————————————————————————————–

As with my previous post, this script does nothing apart from delete irritating files that do nothing apart from waste space. In this case, it’s the lovely .DS_Store files that Mac OS X throws around with glee. I’ve got a feeling you can put loads of file types in one script, but I’ve got a script per file type to (a) make testing easier- didn’t want to risk accidentally wiping out more than I’d intended and (b) to make it easier for others to follow.

Remeber that although your .DS_Store is “only” 7KB in size, it’s probably taking up way more space than that because file systems have minimum block sizes. According to this link- http://support.microsoft.com/kb/140365– any Windows OS from the last 12 years will default to a minimum block size of 4KB, so that 7KB file is already wasting 1KB of space. Multiply that by the number of .DS_Store files lying around and that’s a lot of wasted space. Add in all those accidentally created .lnk files, thumbs.db etc- just bin ’em.

Empty folders script #1

Sick of empty folders lying around making storage look messy? This script:

—————————————————————————————

new-psdrive -name someFolder -psprovider FileSystem -root “SomeDrive:\SomeFolder”

$foldersTotal = (Get-ChildItem “SomeDrive:\SomeFolder” -recurse -force | Where-Object {$_.PSIsContainer -eq $True})

foreach($folder in $foldersTotal)
{
 if($folder.GetFiles().Count -eq 0 -and $folder.GetDirectories().Count -eq 0)
 {$folder.Delete()}
}

remove-psdrive -name SomeFolder

—————————————————————————————

Recurses through any folder tree looking fomr completely empty folders. When it finds them, it deletes them. The catch? Depending on how badly “infested” storage is with empty folders, this can take ages and an unknown nubmer of iterations because it can only delete the lowest folder each time (if you have 3 empty folders- F1, F2 and F3 with F3 being the “lowest” in the tree, F3 is obviously the only completely empty folder as F2 ocntains F3, and F1 contains F2 and F3). So you might need to run it a lot, but it’s worth it. Once it stops finding empty folders, stick it in task scheduler to run every day (after hours, or else people might see their newly-creatd folders vanish before they’ve had a chance to put anything in it).

Useful Dell SUU commands

I know suu.cmd has accepted various switched for a long time now, but this is the first time I’ve bothered to engage with it!

So, running SUU v 7.1.1.162:

\\some server\some share\suu.cmd -comparison

will generate a report telling you what can and can’t be upgraded. Most of the time you won’t care, but it’s worth remembering that this program will update network firmware, drivers and disk firmware etc so only run on critical systems after hours.

Then,

\\some server\some share\suu.cmd -upgradeonly

will ONLY upgrade components, never downgrade. It’ll do everything in one hit so you’ll probably need to reboot after this, and you may lose networking a lot as it runs so running suu either stood at the console or via remote desktop is recommended.

Hyper-V server 2012

Another new OS. Except this one is completely free (as in, you can use it legally without paying for it which must be a first from Microsoft!). However… besides being sufficiently cut-down to run just Hyper-V, you also only get a command line. So it has the same user-friendliness as Server Core, without most of the functionality. It’s probably not ideal for a production environment (after all, most of Windows server is missing and there’s no support) but is great for testing- I’ve got it running as the secondary boot on a 3-year old Dell laptop and it does exactly what it says on the tin- I can create an entire Hyper-V environment on it from my W8 workstation, including being able to use all the new PowerShell commands.

Windows Server 2012 #01

Along with Windows 8, Server 2012 is also blindingly fast, but very, very different (so different that I think I still haevn’t found cmd.exe. So I just start powershell, then run cmd.exe from the powershelll window if I need to!). Again however, it’s very easy if you give it half a day- looks and feels like W8 and has so much additional functionality it’s hard to believe (the dedupe on it is, I suspect, better than anything else on the market and even if it’s not it’s free)