Goodbye fingernails: I’m going to be speaking in ten days

Aside Posted on Updated on

You know, like in front of people.

Who will be looking at me and listening to the words I say.

What have I gotten myself into?!

[PSCustomObject] Need not apply;How PowerShell 2.0 handles objects

Posted on Updated on

Today at a client I had to export some Exchange Information from a one of their Exchange boxes. A simple task, but I kept experiencing some strange issues when I would run my script in PowerShell on the Exchange servers.

The only data I needed was RecipientType, LastLoggedOn and some other similar info, which is also easy to get. It needed to be extracted from Exchange and made ready for assimilation into a larger spreadsheet, so exporting as a Custom Object of some form would be the way to go.

I quickly came up which this script, which should have been more than up to the task. However, the output was very bizarre.

$Array = New-Object -TypeName System.Collections.ArrayList

Function Get-MarkInfo {
   ForEach ($user in $users){
      $mbx = Get-Mailbox $user
      $mbxstat = Get-MailboxStatistics $user
      [PSCustomObject]$obj=@{Name=$user;RecipientType=$mbx.RecipientType;LastLoggedOnUserAccount=$mbxstat.LastLoggedOnUserAccount;LastLogOffTime=$mbxstat.LastLogOffTime;LastLogonTime=$mbxstat.LastLogonTime}
      $Array.Add($obj) | Out-Null
   }
   $Array | export-csv C:\temp\EmailExport.Csv
}

This shouldn’t export these sorts of things

PSObjectWeirdness
Oh no…why is my glorious [PSCustomObject] master race appearing as a hash table? No one asked for key:value pairs!

Read the rest of this entry »

September Atlanta PowerShell Users Group!

Posted on Updated on

Come see me speak on my home turf!

https://www.eventbrite.com/e/atlanta-powershell-user-group-september-meeting-tickets-13037013057

 

Session Topic

Stephen Owen of iVision will give a review of the best new features in PowerShell version 5, including what’s new in the recent WMF and Resource Kits.  He will cover usages cases for some interesting new cmdlettes like Convert-FromString, and also do an overview with examples of some of the recent DSC Goodness released


Meeting Location

iVision, a long time community sponsor,  has graciously agreed to allow to hold our meeting at their offices in Midtown Atlanta.

1430 West Peachtree Street NW
Suite 425
Atlanta, GA 30309 – See more at: http://ivision.com/company/contact-us/#sthash.TTyjn77t.dpuf
1430 West Peachtree Street NW
Suite 425
Atlanta, GA 30309 – See more at: http://ivision.com/company/contact-us/#sthash.TTyjn77t.dpuf
1430 West Peachtree Street NW
Suite 425
Atlanta, GA 30309 – See more at: http://ivision.com/company/contact-us/#sthash.TTyjn77t.dpuf

Directions: http://ivision.com/company/directions
Parking: The venue does not have free parking. It should cost you about $5 to park.

iVision - Engineer the Future, Today

Have questions about Atlanta PowerShell User Group September Meeting?Contact Atlanta PowerShell User Group

One Inch of Power: Get-Battery info!

Posted on

This ‘One Inch of Power’ is a new piece I want to start doing, cramming a lot of functionality into an inch or less of PowerShell code.

Most of these will be ten lines or less, and do something useful. So, here we go!

Ever feel like your battery is letting you down? Thanks to modern Battery WMI compatibility, we can get a battery to report to us its supposed capacity, and then dig through various WMI classes to find out if the battery is really performing as well as it should be.

Remember that most laptop batteries are only going to perform at full power for a year worth of charging cycles, after which you’ll get reduced performance. My battery on my laptop was starting to slouch, so I decided to write this up.

You should run this code once while charging, and then rerun this function to see what the actual output is of your battery.

Function Get-BatteryStats{
$batteryStatus = gwmi batterystatus -name root\wmi
$batterystats  = gwmi win32_portablebattery
$missing = [Math]::Round(((1-($batteryStatus.RemainingCapacity[0]/$batterystats.DesignCapacity))*100), 2)

$batteryReport = [pscustomobject]@{'Charging'=$batteryStatus.Charging[0];'PluggedIn'=$batteryStatus.PowerOnline[0];'ListedCapacity'=$batterystats.DesignCapacity;'ActualCapacity'=$batteryStatus.RemainingCapacity[0];'Percent Remaining'=[Math]::Round((($batteryStatus.RemainingCapacity[0]/$batterystats.DesignCapacity)*100),2);MissingCapacity=if ([math]::Sign($missing) -eq '-1'){"ReRunOnBattery"}ELSE{$missing}}
$batteryReport | ft 

if ($batteryReport.ActualCapacity -gt $batteryReport.ListedCapacity){Write-Warning "Battery Reports greater than possible capacity, try rerunning this code when unit is not plugged in to AC power"}
if ($batteryReport.MissingCapacity -eq 'ReRunOnBattery'){Write-Warning "Can't obtain missing power, rerun while unit is not plugged in to AC power"}ELSE{"You're missing out on $missing percent of your battery, time to replace!"}
}
Time to buy a new battery!
Time to buy a new battery!

Working with SQL using PowerShell

Posted on

I’ve seen a lot of people ask about how to do this, so I thought I’d provide some information on the matter. Previously I had a project in which I had to pull a ton of data from an extended SCCM database and massage it before importing into MDT to setup location settings and things like that for an automated zero-touch install with very granular configuration settings determined based on workstation location.

I had to learn this the hard way, but it saved me weeks worth of painstakingly combing through records, and was also pretty fun once I dug into the guts, and was able to get old customized SQL records to jive with the Microsoft Deployment Toolkit Database!  It’s fun to teach machines to talk to each other!

Because many PowerShell enthusiasts may not be familiar with SQL, in this post I’ll walk through the steps to install SQL, setup a database and then create a table, before digging into how to directly influence SQL from the PowerShell prompt. Read the rest of this entry »

Adding -WhatIf Support to your scripts the right way, and how you shouldn’t do it

Posted on

If you are a prudent sysadmin or consultant, you probably rely on using the -WhatIf command before ever running any serious PowerShell cmdlets in your environment. Since we love it so much, shouldn’t we build this very same courtesy into our tools that others will use?

Before I learned how easy it is to add -WhatIf support to my Functions and Scripts, I’d often write something ugly like this:


Function Do-Stuff{

    param([switch]$WhatIf)

    ForEach($item in $args){
        if ($WhatIf){
            Write-host "WhatIf: Would be performing `$Action on $item" -ForegroundColor Cyan
            }
            ELSE
           {
           "Actually performing `$Action on $item"
            }
     }

}

Aside: This is amended from an actual script in production that I’ve created. It was made a LONG time ago.

Yep, it’s not very nice and I’m deeply, deeply ashamed. Read the rest of this entry »

PowerShelling FizzBuzz

Posted on Updated on

I recently learned about the FizzBuzz test, which is meant to help interviewers determine if a prospective hire can understand the fundamental logic needed to program.

The premise is this:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

I thought this sounded like a fun challenge, so I decided to try my hand at it.

At first, this seemed deceptively easy. Set up a For-Each loop with $num incrementing. If the number is divisibile by 3, then performing a modulo operation will result in a remainder of zero.

Perform the same if the number is divisble by five. Then write either Fizz or Buzz based on which was true.

However, if the number is divisible by BOTH, write out Fizzbuzz instead, and then proceed. The problem here was catching for the AND condition, very similar to a binary math operation. I eventually discarded my ForEach and instead used a While Loop, as the behavior of Continue and Break within a For loop lead to undesired outcomes.

Here is my answer:

Function Start-FizzBuzz {
$num = 0
while ($num -lt 100) { #-lt is shorthand for LessThan 
    $fizz = $false
    $buzz = $false
    
   
    $num++
    if (($num % 3) -eq 0) {$fizz = $true;}
    if (($num % 5) -eq 0) {$buzz = $true;}


    if (($fizz) -and ($buzz)){
        "FIZZBUZZ"
        continue 
        #continue tells PowerShell to continue on to the next object in series, and gets around a situation where we'd get output of FIZZ, BUZZ, FIZZBUZZ
        }
    if ($fizz){
              "FIZZ"
               CONTINUE
               }
    if ($buzz){
               "BUZZ"
               CONTINUE
               }
    
    $num #if we didn't write Fizz, Buzz or FizzBuzz, write the number itself
    }
}