Thursday, January 5, 2012

Powershell (v2) - Initializing Variables at Usage

Lately I have been writing more well-documented/commented code as a matter of courtesy and practicality.  The courtesy is out of consideration for other who may not know Powershell (or the objects) as well as I do. By reading the comments they can really get a feel for what the script does and why it does it that way.  Practically speaking, comments help to remind me when I can't recall why I did that really weird hack.  It also helps me articulate the basic flow of the script.  In one recent case, where I used the following two commands right off the bat,
# Clear screen
cls;

# Initialize $path variable in Start-Transcript call
Start-Transcript -Path ($path = "C:\users\will\documents\data") -ChildPath "transcript.txt";
By declaring $path in the -Path arguments as ($path = "C:\users\will\documents\data") it allows me to set the Start-Transcript -Path output location, and, intialize the $path variable all at once. This way, when I start my transcript, I don't have poorly organized regions and my variable is configured right off the bat. In fuller usage, my script looks like this now.  I have highlighted the intialized variable in red below.
# Clear screen
cls;

# Initialize $path variable in Start-Transcript call
Start-Transcript -Path (Join-Path -Path ($path = "C:\users\will\documents\data") -ChildPath "transcript.txt");

#region variables

$variables = something;
$othervariables = something else;

#endregion variables

#region functions

function Write-DateTime {
return (Get-Date).ToString("yyyyMMdd hh:mm:ss");
}
Set-Alias -Name wdt -Value "Write-DateTime";

#endregion functions

#region script body

# Output status to host
Write-Output "$(wdt): Doing some work.";
Do-Work;

End-Transcript

#endregion script body

0 comments:

Post a Comment