How to Use Cmdlets in PowerShell

Posted by:

|

On:

|

A cmdlet is a command in PowerShell. When you type cmdlets in the terminal or code editor, you’ll see a glow. For me, it’s yellow. Anything that color is something you’re telling the computer to do.

To start, Cmdlets are made of two attributes, a verb and a noun. Usually, you’ll see the verbs Get and Set as you read and update information. The nouns are what you are trying to perform an action on. This could be an ADUser, SQLServer, a Service, etc.

Cmdlet Parameters

Subsequently, you can add parameters that come in two main types: named parameters and switches. You will explicitly define named parameters, and switches are usually considered true if used.

Cmdlet with Named parameter:

PowerShell
Get-Service -Name wsearch

Cmdlet with switch:

PowerShell
Get-Service -RequiredServices

Many cmdlets will have default parameters, in this case “Name” is a default parameter.

PowerShell
Get-Service -wsearch

Notice that the output of the code above is a table. You can select each header to parse only the information needed.

Cmdlets Piping and Methods

Next, we’re going to use a pipe | to pull the table into our next command. Pipes take the previous statement as input to the next.

PowerShell
Get-Service -Name wsearch | Format-List

As you can see, this is useful, but maybe you wanted to just know what services Windows Search depends on. You can use the Select-Object cmdlet to do that.

PowerShell
Get-Service wsearch | Select-Object ServicesDependedOn

If you remember, the cmdlet retrieves an object, in this case the service wsearch. If you want to get more advanced, we can put parentheses around the object and select the ServicesDependedOn directly. This makes for cleaner code, and you’ll look cool in front of your friends.

PowerShell
(Get-Service wsearch).ServicesDependedOn

Cmdlets are fun to play around with. As you get more comfortable, you’ll see the pieces that make up these objects and have a better understanding of how to complete a given task.

Cmdlets Help and Documentation

Finally, use these cmdlets to help better understand what PowerShell can do:

  • Get-Help. This is your best friend, alongside using -? as an argument. This command will show help files like a manual page in Linux. You can also use the -online switch to pull up the command in Microsoft’s website.
  • Get-Command: Retrieves all commands installed on your machine.
  • Get-Verb: Running this command will generate a list of verbs, and running the command with a verb will show you what group the verb is in. Knowing this can help you learn what to expect a command to do.
  • Get-Member. This requires an object to run and will show you what properties and methods you can apply.

In the future, I might cover interesting cmdlets in detail, but toy around with these to see what all you can do.