PowerShell Syntax, Help, & Conditionals.md - Juan-bit94/Ops401D10 GitHub Wiki

Syntax, Help, & Conditionals

Understanding PowerShell cmdlets

  • To understand cmdlets and PowerShell, its important to draw some distinctions among terms.
  • Some of these terms have widely separate meanings in the computer world. Understanding how they relate to PowerShell and how they interrelate to each other, forges the way to mastering PowerShell because they are an important relationship specific to learning PowerShell.
  • The first term is cmdlet. These are the core commands of PowerShell, the native commands so to speak. Its important to understand that's it's okay to call PowerShell cmdlets commands.
  • With that said, there is a very real difference between cmdlets and functions.
    • Functions, they are named sets of PowerShell commands that perform repeating set of tasks. It is safe to draw an analogy between functions as they relate to programming languages and functions as they relate to PowerShell, same idea.
    • Script, its a set of commands that perform repeating sets of tasks, like functions, they're comprised of PowerShell cmdlets. The main distinction is that scripts are often thought of as saved text files that can be launched at any time.
  • Its a bit of splitting hairs because functions are often created and saved as scripts.
    • External commands, they are non-native commands (DOS commands for example), it worth putting them in the mix, because while they can be relatively transparent in terms of working with PowerShell, they are not native PowerShell commands, they are not cmdlets. They are simulated commands that build a bridge between DOS and PowerShell. They are there for compatibility and to ease the transition between other CLIs and PowerShell.

Understanding Cmdlets

  • Cmdlets are applications
    • .NET commands in C#
    • Compiled
  • In practical terms, what really sets PowerShell cmdlets aside from their counterparts in other CLIs is that they are applications. Actual .NET commands written in .NET languages like C#. They have a very distinct and it's relatively safe to say rigid syntax, verb-singular_noun.
  • To be clear, that's any PowerShell cmdlet that comes from Microsoft, you will not find any exceptions, and there are about 100 approved verbs mandated by the PowerShell teams, but beyond the team, you can't enforce it.
  • If you create your own cmdlet, you choose anything you like. Now you probably have guessed that this is a bad idea, and even if you do create your own cmdlets, you should adhere to the PowerShell standard, since it means stability and standardization and those are good things.
  • PowerShell commands have two primary forms:
    • Cmdlets
    • Functions
  • PowerShell commands have two primary forms, cmdlets and functions. All it means is that a user can use a single cmdlet or a group of the as a function.
  • Cmdlets are written in compiled .NET languages like C#
  • Function is a collection of PowerShell cmdlets.
  • Cmdlets and functions are typically packages

Cmdlet Fundamentals

  • Get is the most common verb in PowerShell
  • Noun is always singular
    • Get-Process | not Get-Processes
    • Get-ChildItem | not Get-ChildItem
  • PowerShell is generally case-insensitive when it comes to cmdlets.

Using Get

  • Let's start by clicking on the Windows button, right click on Windows PowerShell and choose Run As Administrator. Now the most commonly used verb in the PowerShell command library is Get.
  • As the name implies, Get retrieves something.
    • Example:
      • get-command
    • I can type the above get-command, now I will get to see a list of all the PowerShell functions, cmdlets, and aliases.
    • get command has its own aliases, gcm. run gcm and you will get the same results.
  • Now there are a ton of PowerShell functions, cmdlets, and aliases. Having them all be displayed is not very useful, so you could use wildcards to drill down.
    • Example:
      • gcm a*
    • The command above will show you all the PowerShell commands beginning with A.
  • If you want to use get with a specific PowerShell feature, for example, to see the drives that PowerShell is using, you can use this command get-ps, for PowerShell, drive.
    • You will notice after running the cmdlet, how more than just local drives are displayed. There are actually registry entries, network drives, and even variables.
    • You can call up help for get-psdrive to understand what you are looking at.
    • Example:
      • get-help get-psdrive
  • Get is widely used and it's safe bet that as you work with PowerShell, you are going to want to use help to find the various get functions and cmdlets in PowerShell.

Working with Modules

  • This section will discuss modules and working with them in PowerShell.
  • Modules in PowerShell have two states, loaded and unloaded. In order to work with a module it has to be loaded. So if we want to see just the loaded modules, just type in get-module and press enter.
  • To see the list of all available modules, you can type the following: get-module -listavailable and press enter.
  • You will see a ton of unloaded modules, if you see a module you want to load, use the gcm (alias for get command). put a space -module and then the name of a module, lets say its the applocker one.
    • Example:
      • gcm -module applocker
    • After entering the above cmdlet, you will get some information on applocker.
  • Now to remove a module, run the following cmdlet
    • Example: -** remove-module applocker**
  • Keep in mind, that when you load a module, you will see different cmdlets that you can use.
  • To see all available functions doe branchcahe, run the following cmdlet
    • Example:
      • gce -module branchcache
  • The above cmdlet will give you the ability to see right away when you load something exactly what's available to you once that module is loaded.

Help Syntax

  • It may seem odd to discuss at great length a help file system, but knowing this helps when you understand PowerShell a bit better, and the scope and breath of its functionality, it becomes really easy to understand why it Help is an important topic when discussing PowerShell. The help system itself is expansive and I'll suggest right off the bat, that you find yourself turning to help more than you normally would with other applications, and that speaks to the all encompassing power of PowerShell.
  • Now it all starts with Get-Help, the main help command in PowerShell.
    • Get-Help [cmdlet] <parameters>
  • You follow the get-Help with whatever function alias or cmdlet you need help on and any applicable parameter's.
    • Example
      • Get-Help Get-EventLog
  • PowerShell Help is not limited to your local system. You'll use the local help a lot, but you also have the option of going online to delve deeper. PowerShell Help should be updated routinely because there's always new functionality and information that gets added to help.
  • There are two alternate commands, man and help that works as well.
  • Note that these only work for commands and they specifically show one screen at a time, similar to piping the more switch to the Get-Help cmdlet.

PowerShell characters and pipes

  • PowerShell Help can also take advantage of numerous characters, and the piping character.
    • Example:
        • (wildcard) the asterisk is a wildcard that works like in other applications, revealing everything (show all).
      • | (pipe) the pip character is the shift of the backlash key normally found above the entre key. And if you've done any work with Linux or Unix, then you know how its used. You can use pipe with more to pause when the screen gets filled using enter to continue one line at a time and space to continue one screen at at time.
      • ? The question mark is used in place of Get-Help used for cmdlet help
        • Example: Get-Command -?

Going Deeper into Help

  • Advanced syntax can dig right into help specifics (like synopses):
    • Example:
      • Get-Help * | Where { $_synopsis -Match "path" } | ft name, synopsis -auto
    • Like synopses for example, and the example here searches the synopsis of all help functions, cmdlets and aliases, and returns anything that contains the string path. The main takeaway here as I kind of indicated earlier, is that mastering Get-Help is its own major topic, and it will become a regular part of your routine when you're working with PowerShell.

Understanding PowerShell Help File syntax

  • The cmdlet we will use is get-help, type it and press enter.
    • You will see description followed by a other information.
  • There are two other commands that you can use.
    • The first is help, go ahead and type that and press enter.
      • As you can see, we have the very same information topic, short description, long description, and so on.
      • If we use a pipe and then the more command. Every time You press enter, you can move down one line, or if you press space, and entire page.
    • The second is man, if you go ahead and type that and press enter. You will see it has the exact same results.
  • Now, with Get-Help, what I want to do is I want to see actual help on a specific topic. So I will use the up arrow to bring the command back, and then put a space and then type in server and press Enter. Now what happens here is we see all sorts of information from the help system on
    • Example
      • get-help server
  • Now that's great, and if I wanted to get help, say, specifically on server manager, get-help space and then type in servermanager and press enter.
    • Example
      • get-help servermanager
  • You can see that we have two functions from the help system that we can actually drill down on. If we want to use PowerShell to do some sort of interaction with servermanager.
  • I am going to show you something that's a little bit complicated. This is where the syntax gets really complicated. and it'll take sometime for you to familiarize yourself with the syntax.
  • I'm going to use get-help. And what I want to do here is I want to dig into all the help topics that contain a string. In this case, I'll say path, so the string will be path. I actually want to search the synopsis, so not the actual command names themselves but the actual synopsis that the PowerShell help provides.
  • So get-help* and here's where I use the pipe. So it's right above the a Shift key on the right-hand side. Just like that and then a space and then where. And then inside braces, I'm going to use curly braces, and this is where we actually have the string information. So, the $_.synopsis-match. and then in quotation marks, path, opening ad closing quotation marks, and then close that brace. Now, I'm going to put a space and add another pipe. And, I'm going to use ft, feature name, f is short for feature, name, synopsis. And then, -auto.
  • Now again, this is sort of the other end of what I showed you earlier with the PowerShell help. So, this is a kind of complicated syntax to grasp. And over time, you'll understand when you use the help system that you can do things like this to drill right down into the deepest parts of the help system. I'll go ahead and press Enter, and it might take a second to search and, there you go.
    • Example
      • get-help * | where {$_.synopsis -match "path"} | ft name.synopsis -auto
  • So what this cmdlet did was bring back anything under the synopsis. Remember, we're not talking now about the name, we're talking about synopsis that has the word path in it. And, you will see some ellipsis marks there, that just means there's more information in these actual commands.
  • But you can see that the word path has been brought up and that's great because that allows us to look for specific things. In this case, if I wanted to find all the PowerShell functions, cmdlets and aliases that in the description had some sort of path operation.

Comparison operators

  • We will discuss PowerShell's comparison operators. Now PowerShell is well named. It's got power right in its name and you can use comparison operators in PowerShell to actually create functions and all sort of scripts on the fly. So let' take a look at the comparison operators.
  • The first one is greater than, so let's try this, 10 -gt 20, the -gt stands for greater than. If you run it, you will get the return false because 10 is not greater than 20, so we get a false result.
  • If you try the inverse, 20 -gt 10, you will get a true result.
  • So you can start to use comparison operators to incorporate programmability into your work with PowerShell.
  • Let's take a look at the other comparison operators. So for example, there's less than. So it's LT, -lt. 10 is less than 20 (10 -lt 20). If we run this, we get a true result.
  • Then there's equals, so 20 -eq 15+5, is 20 equals (to) 15 minus 5. the result is false. So we can actually test equality. I'm going to bring that back up with the up arrow and this time change that second value to 6.
    • 20 -eq 15+6 would return false.
  • There's also not equals. So 20 -ne 15+5, -ne stands for not equals, there we get a false return.
  • So let's try this, 30 -ge 20, -ge is for greater than or equal to. For this we get back true.
  • And then there is less than or equal to, 20 -le 30, -le for less than or equal to. For that we get true.
  • You can even use a comparison operator with strings. This becomes very helpful, for example, start a quotation mark there.
    • "Hello" -eq "hello", -eq for equals, and obviously that will come back as true.
  • If I bring that back up though, let's change that last character to a zero. We will get a false return because the two strings are not equivalent.
  • You can come to understand how to compare strings, for example, "chrome" -ne "Firefox", and we get a true because the two aren't equal to each other.
  • So once we start to work with the comparison operators, and plug those into the other functionality you're going to learn about PowerShell, you can start to create some fantastic, extremely powerful scripts and commands with single lines or just a couple of lines using the comparison operators as one of your tools.

Using Where-Object

  • This section discusses Where-Object in PowerShell. Where-Object and its typed where-object is a PowerShell cmdlet. And what it does is that it selects objects that have certain property values. You can pass objects to the command to uncover these objects. So, you can use where-object to find objects containing certain IDs, or for example, dates. Now, where-object has two primary uses:
    • As script blocks
      • Script blocks need a property name, an operator that serves as a comparison, and some sort of property. And where-object will display all the objects result in a true value. So, let's take a look at that first. So where-object, and this is the script block, get-process. So what we want to do is get all the processes or search in the processes in the computer and here's where we type in, where-objects. So all we're doing is getting the processes and piping them into where-object. Now, this is a script block, so the idea here is this is how you would write it in a script, for example. And, we would use braces, and then inside the braces, I'll use the $ so for a string_and then, .priorityclass. Now what we want to do is search in the priorityclasses of the processes to get some sort of result. And in this case, I'll use equality, so -eq and a string, and the string is normal. So all we want to do here is a find all the processes that are running at the normal setting. And if I go ahead and press Enter
      • Example
        • get-process | where-object {$_.priorityclass -eq "normal"}
      • We can see all the various processes laid out in a table with the process names. Now you may have guessed that we can do another way. So I'm going to bring that back up with the up arrow. This time, I'm going to say ne, so not equal to low. So really with processes and Windows, we have three types: low, normal, and high processor priority. So, I'll go ahead and press Enter.
        • get-process | where-object {$_.priorityclass -ne "normal"}
      • Now here what happened was, we actually got a couple more results because, there are a couple of processes that are running high. And so, this combined because we use not equal, all the normal and high process assignments in Windows. So, this resulted in all the normal and high processes and those get returned back to us. Now, comparison statements are a little easier to craft and understand, because they dispense with the braces and special characters. So, it's more realistic in the language that it uses and it can do the same things. So, I'll type this in, get-process. Again, we're going to use the pipe and pipe into where-object, but we're going to dispense the braces. So it's just priorityclass -eq. And then, normal. And I press Enter, and we get the very same results that we got using the script block style of syntax. And, just one more example.
        • get-process | where-object priorityclass -eq "normal"
      • This time, I'm going to change normal to, low because remember, when we used the not equals to low, we got the results back that were normal and high. And as you can see, they are no processes set to low.
        • get-process | where-object priorityclass -eq "low"
        • get-process | where-object priorityclass -eq "high"

If, Else, and Elseif Statements

  • We will discuss If, Else, and Elseif Statements in PowerShell. Now, in addition to the comparison operators, PowerShell has a fully featured conditional system where you can use statements like if, else, and elseif, programming statements. So let's take a look. Now, the first thing I'm going to do is create a variable. So I am going to start with the $ sign, string sign, num, we'll call the variable num, for number, = and I'll set it at 10 and press Enter. Now you can also use write-host, which actually writes back to the PowerShell screen.
  • It looks like this, write-host, and space, and then the name of our variable, $num. Press Enter, and you can see the value is 10. Great, so we're all set. Now, I'm going to use the if statement. So if, and what you do with if, it's very similar or exactly the same as working with languages like C and C# and so on, Java. In parenthesis, you have your test statements. Now, the test statement is the name of the variable. And then a space and then I'm going to test for equality here.
    • Example
      • $num=10
      • write-host $num (this cmdlet prints the value of the variable)
      • if($num -eq 10) {write-host "it's 10} This prints the message it's 10 -So I'll use the comparison operator eq for equals, 10. Close the parentheses and then put a space, you don't need to but I'm going to put a space there. Create an opening brace and then write-host and a string, "it's ten". Close the brace, and press Enter. And as you can see, we get a positive result. The result comes back true, because num does equal 10. If we wrote the statement to return false, then nothing would come back.
    • Now, I'm going to put in an else statement. So if else works exactly the same way as it does with other programming languages, so if one condition is true, we get the first result. Otherwise, and that's where else comes in, we get the other results. So in braces, write-host "not 10". Close that brace and press Enter. And we get that result of it's 10, because we know that we haven't changed the variable's value.
      • if($num -eq 10) {write-host "it's 10} else {write-host "not 10"}
    • Let's go ahead and do that. $num=11.
    • So if we bring up that last command, this one tests for 10, we should get a false result which means that the else statement will kick in and we'll get a result of not 10, and there you go, that worked. So, let's take it one step further. I am going to do an elseif statement right here. So after the if statement, elseif, like that. And then we have our testing condition in parentheses.
      • if($num -eq 10) {write-host "it's 10"} elseif($num -eq 11) {write-host "it's 11"} else {write-host "not 10"}
    • What I'll do is say, $num space rather -eq 11. Close that parenthesis right there, create our opening brace write-host, "its 11", close that brace and then put a space. So we've add that extra statement, so here we're going to test to see if it's 10. If num is 10, we get a result telling us it's 10. But we have an elseif here, so now it's going to check to see if it's actually 11, and if it is 11, then it's going to tell us that it's 11. And I'm going to change this because, obviously, we have two tests here. So I'm just going to put in a result for anything that doesn't come up, that's either 10 or 11, I give up. Press enter and you see we get 11. If I change the value of num back to 10, and I'll bring back that last command. Now we get a result, it's 10. And if I change num to 12, we get the final else result, I give up.
  • So you can see that you can do all sorts of interesting things using testing or comparison operators and the conditional statements of if, else, and elseif.

Switch Statements

  • This discusses switch statements in PowerShell. Okay, I'm going to start by showing you something, write-host. What I want to do here is get the date, you can use the get-date function. You open two parentheses, type in (get-date). Close one parenthesis, put in a period, and then whatever you're looking for, in this case, let's say dayofyear. and press Enter, and there you go. It's 99th day of the year.
    • Example
      • write-host ((get-date).dayofyear)