Parse Computer Name for Project Name

On some days… I just want full on project redo. It’s amazing how many decisions you’d make differently in those initial project meetings, once you’ve begun delivering results. Why, oh why, did we allow for hyphens in project names!?

Here’s my problem and how I fixed it. Let’s say we have four projects and their names are those listed below.

TRAILKING
ARF-SOIL
INTERALX
SECTRAIN

Now, let’s consider that we use these as our host names, or computer names; however, we append some information onto these four strings. For our terminal hosts, we’ll add -TH-01 and for our compute hosts, we add -CH-01. Therefore, we’d have two computer names for each project. For the TRAILKING and ARF-SOIL projects, we’d have the following four computers.

TRAILKING-TH-01, TRAILKING-CH-01, ARF-SOIL-TH-01, and ARF-SOIL-CH-01

Now, let’s consider we need to parse these computer names later on to help determine the project name. Can you see the problem, because I didn’t initially. The little extra coding I had to do is why we’re here today. You know, someone might need it one day, too.

If I split the full computer name at the first hyphen, and assume index 0 is the project name, then the ARF-SOIL project, is only going to be the ARF project. That’s not going to work. Take a look at my one-off solution. I hate these, but sometimes, it’s just too late to fix a project problem. Hindsight, man.

$String1 = 'TRAILKING-TH-01'
$String2 = 'TRAILKING-CH-01'
$String3 = 'ARF-SOIL-TH-01'
$String4 = 'ARF-SOIL-CH-01'
$String5 = '-ARF-SOIL-CH-01'

$String = Get-Random -InputObject $String1,$String2,$String3,$String4,$String5
$TempArray = $String.Split('-')

If ($TempArray.Count -eq 3) {
    $Project = $TempArray[0]

} ElseIf ($TempArray.Count -eq 4) {
    $Project = "$($TempArray[0])-$($TempArray[1])"

} Else {
    Write-Warning -Message "Unable to properly parse computer name: $String."
    Write-Verbose -Message "$BlockLocation Unable to properly parse computer name: $String."
}

$Project

As we repeatedly run this code in the ISE, or Visual Code, it’ll properly parse our computer names. If the string is split at its hyphens, and we’re left with three parts (TRAILKING, CH, and 01), then we know the first part is the project name. If the string is split at its hyphens, and we’re left with four parts (ARF, SOIL, TH, and 01), then we know the first two parts, combined with a hyphen, is the project name.

That was it. Happy Thanksgiving!

Leave a Reply

Your email address will not be published.