0

This may sound like a stupid question, but I am trying to separate the values in a variable so that I can cross compare them with another variable to decide what to do within an if statement.

Basically, I want to take the beginning letter of a users username, whatever letter that is, will then be compared to both variable to decide what action to take. So for example if the username is "Josh" the message "Home2" should appear. I'm not sure whether what I'm trying to achieve is possible but any help is appreciated.

$UserName = $env:username
$HomeDriveLetterAK = "\\charlie\home_A-K\$Username" 
$HomeDriveLetterAK = "\\charlie\home_L-Z\$Username"
$Home1 = "A, B, C, D, E, F"
$Home2 = "H, I, J, K, L, M"

If ($username.StartsWith($Home1, 1)) 
{
[System.Windows.Forms.MessageBox]::Show("Home1" , "Status" , 'OK', 'error')
}
ElseIf ($username.StartsWith($Home2, 1))
{
[System.Windows.Forms.MessageBox]::Show("Home2" , "Status" , 'OK', 'error')
}

2 Answers 2

1

Alternatively, you can use a Switch:

$username = "John"

Switch -Wildcard ( $username[0] )
{
 '[A-F]' { [System.Windows.Forms.MessageBox]::Show("Home1" , "Status" , 'OK', 'error') }
 '[G-M]' { [System.Windows.Forms.MessageBox]::Show("Home2" , "Status" , 'OK', 'error') }
 '[N-S]' { [System.Windows.Forms.MessageBox]::Show("Home3" , "Status" , 'OK', 'error') }
 '[T-Z]' { [System.Windows.Forms.MessageBox]::Show("Home4" , "Status" , 'OK', 'error') }
 Default { Write-Output 'Unable to determine "Home" for this user.'}
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think I like this better than my solution.
0

First, make $Home1 & $Home2 arrays, not CSV strings. I'll make parsing everything a lot easier. Then use the ToCharArray() method on the String object that is $username to get the first character, and the -contains operator to compare.

$Home1 = ("A","B","C","D","E","F")
$Home2 = ("H","I","J","K","L","M")
$FirstLetter = $username.ToCharArray()[0];
if ($Home1 -contains $FirstLetter) {
    [System.Windows.Forms.MessageBox]::Show("Home1" , "Status" , 'OK', 'error');
} elseif ($Home2 -contains $FirstLetter) {
    [System.Windows.Forms.MessageBox]::Show("Home2" , "Status" , 'OK', 'error');
}

BTW, you probably want to fix the variable name in this line too:

$HomeDriveLetterAK = "\\charlie\home_L-Z\$Username"

1 Comment

You are a genius! Thank you so much, you have no idea how much this is going to help me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.