Conditional Logic

PowerShell Tutorial 8: Conditional Logic (if, elseif, else, and switch)


As with other programming languages, PowerShell is a dynamic scripting language. Script code can be executed based on conditions that exist or occur. For example, a script might prompt for user input and run a block of code based on the data supplied by the user. A process or application may stop running, triggering an action within a script. Conditional Logic allows us to write scripts in a complex environment, it adds the intelligence required to create decision-making scripts.

Launch PowerShell and let's get started…

Comparing Data

We are going to compare data using the following PowerShell Comparison and Logical Operators.

Table 1: PowerShell Comparison Operators:

Operator Description
-eq Equal to
-lt Less than
-gt Greater than
-ge Greater than or Eqaul to
-le Less than or equal to
-ne Not equal to


I'm not going to join in the great debate over why these operators where chosen, they exists within PowerShell and must be used. Special note: When comparing text strings, by default PowerShell is not case-sensitive. "TOM" and "tom" would compare "equal to" (-eq). However, you can force PowerShell to compare values based on case-sensitivity. By appending an "i" to the operator, you're telling PowerShell to be "case-insensitive." Appending a "c" forces PowerShell to compare as "case-sensitive."

Examples:
Tom -eq TOM. The result is "True"
Tom -ieq TOM. The result is "True"
Tom -ceq TOM. The result is "False"

Table 2: PowerShell Logical Operators:

Operator Description
-not Not
! Not
-and And
-or Or

Now that we have the table listings of Operators, let's do some examples to show their use and results.

7 -eq 7<enter>

Result is "True"

7 -ne 7<enter>

Result is "False"

7 -lt 10<enter>

Result is "True"

7 -gt 10<enter>

Result is "False"

"Tom" -eq "tOm"<enter>

Result is "True"

"Tom" -ceq "tOm"<enter>

Result is "False"

I'm going to skip the logical operators for now, we'll get back to them in a moment. What's important to understand is each code snippet is providing a result, either True or False. The results are used in the decision-making process within PowerShell scripts.

Conditional Logic

Now that we have results, what do we do with them? We need a way to apply comparison results with conditional logic (the decision-making process). PowerShell supports two logic statements to help out:

  1. if - evaluates a comparison, then either executes or sidesteps code blocks based on the result. if statements require result of the comparison to be True to execute it's associated code block.
  2. switch - Does the same as the if statement with the exception that it can evaluate multiple comparisons, each having the ability to execute code blocks. This is the same as a "select case" or "case" statements in VBScript and other programming languages.

Using the "if" Statement

The if statement syntax:

if (condition) {code block}
elseif (condition) {code block}
else (condition) {code block}

  • condition = an expression that results to a Boolean Value (True or False).
  • code block = what to execute if condition is True.
  • elseif (optional) = test an alternative condition if preceding condition was False.
  • else (optional) = executes it's code block whenever none of the if or elseif statements return a True result.

Let's do a simple script that shows the if statement in action. Copy the code into clogic.ps1 file and save it to the "MyScripts" directory. Run the script: "C:\MyScripts\clogic.ps1<enter>" -or- type ".\clogic.ps1 if you are currently working in the MyScripts directory.

$x = 2 #creates a variable x and assigns 2 as the value
  if ($x -eq 5) {Write-Host "Hello my name is Bob"}
    elseif ($x -eq 4) {Write-Host "Hello, my name is Sue"}
    elseif ($x -eq 2) {Write-Host "Hello, my name is Troy"}
    elseif ($x -gt 1) {Write-Host "Hello, my name is Mary"}
  else {"I have no idea what my name is?"}

The result should be Hello, my name is Troy as the condition ($x -eq 2) resulted in a True value and executed the script block {}. But I purposely threw you a curve ball. Notice that the last elseif statement ($x -gt 1) would also result in a True condition, so why doesn't it's script block get executed? This is by design, once an if statement condition results in a True value the associated script block is executed and PowerShell stops testing subsequent conditions. The way around this is to use a switch statement which we will discuss in this PowerShell training session.

Real-World Example:
Sometimes different Operating Systems use different WMI classes and/or properties. I ran into this difference when attempting to enumerate printers on Windows XP, Windows 2003, and Windows 2000. I used an if statement to test the OS version and based on the version, PowerShell would run the code block associated for each OS. Here's the code I used:

Copy the following code into a .ps1 script file. Name it PrintReport.ps1 and execute the script.

$strComputer = Read-Host "Printer Report – Enter Computer Name"
$OS = Get-WmiObject -Class win32_OperatingSystem -namespace "root\CIMV2" `
-ComputerName $strComputer

# if statement to run code for Windows XP and Windows 2003 Server.
if (($OS.Version -eq "5.1.2600") -or ($OS.Version -eq "5.2.3790"))
{
    write-host "Computer Name: " $strComputer
    #nested if statement
    if ($OS.Version -eq "5.1.2600") {write-host "OS Version: Windows XP"}
    elseif ($OS.Version -eq "5.2.3790") {write-host "OS Version: Windows 2003"}
        $colPrinters = Get-WmiObject -Class win32_Printer -namespace "root\CIMV2" `
        -computerName $strComputer
            foreach ($objPrinter in $colPrinters) {
            write-host "Name: " $objPrinter.Name
            write-host "Description: " $objPrinter.Description
            write-host
            }
}

# if statement to run code for Windows 2000 Server
elseif ($OS.Version -eq "5.0.2195")
{
    write-host "Computer Name: " $strComputer
    write-host "OS Version: Windows 2000 Server"
        $colPrinters = Get-WmiObject -Class win32_PrintJob -namespace "root\CIMV2" `
        -computername $strComputer
        foreach ($objPrinter in $colPrinters) {
        write-host "Name: " $objPrinter.Name
        write-host "Description: " $objPrinter.Description
        write-host
        }
}
# if OS not identified
else {write-host "The OS for: $strComputer is not supported."}
write-host "–END OF REPORT–"

When the script is executed, you are prompted to enter the computer name you wish to enumerate. By adding the "Read-Host" cmdlet, you're now able to enumerate other computers on your network. Pretty cool stuff going on here, let's break it down.

Step 1. $strComputer = Read-Host "Printer Report – Enter Computer Name"
Creates a variable called $strComputer and assigns a value supplied from user input.

Step 2.  $OS = Get-WmiObject -Class win32_OperatingSystem -namespace "root\CIMV2" `
-ComputerName $strComputer

Creates the variable "$OS" and assigns the win32_OperatingSystem class object. Something else to look at. Even though it looks like two lines of code, it's actually one line of code. The "`" escape character means to continue as one line. Used for keeping scripts legible should you run out of space. PowerShell reads the line as:
$OS = Get-WmiObject -Class win32_OperationSystem -namespace "root\CIMV2" -Computername $strComputer

Step 3.  if (($OS.Version -eq "5.1.2600") -or ($OS.Version -eq "5.2.3790"))
Here is where we talk about Logical Operators.

Operator Description
-not Not
! Not
-and And
-or Or

What you need to know. The Not operators -not and ! (both mean NOT) allow you to modify the results of a condition. For example:
if (1 -eq 1) – results in a True value and runs the script block.
if (!(1 -eq 1) – results in a False value and skips the script block.

The -or operator means at least one of the conditions must be True to execute the script block.
For example:
if ((1 -gt 2) -or (2 -gt 1)) – One of the conditions are True so, it's associated script block will execute.

The -and operator means that all conditions must be True to execute the script block.
Example:
if ((1 -ge 1) -and (2 -ge 1)) – Both conditions are True, script block executes.
if ((1 -ge 1) -and (2 -le 1)) – The first condition is True, whereas the second is False. The script block is skipped.

Step 4.  {
    write-host "Computer Name: " $strComputer
    #nested if statement
    if ($OS.Version -eq "5.1.2600") {write-host "OS Version: Windows XP"}
    elseif ($OS.Version -eq "5.2.3790") {write-host "OS Version: Windows 2003"}

        $colPrinters = Get-WmiObject -Class win32_Printer -namespace "root\CIMV2" `
        -computerName $strComputer
            foreach ($objPrinter in $colPrinters) {
            write-host "Name: " $objPrinter.Name
            write-host "Description: " $objPrinter.Description
            write-host
            }
}

In step 3. if one of the conditions are True the script block in step 4. is executed. The script block writes the following information to the screen:

  • The Computer Name
  • The OS Type – Note, in RED, we can nest additional if statements within code blocks. Now you are stating to see how complex PowerShell, as a scripting language, can be.
  • The script block then enumerates the win32_Printer class and sends the requested property information to the screen.
  • Once the block completes, PowerShell skips to Step 8. and writes "–END OF REPORT–" to let the end user know it has completed.

If none of the conditions are True in step 3. PowerShell moves to the next if statement, in this example that would be…

Step 5.  elseif ($OS.Version -eq "5.0.2195")
If this condition results in a True value, the script block in step 6. is executed.

Step 6.  {
    write-host "Computer Name: " $strComputer
    write-host "OS Version: Windows 2000 Server"
        $colPrinters = Get-WmiObject -Class win32_PrintJob -namespace "root\CIMV2" `
        -computername $strComputer
        foreach ($objPrinter in $colPrinters) {
        write-host "Name: " $objPrinter.Name
        write-host "Description: " $objPrinter.Description
        write-host
        }
}

The result of the script block outputs the following information to the screen:

  • Computer Name
  • OS version
  • Requested Property information of the win32_PrintJob class.
  • Once the block completes, PowerShell skips to Step 8. and writes "–END OF REPORT–" to let the end user know it has completed.

If the result in step 5. is False, PowerShell continues reading the script and finds the "else" statement.

Step 7.  else {write-host "The OS for: "$strComputer" is not supported."}
Outputs " The OS is not supported." Step 7. runs when all conditions in the script end with a False value.

Step 8. write-host "–END OF REPORT–"
Let's you know the script has completed.

This example shows just how dynamic our scripts can be, based on conditions that exist in our environment. And how we can write if statements to test those conditions and run script blocks according to the results of those tests.

 

Using the Switch Statement for Multiple Comparisons

Since we can use elseif statements to test multiple conditions, there may come a time when too many additional tests lend to difficult script writing and down-right ugliness. There are other times where you want to test multiple conditions that result in multiple True values and you don't want the script to stop testing when it receives the first True value (as it does with an if statement). The option that allows you to accomplish this is the switch statement. The PowerShell switch statement organizes a collection of tests that are evaluated using the same expression.

The Switch statement syntax:

switch (expression)
{
  (test) {code block}
  value {code block}
  default {code block}
}

  • Test = An evaluated expression.
  • Value =  A value, like a number or text string.
  • Default = Default code block to run if none of the expressions return a True value.

Here is an example from Ed Wilson's PowerShell book: "Windows PowerShell Step by Step." Save the script code as ComputerRoles.ps1 and run the script:

$objWMI = Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2"
"Computer "+ $objWMI.name + " is a: "

switch ($objWMI.domainRole)
  {
  0 {Write-Host "Stand alone workstation"}
  1 {Write-Host "Member workstation"}
  2 {Write-Host "Stand alone server"}
  3 {Write-Host "Member server"}
  4 {Write-Host "Back-up domain controller"}
  5 {Write-Host "Primary domain controller"}
  default {Write-Host "The role can not be determined"}
  }

In this example I used a number value which correlates to the value of the domainrole property within the win32_ComputerSystem WMI class. When the value was returned as True, the script block output the role using the "Write-Host" cmdlet.

Modify the script to prompt user for "Computer Name:"

$strComputer = Read-Host "Enter Computer Name"
$objWMI = Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2" `
  -computername $strComputer

Write-Host "Computer: $strComputer is a:"
switch ($objWMI.domainRole)
  {
  0 {Write-Host "Stand alone workstation"}
  1 {Write-Host "Member workstation"}
  2 {Write-Host "Stand alone server"}
  3 {Write-Host "Member server"}
  4 {Write-Host "Back-up domain controller"}
  5 {Write-Host "Primary domain controller"}
  default {Write-Host "The role can not be determined"}
  }

Now that we can input the $strComputer value, we can run this script on any remote computer in the environment, as long we have local admin rights.

This next example has no real purpose other than demonstrating how the switch statement works using the (test) expression with multiple True value results. Unlike if statements, switch statements continue running when True value matches are found. So it is possible that more than one code block will be executed. Copy and Paste the code into the PowerShell shell. The results should be obvious, test expressions that correctly equal 10 will run:

switch (10)
{
  (1 + 9) {Write-Host "Congratulations, you applied addition correctly"}
  (1 + 10) {Write-Host "This script block better not run"}
  (11 – 1) {Write-Host "Congratulations, you found the difference correctly"}
  (1 – 11) {Write-Host "This script block better not run"}
}

Conditional logic is the foundation for dynamic PowerShell script writing. We successfully demonstrated how we can control the flow of a script base on conditional responses. In the next PowerShell training session we are going to build on what we have learned and introduce Loops, which takes flow control to the next level. See you in the next PowerShell tutorial…

Email This Page To A Friend Email This Page To A Friend 

Comments

Good information!
A couple things. In your 2nd domain role example when adding user input you have, “Printer Report – Enter Computer Name”. I’m guessing you just copy and pasted and forgot to change it to Domain Role Report or something. Also, I went through a few errors before figuring out that the char ` in your previous scripts allows a CrLf in the script. This and the # (comment) should be mentioned earlier – IMO.

Thanks for catching my typo Joe. The escape character ` is mentioned in the MS Script breakdown above.

Step 2. $OS = Get-WmiObject -Class win32_OperatingSystem -namespace “root\CIMV2″ `
-ComputerName $strComputer
Creates the variable “$OS” and assigns the win32_OperatingSystem class object. Something else to look at. Even though it looks like two lines of code, it’s actually one line of code. The “`” escape character means to continue as one line. Used for keeping scripts legible should you run out of space. PowerShell reads the line as:
$OS = Get-WmiObject -Class win32_OperationSystem -namespace “root\CIMV2″ -Computername $strComputer

Sorry you missed it, glad to hear you were able to figure it out. The # comment was mentioned in an earlier tutorial.

By Bill Matsoukas on October 9th, 2008 at 10:33 am

Great tutorials! Thanks.

I am a writer, so please excuse the ticky-tack correction. I just can’t help myself. You wrote:

By appending an “i” to the operator, you’re telling PowerShell to be “case-insensitive.” Appending a “c” forces PowerShell to compare as “case-sensitive.”

Actually the “i” and the “c” are *prepended* to the operator.

Great article. The conditional that I have trouble with is using the -contains operator. I can write this in vbs using instr without a problem. I always end up using the -eg or -ne and including the entire string. Is there a way to do this? Simple example:
$a = “The quick brown fox jumped over the lazy dog”
$z = “fox”
If ($a -contains $z)
{$b = “The line is ” + $True}
Else {$b = “This is lie and ” + $false }
$b

The reason you are getting a false value with the above example is that -contains requires “exact” equality. So to get a True value your second line of code would need to look like $z = “The quick brown fox jumped over the lazy dog”.
Contains was designed to test a particular item within a collection
Examples:
$Users = “John Doe”,”Dave Davis”,”Dick Jones”
$Users -contains “John Doe”
The result is True

$Users -contains “Doe”
The result is False

To get the expected result in your example above use -like, -notlike, -match, and/or -notmatch operators

Here is an article I found that goes into more detail and will get you on your way: http://www.computerperformance.co.uk/powershell/powershell_conditional_operators.htm

Hey there Jessie, I’ve just been learning powershell from your tutorial, programming for the first time. Very interesting. I decided to try something of my own. I want firefox to report this:

PS C:\My Scripts> if (get-process -processname “firefox” | where-object {$_.cpu -lt “70″}) {write-host “firefox is using
acceptable resources”}

But I want it to close if the CPU exceeds “70″. How do I go about this? I have tried with do until/while but in most cases I get an instant closing of firefox and then a infinite loop of the script complaining no process “firefox” exists. As I said it’s the first programming I’ve done, so I might be missing something completely. Adding two “write-host” statements to the do until? Thanks alot for your tutorial, it’s been great fun so far.

Hi Kallio,
Try using a variable to capture the Process object (Firefox) and then test the condition.

#Assign object to a variable
$FF = Get-Process -Name “Firefox”
#Test condition and action to take when result is true.
If ($FF.CPU -lt 70){Write-Host “Firefox is using acceptable CPU resources”}

Regarding the conditional statement ‘Switch’, I have looked around a little and can’t seem to find how to accomplish what I need it to do. It would seem that ‘Switch’ will only output statements to the screen? I claims that it will ‘process whatever is in {}’ but all the examples are {‘literal’} or [Write-Host ‘literal’}, which works fine. What I need to know is how to make whatever I put in the script block work. Example: I want to display choices on the screen, read the users’ choice into a variable, run a Switch command that will compare the users’ input and perform the code in {} that corresponds to that choice, ie.

Write-Host ” Server A”
Write-Host ” Server B”
Write-Host ” Server C”
Write-Host ” Server D”

$ServerChoice = Read-Host “Select one”

$Server = Switch ($ServerChoice)
{
{
1 {Server A}
2 {Server B}
3 {Server C}
4 {Server D}
default {Server B}
}
}

$Databases = Get-MailboxServer $Server | Get-MailboxDatabase -status | sort-object Name

As you can probably deduce, I am trying to assign the output of the Switch statement to a variable that is to be used in the Get-MailboxServer commandlet which is piped into the Get-MailboxDatabase command. Am I wrong to think that I could use Switch in this manner? Can Switch even output anything besides text to the screen? Further, can Switch be used in such a way as to assign it’s output to a variable?

How about this…
Write-Host “[1]-Server A”
Write-Host “[2]-Server B”
Write-Host “[3]-Server C”
Write-Host “[4] Server D”

$ServerChoice = Read-Host “Select an option 1-4″

Switch ($ServerChoice)
{
1 {$server = “Server A”}
2 {$server = “Server B”}
3 {$server = “Server C”}
4 {$server = “Server D”}
default {$server = “Server A”}
}

Write-Host “You chose $server”

hello :)
check both conditions ????
im not able to find the right way !
do you have any idee?
(if or switch condition)

$d41 = 90 (1..50)
1 . if ($d41 -le 50) also “50″
{action} True ?????? but is fault !!!!!
2 . if ($d41 -gt 51 -and $d41 -le 100){action} False ?????? but is right !!!
3 . if ($d41 -gt 101 -and $d41 -le 300){action} False
4 . if ($d41 -gt 301 -and $d41 -le 500){action} False
5 . if ($d41 -gt 501 -and $d41 -le 1000) {action} False
6 . if ($d41 -gt 1001) no limite >
{action} False
many tnx for you help
arnold

Arnold,
It looks like a syntax error to me.
Try this example:

$d = 40
If(($d -eq 40) and ($d -lt 50)){$True}

$d = 50
If(($d -eq 50) and ($d -gt 60)){$True}

Hope that helps…

For all intents and purposes, consider me a day 1 newbie. I am trying to use your tutorial to get started.

per your instructions, I copied the contents of your PrintReport.ps1 file into a ps1 file on my local machine.

My desktop (the local machine where the script was run) is running vista ultimate x64. This machine is in the same workgroup as my laptop which runs Windows XP Pro.

I ran the script from the desktop and input the machine name of the laptop. I get an access denied error and the script ends.

I also tried running it on my domain (all machines are VM’s).

In the first VM, I have Windows Server 2008 running. The remaining 4 VM’s are all running windows XP Pro and are named XP1, XP2, XP3, and XP4.

When I run the script from the server and input the XP1 machine name, it hangs for about a minute then returns, “The OS for: XP1 is not supported.”

The OS of XP1 is:
OS=Windows_NT

the version is 5.1.2600

If you’re still watching this, any help is appreciated. Thanks.

One thing I notice, you mention that appending i or c to operators modifies them to be case in/sensitive, however the examples you provide are -ieq and -ceq. Though technically append does not refer to the beginning or end of the existing element as the location, by convention, append means to add to the end, just as appendices are at the end of books. What you are describing here is usually referred to as prepending.

By Vishwas Setty on May 25th, 2010 at 11:26 am

Check and make sure you have administrator rights on the machines that you are trying to run that particular script…And, I guess you should run that script which he has made on that particular machine…you might have to add some more code to do run scripts remotely….Hope tat is right….Hopefully Jesse shud look into this question soon…

Regards
Vishwas

Hi,
I seem to be getting the dollowing
The term ‘elseif’ is not recognized as the name of a cmdlet, function, script f
ile, or operable program. Check the spelling of the name, or if a path was incl
uded, verify that the path is correct and try again.
Any ideas?

I’m new to PowerShell (and I’m finding the tutorials very useful, thanks) but I’ve been around the block a few times with Perl and Bash. Whilst I can see the PrintReport.ps1 script is useful for demonstrating -or and nested “if” statements, as an example of code efficiency and readability it’s not great for people new to scripting. I haven’t tested the following, but as far as I can see it would do the same thing in a slightly nicer way…

$strComputer = Read-Host “Printer Report – Enter Computer Name”
$OS = Get-WmiObject -Class win32_OperatingSystem -namespace “root\CIMV2″ -ComputerName $strComputer

if($OS.Version -eq “5.1.2600″)
{
$osName = “Windows XP”
$class = “win32_Printer”
}
elseif($OS.Version -eq “5.2.3790″)
{
$osName = “Windows 2003″
$class = “win32_Printer”
}
elseif($OS.Version -eq “5.0.2195″)
{
$osName = “Windows 2000 Server”
$class = “win32_PrintJob”
}
else
{
Write-Host “The OS for computer $strComputer is not supported”
exit
}

$colPrinters = Get-WmiObject -Class $class -namespace “root\CIMV2″ -computerName $strComputer

Write-Host “Computer Name: ” $strComputer
Write-Host “OS Name: ” $osName

foreach ($objPrinter in $colPrinters)
{
Write-Host “Name: ” $objPrinter.Name
Write-Host “Description: ” $objPrinter.Description
Write-Host
}

Write-Host “–END OF REPORT–”

Nicely written introductory tutorials. Thank you.

* Minor cleanup: The if statement syntax has
else (condition) {code block}
rather than
else {code block}

* Also, near the top where “Conditional logic” introduces the switch statement, it points out that the PowerShell switch statement is similar to VBScript and some other languages. Even though you clearly say it later, for the sake of a non-careful reader, perhaps also mention the important difference that PowerShell’s switch can execute multiple cases.

Just minor tweaks in an excellent introduction.

For people getting the “Access denied” messages, make sure you right-click on the powershell icon and select “run as administrator”. That fixed it for me.

Ola, re the “elseif” not recognized. I noticed that when I pasted directly into the powershell window I get the same, but when I create a .ps1 file and run it as suggested it works fine. Must be a quirk in the immediate window.

Please! No apostrophes in possessive “its”.

Sweet and simple, I like it, thanks.

However, I came across your blog through searching for a solution to a problem I’m having. Can you shed some light on to why the uncommented bottom if -or statement works while the commented statement does not?

# if ($TempEnvironment -ne “dev” -or $TempEnvironment -ne “acpt” -or $TempEnvironment -ne “prod”) { …code }

The above statement steps into the code regardless.
The below statement works and steps over on a true condition.

if (!($TempEnvironment -like “dev” -or $TempEnvironment -like “acpt” -or $TempEnvironment -like “prod”)) { …code }

Would anyone know why? They should result the same (in principle). Replacing -ne with -ine or -eq (code reversed) still does not work.

There is clearly more to -or that I need to read up on. Perhaps one of you can help ‘enlighten me’.

Thanks

Hi Gary
You can read about boolean algebra, there is the answer to your question.
exp: is an expression

Your first statment:
(!exp1 or !exp2 or !exp3)

Condition: all exp false
Result: true

Condition: one exp true
Result: true

Condition: all exp true
Result: false

Your second statment:
!(exp1 or exp2 or exp3)

Condition: all exp false
Result: true

Condition: one exp true
Result: false

Condition: all exp true
Result: false

In you second example, you can use the operator: “and”

if (!($TempEnvironment -like “dev” -and $TempEnvironment -like “acpt” -and $TempEnvironment -like “prod”)) { …code }

Your second statment:
!(exp1 and exp2 and exp3)

Condition: all exp false
Result: true

Condition: one exp true
Result: true

Condition: all exp true
Result: false

Regards Per

tnx for this great guide…just wanna ask if how to get the list of -class on Get-WmiObject?

a 4 year old + article that still contains errors and no one see’s it or points it out? sorry, but if you cannot get this right no one should believe anything else you have to say.

to whit:
if (condition) {code block}
elseif (condition) {code block}
else (condition) {code block}

dude, if you have ELSE it is because all other conditions failed. You DO NOT check another (condition) in ELSE statement. it should be:
if (condition) {code block}
elseif (condition) {code block}
else {code block}

good luck with anything else you write. No one should believe any of it.

jt – is your life dedicated to demonstrating why anonymous begins with an “A”? I’ve noticed that this useful tome could be improved with some editing. But it is a worthy effort, unlike your childish, self-serving tantrum. An apology is in order.

Tanks to the author if this blog. He is helping lot of people, me included. You deserve my recognition and admiration.

Damn good site. Been scripting for years and this helps the switch over quite easy. Thanks (Screw jt)
Using what you showed already plus one extra line, rewrote this one.

cls
$strComputer = Read-Host “Enter Computer Name”
$objWMI = Get-WmiObject -Class win32_ComputerSystem -namespace “root\CIMV2″ -computername $strComputer
$OShash = @{0=”Stand alone workstation”;1=”Member workstation”;2=”Stand alone server”;3=”Member server”;4=”Back-up domain controller”;5=”Primary domain controller”}

$OShash[[int]$objWMI.domainRole]
Remove-Variable [a..z]* -Scope Global

Gary- Well said!

As a community, we are entitled to RESPECTFULLY provide corrections when we see them. Criticism and insults should be reserved for those precious few who never make mistakes. Based on the grammar and punctuation, I’d say that “jt” AIN’T that guy.
As for the rest of us, I think I speak for everyone when I say “Thank you, Jesse”

By Terry Hobart on April 24th, 2013 at 10:27 am

Please ignore my previous about Get-Member. I had the syntax backward. My bad.

Terry

I know that I’m a little late to this thread, but I would have to agree with Tom M.

I am looking for an answer to a problem, and this tutorial was extremely helpful. I can’t see ranting and raving at something that is (most likely) a typo.

Thanks Jesse for all your work.

Very helpful article – thank you very much for this.

Great example

 

Leave a Comment