0

I am trying to assign the output of an if statement to a variable, I am New To Powershell and don't have a firm grasp of it, Any Help would be Great. Thanks!

$Var = if ($Title -eq "Service Route Rep"){
$Department = "Operations"}elseif ($Title -eq "AP Clerk"){
$Department = "Finance"}elseif($Title -eq "Product Development Manager")
$Department = "Operations"}      

$Title = "Service Route Rep"
$Department = "$var"

$user.department = "$Department" 

and i receive the error

Set-ADUser : replace
At line:1 char:1
+ Set-ADUser -instance $user
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [Set-ADUser], 
ADInvalidOperationException
+ FullyQualifiedErrorId : 
ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.SetADUser

2 Answers 2

2

For another approach, especially if you have more items to decode.

$Var = Switch ($Title){ 
           'Service Route Rep'           { 'Operations' }
           'AP Clerk'                    { 'Finance'    }
           'Product Development Manager' { 'Operations' } 
           Default                 {'Title Not in list!'}
         }

HTH

Sign up to request clarification or add additional context in comments.

Comments

2

In this scenario, you are trying to set $Var to a value based on a conditional expression. To do so, you must evaluate the expression, and return the desired output:

$Var = if ($Title -eq 'Service Route Rep'){ 'Operations' }
        elseif ($Title -eq 'AP Clerk'){ 'Finance' }
        elseif ($Title -eq 'Product Development Manager') { 'Operations' } 

In your code, you are evaluating the expression, but set $Department with the desired department value. This means that the expression itself is returning $null. Then, you take the value of $Department, and overwrite it in the line $Department = "$var", which is setting $Department to $null.

I would recommend looking at using a HashTable in this case. It is a very common pattern, as it is far more readable.

$TitleMap = @{}
$TitleMap.Add('Service Route Rep', 'Operations')
$TitleMap.Add('AP Clerk', 'Finance')
$TitleMap.Add('Product Development Manager', 'Operations')

$Title = "Service Route Rep"
$Department = $TitleMap[$Title]

You will also may note that I have used single vs. double quotes, which you can read more about here.

1 Comment

For added readability I suggest to combine the hashtable creation and the assignment of its members: $TitleMap = @{ 'Service Route Rep' = 'Operations'; 'AP Clerk' = 'Finance'; 'Product Development Manager' = 'Operations' }. You can replace the ; by line feed, I just can't write it as such in the comment.

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.