Thursday, 19 July 2012

LttP: Powershell Games 2012 - Beginner Event 8

Beginner Event 8 has me a bit worried, as I think it's a bit easy.  That normally means I've missed something big and, normally, painfully obvious...

As far as I can tell the design points boil down to this:
  • Write the output to the host
  • Check if the machine is a laptop or desktop based on hardware
  • Only run it on the local computer
  • If it needs admin rights, check that it's running as admin
  • Use a simple function that returns a Boolean value
This means that the whole "inventory of machine on the network" part is a red-herring, and that what I should end up with is something fairly simple.

Here's my thought process on how I tackled those design points:
  • Build up my "message" and use Write-Host to output it at the end
  • Check for a battery using WMI (there is probably a WMI class for that...)
  • Local computer only...no problem
  • Get-WMIObject doesn't need admin rights...so I'm good here so far
  • I'll use a function to work out if the machine has a battery, then use an If statement to amend the message accordingly
Turns out I was right about WMI and there is a Win32_PortableBattery class.  When I run it on my desktop I get nothing, and an error is thrown when trying to run the following:

Get-WMIObject Win32_PortableBattery | Get-Member

That looks good to me, because my desktop doesn't have a portable battery. 

I checked Get-WMIObject Win32_PortableBattery on a laptop and it returned results so, armed with that confidence I charged off and wrote the following to become my "entry":

Function Is-Laptop
{
 If(Get-WMIObject Win32_PortableBattery)
 {
  Return $true
 }
 else
 {
  Return $false
 }
}

$comupterType="desktop"

If(Is-Laptop)
{
 $comupterType="laptop"
}

$Message=$Env:COMPUTERNAME
$Message+=" is a "
$Message+=$comupterType

write-host $Message

Time to read the expert commentary.

UPDATE:

I'm not sure how I would've scored as I used a different WMI class than the expert, and therefore a slightly different approach for figuring out if a machine was a desktop or laptop.

In my entry I basically said that if the machine has a portable battery then it's a laptop; which isn't strictly true because of tablets and slates (although not all that common); but I considered it a reasonable assumption.

No comments: