The Kirkland Coder: February 2012

Thursday, February 23, 2012

PowerShell IsEmptyOrNull?

The current version of PowerShell allows for a quick and easy way to check if a variable is NULL or EMPTY. Just place the variable as the condition of an "IF" statment. Here is an example with an array:

# Set $a as an EMPTY array
$a = @()

# Now test it
if ($a) { Write-Host "has value" }
else { Write-Host "NULL or EMPTY"}

# Set $a as a NULL
$a = $null

# Now test it
if ($a) { Write-Host "has value" }
else { Write-Host "NULL or EMPTY"}

The output is:

NULL or EMPTY
NULL or EMPTY

There you have it. I tend to use beacuse it looks clean, but as I like to say, "Programming is an Art, and there are a lot of crappy painters out there".

Wednesday, February 22, 2012

Check if Running As Administrator

Have you ever had a script that requires it be run in “Run As Administrator” mode and needed a function to check that? When I run into this I use the following function:
function Confirm-RunningAsAdministrator
{
<# 
.SYNOPSIS 
This function will return a bool, "True" if running as administrator,
"False" if not.
  
.DESCRIPTION 
You can use this script to check is you are currently running as
administrator. It is best used when your script needs to verify
that this is the case.
  
.EXAMPLE 
    if (Confirm-RunningAsAdministrator)
    {
        Write-Host "Running as an administrator."
    }
    else
    {
        Write-Host "NOT running as an administrator."
    }

    ----------------------------------------------------------- 
    If running as an administrator, this would produce: 
      
Running as an administrator. 
  
.INPUTS 
None. 
  
.OUTPUTS 
[bool] - "True" if running as administrator, "False" if not. 
  
.NOTES 
Original Function name: Confirm-RunningAsAdministrator.ps1 
Original Author: Norman Skinner 
Original Created on: 12/05/2012 

HISTORY:
    ===========#================#=========#============================
    Date       | User           | Version | Description
    -----------+----------------+---------+----------------------------
    12/05/2011 | Norman Skinner | 1.0.0.0 | Created script
    -----------+----------------+---------+----------------------------
               |                |         |
    -----------+----------------+---------+----------------------------
#> 
    $WinIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $currentPrincipal = New-Object Security.Principal.WindowsPrincipal($WinIdentity)
    $AdministratorRole =  [Security.Principal.WindowsBuiltInRole]::Administrator 
    return $currentPrincipal.IsInRole($AdministratorRole)
}

Tuesday, February 21, 2012

My Delimiters

When I split a string, I prefer to use a character array for my delimiters. It is handy when you have users that tend to use several different types, and not always consistently. But you should be warned that it might need to be edited when using it with CSV files. So here is the declaration I use:

[char[]]$Delimiters = @(';', ',', "`t")

So this works well with the "Split" command. For example:

[char[]]$Delimiters = @(';', ',', "`t")
[string]$String = "One,Two;Three"
[array]$NewArray = $String.Split($Delimiters, [StringSplitOptions]'RemoveEmptyEntries')
Write-Host "The String:"
$String
Write-Host "The New Array:"
$NewArray

Would produce the following output:

The String:
One,Two;Three
The New Array:
One
Two
Three

Write-NoteStart

Once in a while I have to output information from a script that will say what I am doing and then if it completed or failed. In most cases it would look horrible on the screen. Like so:

Checking network connection...completed.
Checking file...completed.
Writing network information to file...completed.

This bugged me to no end; so I wrote the “Write-NoteStart” function to make it easier for me to sleep at night. When using this function the output looks more like this:

Checking network connection.............completed.
Checking file...........................completed.
Writing network information to file.....completed.

Here is the function:

function Write-NoteStart
{
<#
.SYNOPSIS
This function will place periods after writing a string and not write a new line.

.DESCRIPTION
This script is used to produce dots/periods after a given string for aligning
results. You can adjust the position it should add dots up to.

.EXAMPLE
    Write-NoteStart "Checking status" -DotTo 40
    Write-Host "completed."
    Write-NoteStart "Checking your connection" -DotTo 40
    Write-Host "completed."
    -----------------------------------------------------------
    This would produce:
    
Checking status.........................completed.
Checking your connection................completed.

.INPUTS
A string and an int.


.OUTPUTS
Write-Host to the screen with your string followed by periods.

.NOTES
Original Function name: Write-NoteStart.ps1
Original Author: Norman Skinner
Original Created on: 02/01/2012
Version: 1.0.0.0

#>
    param (
        [string]
        # The string for the start of the line.
        $Note = "No data",
        [int]
        # What line position to run dots to.
        $DotTo = 60
    )
    if ($Note.Length -lt $DotTo)
    {
        Write-Host $Note -NoNewline
        for ($i = $Note.Length;$i -lt $DotTo; $i++)
        {
            Write-Host "." -NoNewline
        }
    }
    else
    {
        Write-Host $Note
    }
}


Sunday, February 19, 2012

PowerShell: Try, Catch, and Finally

This is the example I like to refer to for my PowerShell try/catch/finally blocks. 

###---------------------------------------------
### A try/catch/finally example.
###---------------------------------------------
try
{
    Write-Host "Try this."
    $Result = 1/$Zero
}
catch [System.DivideByZeroException]
{
    Write-Host "Caught divid by zero exception."
}

catch [System.SystemException]
{
    # This catch will catch every thing else.
    Write-Host "Caught base exception."
}
finally
{
    Write-Host "Finally this."
}


Why start now?

Why after so many years would I start to blog now? I am mainly doing it for myself. Throughout the years I have collected tidbits of knowledge that I would like to keep track of. Sure, One Note does a fairly good job at helping me keep track of most of it. But I talk to a lot of new scripters, hackers, and programmers that ask questions I have had to answer for myself through sometimes a long process. Sometimes I would find it quick. Other times I would have to wade through long definitions with way too much information for a small answer. So that is the other reason I am starting this up.

Please do not get me wrong, I am no expert. I am a programmer who’s greatest love after his wife and child, is to code and learn new coding skills. If others find some of my post useful, then that is great. If not, then all the more knowledge for me.