Posted
Comments None

After a few weeks’ break for Christmas, I’ve returned to blogging and tonight we’re looking at a couple quick rules to help the reuse of our code.

There are more proper and less proper ways to do things in many programming languages. Some have very clear conventions to follow, and some seem to be the Wild West of programming tricks and shortcuts. The former are nice because you can generally tell what something does and whether it will work by looking at it, and the latter are good because you can get results very quickly, and you will feel like you know kung-fu. (Hint: pick legible syntax over kung-fu whenever possible… even when you are not going to re-use your code, you will have an easier time retaining knowledge if you are not using “tricks” to get your task done).

Below I will cover a few good hygiene habits that will help your work stand the test of time, while also exercising and deepening your understanding of the ‘Shell.

One of the easiest shortcuts PowerShell provides are CMDlet aliases. These shortened or alternative names are nice for their brevity and familiarity with other shell environments. Two of the most common aliases are “dir” and “ls.” Both are used in lieu of Get-ChildItem and are likely familiar to DOS and Unix users respectively. Aliases are invaluable in the console window, but always prefer typing out the full command name in saved scripts. Yes, the next admin to come along can simply open up a console and type “Get-Alias sujb” but it is better if you just used “Suspend-Job” in your saved script in the first place so she does not have to. I would especially avoid the aliases “%” (ForEach-Object) and “?” (Where-Object) in saved scripts, as the novice PowerShell user may very easily mistake them for wildcards or some strange operators. Rather than confounding them, we should be enlightening and gently guiding our acolyte coworkers, helping them in their own journeys in the ‘Shell.

We must make a similar consideration when it comes to type declarations. When you create functions for re-use, type constrain and or validate your parameters. That means that your function will demand that the parameters it receives are of the exact type of data that it needs to execute. Sometimes data can be ambiguous, and errors or, worse, undetected strange behavior, can occur. PowerShell data types are declared by the type name in square brackets “[ ]” before the data or variable, e.g., “[string]$x”.

For an example of the importance of type constraints, enter the following lines individually in a console window, followed by enter, and see what is returned.

2
"2"
2 + 2
"2" + "2"
"2" + 2
2 + "2"

Does it make sense what is happening? When you use quotes, PowerShell interprets the character 2 as a string, rather than an integer. When PowerShell adds strings, it appends the second one to the first. When it adds integers, it is doing math. When mix up the line with quotes and no quotes, PS type casts the second piece of data to match the first, so that it can perform the appropriate kind of addition.

PowerShell does not enforce strong typing, but that does not mean you cannot enforce strong typing in your functions. What does it mean to enforce strong typing? It simply means we declare the type of data for our parameters within the function. Let’s make weakly typed function of the mess above.

Function AddMe ($number1,$number2) {
Write-Output ($number1 + $number2)
}

Now if you iterate over the combinations above as parameters, you get the same results.

AddMe "2" 2
22
AddMe 2 "2"
4

Now let’s type constrain the function and try again. As we are clearly looking to do arithmetic, we’ll demand that the parameters are integers. Now, even when they are implicitly specified as strings, the function will cast them as integers and return the correct value.

Function Addme ([int]$number1,[int]$number2) {
Write-Output ($number1 + $number2)
}
AddMe "2" 2
4
AddMe 2 "2"
4
AddMe "2" "2"
4

See how nice and consistent that is? Learning about the specific data types silently sliding down the pipeline is an important step in our mastery of PowerShell, and requiring data of the appropriate type can harden our scripts against human error.

Author

Posted
Comments None

PowerShell 5 includes Get-Clipboard, a handy CMDlet that had previously been up to individual users to add to their PS Profile. In my own version I added the capability to parse a region copied directly from an excel spread sheet, including column headers as property names. This serves two purposes: My coworkers were more likely to use it if they can use Excel; I am more likely to use Excel if I can use PowerShell.

To use it, select a region in Excel you wish to get and copy it. If you grabbed the column headers along with the rest of the data, just enter

Get-MdtClipBoard -SpreadSheet

If you do not have access to the column headers in your selection, you can specify them manually such as

Get-MdtClipBoard -SpreadSheet -Headers "Column1Title","Column2Title","Column3Title"

To do: re-format this as a wrapper for the PS 5 CMDlet, including the additional format types (image, audio, FileDropList).

Author

Posted
Comments None

When your computers in a corporate network are encrypted with BitLocker, you can optionally have the recovery information uploaded to Active Directory. There aren’t really any major drawbacks to doing this, as in most cases if an attacker has elevated access to AD, he can simply log into an encrypted workstation without bothering with BitLocker and your workstation hard drives are not the greatest of your problems.

The BL info is stored in an odd manner, which can make scripting retrieval a little difficult. I took the opportunity to create the following command, trying to meet these objectives:

  1. It needs to be able to verify the computer we’re looking up
  2. It should be able to accept pipeline input for batch jobs and utilize the Begin section of the function to perform any initial searches that are used again for each object
  3. It should also be able to look up the password/computer by recovery key, for when Joe Exec was given a loaner and doesn’t know the computer name and stuck a thumb drive in and tried to boot (or tried to dock it, or any of the other myriad cases where BitLocker starts acting up)
  4. It should default to NOT retrieve the password, but do so optionally
  5. Let’s use Comment Based Help for some simple documentation

This is what I came up with:

I’ve seen alternate methods of looking them up, where instead of returning all “msFVE-RecoveryInformation” objects, you use the computer’s Distinguished Name as a SearchBase. I may go back and optimize this, but I’ve been satisfied with the performance on this method. Let me know if you have any thoughts on the matter.

Author

Posted
Comments None

For a PowerShell beginner, I would make the following suggestions:

  1. Use the console, not the ISE
  2. Change the font to Consolas
  3. Use Windows 10 or at least upgrade to PowerShell 5

Additionally, the first thing you’ll need to do is set the execution policy on your machine. You probably want to start out with “RemoteSigned.” To change it, run a new instance of PowerShell as Administrator. Then execute:

Set-ExecutionPolicy RemoteSigned

It will ask you to confirm. Note that this is a system-wide setting. If you start an un-elevated instance of PowerShell, and make the change in your Administrator PowerShell instance, you can see the setting change in your normal window by running

Get-ExecutionPolicy

For nearly any “Set” command, there is a corresponding “Get” command. Learn this well as you start out: “Get it before you set it.”

Now, we need to see if a profile script exists yet on this machine. There is a built-in global variable for the location of your profile script, $profile. To see if one exists, run

Test-Path $profile

Either true or false will be returned. If true was returned, skip the next part or you’ll overwrite any changes you’ve made previously. Otherwise, go ahead and create a profile script now with

New-Item -path $profile -type file -force

When you add the -force switch to New-Item, it creates any missing directories in the path as well as the final item. Now, you can edit the script graphially with

notepad $profile

You might consider adding some aliases or a function to customize your command prompt.

Author

Posted
Comments None

At work, I’ll often fire off a few background jobs, and then forget they’re there. If only there were an easy way to remind myself I have a job running, and to check if it is complete or not.

Okay, so I would not have led in that way if I did not have a solution to propose. Like any good shell, PowerShell is highly customizable, letting us set the command prompt to basically whatever we want. All we have to do is create a function called “prompt” and stick it in our profile script.

Here’s mine:

Function Prompt {
	$Jobs = Get-Job
	IF ($Jobs) {
		$RunningJobCount = $jobs | ?{$_.State -eq "Running"} | Measure-Object | select-object -expandproperty Count
		$OtherJobCount = $jobs | ?{$_.State -notin "Running","Completed"} | Measure-Object | select-object -expandproperty Count
		$CompletedJobCount = $jobs | ?{$_.State -eq "Completed"} | Measure-Object | select-object -expandproperty Count
		Write-host "[J $($RunningJobCount):$($OtherJobCount):$($CompletedJobCount)] " -NoNewLine
	}
	$Loc = Get-Location
	$path = $Loc.Path
	$color = $global:host.ui.rawui.foregroundcolor
	Switch ($Loc.Provider.Name) {
		{$_ -eq "FileSystem"} {
			$Color = "Green"
			IF ($Path -match "^(Microsoft\.PowerShell\.Core\\FileSystem\:\:)") {
				$Path = $path -replace "^(Microsoft\.PowerShell\.Core\\FileSystem\:\:)"
			}
		}
		{$_ -eq "CMSite"} {
			$color = "Cyan"
		}
		{$_ -eq "Registry"} {
			$color = "Red"
		}
		{$_ -eq "ActiveDirectory"} {
			$color = "Magenta"
		}
	}
	Write-Host "$($path) " -nonewline -ForegroundColor $color
	Write-host ">" -NonewLine -ForegroundColor Yellow
	Write-Output " "
}

This provides several things. First, it looks for background jobs and displays the count before the prompt. If I issue a command like

Start-Job {Start-Sleep 5}

it will display [J 1:0:0] before the prompt. The first digit indicates the number of running jobs, the last digit indicates completed jobs, and the middle digit is for jobs that are neither running nor complete—usually, failed jobs. So every time I hit “enter”, or after running a command, the prompt refreshes and displays updated information. Once all the jobs are in the completed column, I can simply run

Remove-Job *

to clear them out, or use Receive-Job if they need to first be received. When they are all cleared, that portion of the prompt disappears.

The other thing this prompt script does is colorize the location based on PSProvider and remove the junk before UNC paths. You can see above in the Switch statement that if I am in ActiveDirectory, the path is magenta, if I am in Configuration Manager, it is cyan, if I am in the registry, it is red. It defaults to green for the file system.

To illustrate, I browsed to the UNC path of my own admin share. It takes our prompt from looking like this:

To this:

Much easier on the eyes, wouldn’t you agree? Even with the transient jobs information, it is still far shorter. Of course, there are many other kinds of information you could display. You could provide the status of BitsTransfer jobs, CPU utilization, the time of day… anything. So get creative and spruce up that shell a little more.

You’re probably reading this because you work in an MS shop like me. If that’s where we live and work, we really ought to take a few minutes to spruce up the place!

Author

← Older Newer →