Click an Ad

If you find this blog helpful, please support me by clicking an ad!

Tuesday, July 1, 2014

Stepping up my Powershell Game

I watched a fascinating video about Powershell in the enterprise from a talk at TechEd given by Don Jones. It made me realize that it was time to step up my game a bit when it came to Powershell.

Two things I've decided to get more serious about are functions and version control. Version control doesn't look like it will be too hard to implement. We don't have any developers in-house so I don't have anything at-hand to use, but Sapien makes a version control system that I'm going to take a look at.

Most of the scripts I write automate certain things. What I've found over time is that I'm constantly stealing code from one script to use in another. Most of the time the syntax is even identical. I really should automate these snippets into full blown functions. I also think that it's time for me to make some tools for use by our helpdesk. We have a little command line batch file that predates me and is pretty popular within the department. So, for my first function, I'm going to create an uptime function, but I'm going to tie in a bunch of other handy information, too.

From the video, I gathered that [CmdletBinding()] is the cat's meow, and I can now confirm this. Using the Cmdletbinding tag allows me to use Write-Debug and Write-Verbose within my scripts, and then use -verbose and -debug options while calling the function to get that info (among a lot of other things).

Here's what I've come up with so far:

function Get-PCInfo {
  Lists a number of useful pieces of information from a computer
  Gets the following information:
  Logged on User
  CPU Usage
  Memory Usage
  C Drive Free Space
  Get-ComputerProperties <ComputerName>
  .PARAMETER computername
  The computer name to query. Just one.
      HelpMessage='What computer name would you like to target?')]


  process {

    write-verbose "Beginning process loop"

    foreach ($computer in $computername) {
      Write-Verbose "Processing $computer"
      # use $computer to target a single computer

      #Ping Test
      $PingTest = test-connection $computer -quiet
      Write-Verbose "Ping Test Successful"

      If ($PingTest -eq $true){
          #Get Logged On User
          $LoggedOnUser = (Get-WMIObject -ComputerName $Computer -class Win32_ComputerSystem | select username).username

          #Get Uptime
          $lastboottime = (Get-WmiObject -Class Win32_OperatingSystem -computername $computer).LastBootUpTime
          $sysuptime = (Get-Date) – [System.Management.ManagementDateTimeconverter]::ToDateTime($lastboottime) 
          $Uptime = ($sysuptime.days).ToString() + " days, " + ($sysuptime.hours).ToString() + " hours, " + 
            ($sysuptime.minutes).ToString() + " minutes, " + ($sysuptime.seconds).ToString() + " seconds"
          #Get CPU Usage
          $AVGProc = (Get-WmiObject -computername $computer win32_processor | Measure-Object -property LoadPercentage -Average | Select Average).Average

          #Get Memory Usage
          $MemoryUsage = (Get-WMIObject -Class win32_operatingsystem -computername $computer | 
            Select-Object @{Name = "MemoryUsage"; Expression = {“{0:N2}” -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize) }}).MemoryUsage

          #C Drive Free Space
          $CDriveFree = (Get-WMIObject -Class Win32_LogicalDisk -ComputerName $computer | where {$_.DeviceID -Like "C:"} | ForEach-Object {[math]::truncate($_.freespace / 1GB)}).ToString()

          # create an object with your output info
          $InfoItem = New-Object System.Object
          $InfoItem | Add-member -type NoteProperty -Name 'Logged On User' -value $LoggedOnUser
          $InfoItem | Add-member -type NoteProperty -Name 'Uptime' -value $Uptime
          $InfoItem | Add-member -type NoteProperty -Name 'CPU Usage (Load Percentage)' -value $AVGProc
          $InfoItem | Add-member -type NoteProperty -Name 'MemoryUsage (Percent)' -value $MemoryUsage
          $InfoItem | Add-member -type NoteProperty -Name 'C Drive Free (GB)' -value $CDriveFree
          #Display the Info
      } #End If
      Else {
        Write-Host "Unable to Ping Host"
      } #End Else
    } #End Foreach
  } #End Process
} #End Function


  1. Very nice script! I do have one critique : Write-Host "Unable to Ping Host" would be better as write-verbose "Unable to Ping Host".
    That keeps the primary output as an object that you can use in other ways by pipelining the output to another function to make for example an HTML report or whatever.
    Don likes to say " God kills a puppy every time you use write-host"

  2. I know.... I felt that I could make the case this way: I would rather my helpdesk people know why the script didn't work right off the bat without having to rerun with -verbose.

    Work from home theory is fast gaining popularity because of the freedom and flexibility that comes with it. Since one is not bound by fixed working hours, they can schedule their work at the time when they feel most productive and convenient to them. Women & Men benefit a lot from this concept of work since they can balance their home and work perfectly. People mostly find that in this situation, their productivity is higher and stress levels lower. Those who like isolation and a tranquil work environment also tend to prefer this way of working. Today, with the kind of communication networks available, millions of people worldwide are considering this option.

    Women & Men who want to be independent but cannot afford to leave their responsibilities at home aside will benefit a lot from this concept of work. It makes it easier to maintain a healthy balance between home and work. The family doesn't get neglected and you can get your work done too. You can thus effectively juggle home responsibilities with your career. Working from home is definitely a viable option but it also needs a lot of hard work and discipline. You have to make a time schedule for yourself and stick to it. There will be a time frame of course for any job you take up and you have to fulfill that project within that time frame.

    There are many things that can be done working from home. A few of them is listed below that will give you a general idea about the benefits of this concept.

    This is the most common and highly preferred job that Women & Men like doing. Since in today's competitive world both the parents have to work they need a secure place to leave behind their children who will take care of them and parents can also relax without being worried all the time. In this job you don't require any degree or qualifications. You only have to know how to take care of children. Parents are happy to pay handsome salary and you can also earn a lot without putting too much of an effort.

    For those who have a garden or an open space at your disposal and are also interested in gardening can go for this method of earning money. If given proper time and efforts nursery business can flourish very well and you will earn handsomely. But just as all jobs establishing it will be a bit difficult but the end results are outstanding.

    Freelance can be in different wings. Either you can be a freelance reporter or a freelance photographer. You can also do designing or be in the advertising field doing project on your own. Being independent and working independently will depend on your field of work and the availability of its worth in the market. If you like doing jewellery designing you can do that at home totally independently. You can also work on freelancing as a marketing executive working from home. Wanna know more, email us on and we will send you information on how you can actually work as a marketing freelancer.

    Internet related work
    This is a very vast field and here sky is the limit. All you need is a computer and Internet facility. Whatever field you are into work at home is perfect match in the software field. You can match your time according to your convenience and complete whatever projects you get. To learn more about how to work from home, contact us today on workfromhome.otr214423@gmail.comand our team will get you started on some excellent work from home projects.

    Diet food
    Since now a days Women & Men are more conscious of the food that they eat hence they prefer to have homemade low cal food and if you can start supplying low cal food to various offices then it will be a very good source of income and not too much of efforts. You can hire a few ladies who will help you out and this can be a good business.

    Thus think over this concept and go ahead.