Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

#2 PowerShell Learning: Working with Windows PowerShell

August 9, 2023
in Blog, PowerShell Learning
0
ADVERTISEMENT

Table of Contents

Working with Windows PowerShell

In this section we will cover the basics of using Windows PowerShell. First, we will look into the Get-Help cmdlet (pronounced “command-let”), which displays information about cmdlets and conceptual topics in Windows PowerShell.

Then, we will discuss a few of the basic cmdlets, how to use cmdlet parameters, and how to format the output of the cmdlets to get the data required to create a useful output.

Finally, we will cover how to use aliases in Windows PowerShell, how to run traditional Windows applications in Windows PowerShell, and how to manage errors.

Getting Help

To get the help about any cmdlet, PowerShell provides Get-Help cmdlet. The Get-Help cmdlet is a useful tool for learning about Windows PowerShell. By reading the descriptions of the cmdlets, learning about the concepts, and exploring the language topics, you can learn how to use Windows PowerShell.

If you are new to PowerShell, the first topic of interest might be the Get-Help cmdlet itself. To display information about the Help system in Windows PowerShell, run the following command:

PS D:\> Get-Help

TOPIC
    Windows PowerShell Help System

SHORT DESCRIPTION
    Displays help about Windows PowerShell cmdlets and concepts.

LONG DESCRIPTION
    Windows PowerShell Help describes Windows PowerShell cmdlets,
    functions, scripts, and modules, and explains concepts, including
    the elements of the Windows PowerShell language.

    Windows PowerShell does not include help files, but you can read the
    help topics online, or use the Update-Help cmdlet to download help files
    to your computer and then use the Get-Help cmdlet to display the help
    topics at the command line.

    You can also use the Update-Help cmdlet to download updated help files
    as they are released so that your local help content is never obsolete.

    Without help files, Get-Help displays auto-generated help for cmdlets,
    functions, and scripts.


  ONLINE HELP
    You can find help for Windows PowerShell online in the TechNet Library
    beginning at http://go.microsoft.com/fwlink/?LinkID=108518.

    To open online help for any cmdlet or function, type:

        Get-Help <cmdlet-name> -Online

I would recommend using Update-Help command if your system is connected to Internet. The Update-Help command will update the help files for various PowerShell cmdlets.

txE4h4HXgD9oZAHFQI23QhCPFFgFFG6eD7P19btV5002H8Bv0PlNFCAlynsC

To display detailed Help for any cmdlet, including parameter descriptions and examples, use the Detailed parameter of Get-Help. For example, to get detailed Help for the Get-Command cmdlet, type:

PS D:\> Get-Help Get-Command -Detailed

NAME
    Get-Command

SYNTAX
    Get-Command [[-ArgumentList] <Object[]>] [-Verb <string[]>] [-Noun <string[]>] [-Module <string[]>]
    [-FullyQualifiedModule <ModuleSpecification[]>] [-TotalCount <int>] [-Syntax] [-ShowCommandInfo] [-All]
    [-ListImported] [-ParameterName <string[]>] [-ParameterType <PSTypeName[]>]  [<CommonParameters>]

    Get-Command [[-Name] <string[]>] [[-ArgumentList] <Object[]>] [-Module <string[]>] [-FullyQualifiedModule
    <ModuleSpecification[]>] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script
    | Workflow | Configuration | All}] [-TotalCount <int>] [-Syntax] [-ShowCommandInfo] [-All] [-ListImported]
    [-ParameterName <string[]>] [-ParameterType <PSTypeName[]>]  [<CommonParameters>]


PARAMETERS
    -All

    -ArgumentList <Object[]>

    -CommandType <CommandTypes>

    -FullyQualifiedModule <ModuleSpecification[]>

    -ListImported

    -Module <string[]>

    -Name <string[]>

    -Noun <string[]>

    -ParameterName <string[]>

    -ParameterType <PSTypeName[]>

    -ShowCommandInfo

    -Syntax

    -TotalCount <int>

    -Verb <string[]>

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer, PipelineVariable, and OutVariable. For more information, see
        about_CommonParameters (https:/go.microsoft.com/fwlink/?LinkID=113216).


ALIASES
    gcm

To display all of the available Help for a cmdlet, including technical information about the cmdlet and its parameters, use the Full parameter. For example, to get complete Help for the Get-Command cmdlet, type:

Get-Help Get-Command -Full

You can also display selected parts of the Help file. To see only the examples, use the Examples parameter.

Get-Help Get-Command -Examples

To see only detailed parameter descriptions, use the Parameter parameter of Get-Help. You can specify the name of a parameter or use the wildcard character (*) to specify all parameters. For example, to see a description of the TotalCount parameter of Get-Command, type:

Get-Help Get-Command -Parameter TotalCount

-TotalCount <int>

    Required?                    false
    Position?                    Named
    Accept pipeline input?       true (ByPropertyName)
    Parameter set name           (All)
    Aliases                      None
    Dynamic?                     false

To see all parameters of the Get-Command cmdlet, type:

PS D:\> Get-Help Get-Command -Parameter *

-All

    Required?                    false
    Position?                    Named
    Accept pipeline input?       true (ByPropertyName)
    Parameter set name           (All)
    Aliases                      None
    Dynamic?                     false


-ArgumentList <Object[]>

    Required?                    false
    Position?                    1
    Accept pipeline input?       true (FromRemainingArguments)
    Parameter set name           (All)
    Aliases                      Args
    Dynamic?                     false
...

Using Cmdlets (Command-lets)

A cmdlet is a simple, single-function command-line tool. You use cmdlets just as you would use traditional command-line commands and utilities. Begin by typing the name of the cmdlet at the Windows PowerShell command prompt. Windows PowerShell commands are not case-sensitive, so you can type in any case.

For example, try the Get-Date cmdlet:

PS D:\> Get-Date

Wednesday, August 9, 2023 6:41:10 AM

To find the cmdlets (and other types of commands) that are available to you, use the Get-Command cmdlet.

PS D:\> Get-Command

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           Add-AdlAnalyticsDataSource                         1.0.2      Az.DataLakeAnalytics
Alias           Add-AdlAnalyticsFirewallRule                       1.0.2      Az.DataLakeAnalytics
Alias           Add-AdlStoreFirewallRule                           1.3.0      Az.DataLakeStore
Alias           Add-AdlStoreItemContent                            1.3.0      Az.DataLakeStore
Alias           Add-AdlStoreTrustedIdProvider                      1.3.0      Az.DataLakeStore
...

By default PowerShell will list all the available commands weather these are Alias, Functions or cmdlets. If you only want to list the cmdlets, use Get-Command with -CommandType parameter as shown below:

PS D:\> Get-Command -CommandType cmdlet

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Add-AppProvisionedSharedPackageContainer           3.0        Dism
Cmdlet          Add-AppSharedPackageContainer                      2.0.1.0    Appx
Cmdlet          Add-AppvClientConnectionGroup                      1.0.0.0    AppvClient
Cmdlet          Add-AppvClientPackage                              1.0.0.0    AppvClient
Cmdlet          Add-AppvPublishingServer                           1.0.0.0    AppvClient
...

Windows PowerShell cmdlets use a very simple naming convention such as verb and noun separated by a dash (-). When you know and understand the various verbs, using the Get-Command cmdlet becomes much more valuable. For example, when you are looking for information about various items, you know you will more than likely use the Get verb. Therefore, use the Get-Command cmdlet to retrieve only cmdlets that use the get verb. This is done using following command:

PS D:\> Get-Command -Verb Get 

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           Get-AdlAnalyticsAccount                            1.0.2      Az.DataLakeAnalytics
Alias           Get-AdlAnalyticsComputePolicy                      1.0.2      Az.DataLakeAnalytics
Alias           Get-AdlAnalyticsDataSource                         1.0.2      Az.DataLakeAnalytics
Alias           Get-AdlAnalyticsFirewallRule                       1.0.2      Az.DataLakeAnalytics
Alias           Get-AdlCatalogItem                                 1.0.2      Az.DataLakeAnalytics

If you want to look at the cmdlets that will assign a new value to something, you more than likely are looking for a cmdlet that uses the Set verb. The following command retrieves these types of cmdlets.

PS D:\> Get-Command -Verb Set | Select -First 5

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           Set-AdlAnalyticsAccount                            1.0.2      Az.DataLakeAnalytics
Alias           Set-AdlAnalyticsDataSource                         1.0.2      Az.DataLakeAnalytics
Alias           Set-AdlAnalyticsFirewallRule                       1.0.2      Az.DataLakeAnalytics
Alias           Set-AdlCatalogCredential                           1.0.2      Az.DataLakeAnalytics
Alias           Set-AdlCatalogItemAclEntry                         1.0.2      Az.DataLakeAnalytics

You can also use the Get-Command cmdlet to search for the cmdlets with specific noun. For example, to find cmdlets that manage Network adapter, use a command as shown below. Because cmdlet names are usually singular, not plural, the command searches for cmdlets with names that include “NetAdapter”.

PS D:\> Get-Command -Name *NetAdapter*

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Disable-NetAdapter                                 2.0.0.0    NetAdapter
Function        Disable-NetAdapterBinding                          2.0.0.0    NetAdapter
Function        Disable-NetAdapterChecksumOffload                  2.0.0.0    NetAdapter
Function        Disable-NetAdapterEncapsulatedPacketTaskOffload    2.0.0.0    NetAdapter
Function        Disable-NetAdapterIPsecOffload                     2.0.0.0    NetAdapter
Function        Disable-NetAdapterLso                              2.0.0.0    NetAdapter

Using Cmdlet Parameters

The parameters of a cmdlet let you customize the behavior of the cmdlet. Windows PowerShell cmdlets can have none, one, or many parameters. Most cmdlets have several parameters, and it’s important to become familiar with them, because they can make the cmdlet do just what you need it to do.

The cmdlet parameters are identified by a hyphen (-) followed by the parameter name. Remember that slashes (/ and \) are not used with parameters in Windows PowerShell.

When you type a parameter name, you can type the whole name or only the enough characters to distinguish the parameter name from the names of other parameters for that cmdlet.

For example, the Get-Command cmdlet has a parameter named “detailed”. You can type “-det”, which is just enough to distinguish it from the other parameter name.

Some parameter names are optional. You can use the parameter by typing a parameter value without typing the parameter name. However, if you omit the parameter name, the parameter value must appear in the in the same position in the command that it appears in the syntax diagram.

For example, the Get-Help (or in fact most of) cmdlet(s) has a Name parameter that specifies the name of a cmdlet or concept. You can type the name of the Name parameter or leave it out. To get Help for the Get-Alias cmdlet, you can either use Get-Help -Name Get-Alias command or simply use Get-Help Get-Alias command. Both will work fine.

PS C:\> Get-Help -Name Get-Alias

NAME
    Get-Alias

SYNTAX
    Get-Alias [[-Name] <string[]>] [-Exclude <string[]>] [-Scope <string>]

    Get-Alias [-Exclude <string[]>] [-Scope <string>] [-Definition <string[]>]

PS C:\> Get-Help Get-Alias

NAME
    Get-Alias

SYNTAX
    Get-Alias [[-Name] <string[]>] [-Exclude <string[]>] [-Scope <string>]

    Get-Alias [-Exclude <string[]>] [-Scope <string>] [-Definition <string[]>]

Notice the syntax of command. The parameter names which are optional appear in square brackets, such as Get-Alias [-Name] [-Exclude] [-Scope]. In this context, every parameter is optional because you can run Get-Alias cmdlet without any parameter.

Some PowerShell cmdlets (e.g. Enter-PSSession) have mandatory parameters which are required to be entered. If you omit a mandatory parameter, the PowerShell will prompt you to enter the parameter value during runtime.

PS C:\> Enter-PSSession

cmdlet Enter-PSSession at command pipeline position 1
Supply values for the following parameters:
ComputerName:

To view which parameters are Mandatory and which are optional, you can use Get-Help command with -Full parameter as shown below:

PS C:\> Get-Help Enter-PSSession -Full
NAME
    Enter-PSSession
...   
    
PARAMETERS
    -AllowRedirection
        
        Required?                    false
        Position?                    Named
        Accept pipeline input?       false
        Parameter set name           Uri
        Aliases                      None
        Dynamic?                     false
        
    -ComputerName <string>
        
        Required?                    true
        Position?                    0
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Parameter set name           ComputerName
        Aliases                      Cn
        Dynamic?                     false
...

Notice that the Enter-PSSession cmdlet uses -ComputerName as mandatory parameter. This cmdlet helps you to initiate a PowerShell session on remote computer. If you omit the –ComputerName parameter, you will be prompted to enter it.

39TMs8aN6yl15oQ3tyPEJaLlXShgAGaVQbMQZa9X3vCkUpOMu9c7LHuiLgPH

Finding Cmdlet Parameters

Each cmdlet’s help topic lists and describes the parameters of a cmdlet. To display the parameter section of a help topic, use the –Detailed or –Parameter parameters of the Get-Help cmdlet. The –Parameter parameter of the Get-Help cmdlet is particularly useful because it displays only the parameters and includes detailed information about the parameters.

For example, to display detailed information about all the parameters of the Get-Command cmdlet, type the following command:

PS C:\> Get-Help Get-Command -Parameter *

-All

    Required?                    false
    Position?                    Named
    Accept pipeline input?       true (ByPropertyName)
    Parameter set name           (All)
    Aliases                      None
    Dynamic?                     false


-ArgumentList <Object[]>

    Required?                    false
    Position?                    1
    Accept pipeline input?       true (FromRemainingArguments)
    Parameter set name           (All)
    Aliases                      Args
    Dynamic?                     false
...

To display detailed information about a particular parameter, type the parameter name in the value of the parameter of Get-Help. For example, to display a detailed explanation of the ArgumentList parameter of the Get-Command cmdlet, type:

PS C:\> Get-Help Get-Command -Parameter ArgumentList

-ArgumentList <Object[]>

    Required?                    false
    Position?                    1
    Accept pipeline input?       true (FromRemainingArguments)
    Parameter set name           (All)
    Aliases                      Args
    Dynamic?                     false

The Get-Command cmdlet displays cmdlet parameters in its syntax diagram and in the Parameters property of the CmdletInfo object that Get-Command returns. For example, to list the parameters of the Get-Service cmdlet, type:

PS C:\> (Get-Command Get-Service).parameters

Key                 Value
---                 -----
Name                System.Management.Automation.ParameterMetadata
ComputerName        System.Management.Automation.ParameterMetadata
DependentServices   System.Management.Automation.ParameterMetadata
RequiredServices    System.Management.Automation.ParameterMetadata
DisplayName         System.Management.Automation.ParameterMetadata
Include             System.Management.Automation.ParameterMetadata
Exclude             System.Management.Automation.ParameterMetadata
InputObject         System.Management.Automation.ParameterMetadata
Verbose             System.Management.Automation.ParameterMetadata
Debug               System.Management.Automation.ParameterMetadata
ErrorAction         System.Management.Automation.ParameterMetadata
WarningAction       System.Management.Automation.ParameterMetadata
InformationAction   System.Management.Automation.ParameterMetadata
ErrorVariable       System.Management.Automation.ParameterMetadata
WarningVariable     System.Management.Automation.ParameterMetadata
InformationVariable System.Management.Automation.ParameterMetadata
OutVariable         System.Management.Automation.ParameterMetadata
OutBuffer           System.Management.Automation.ParameterMetadata
PipelineVariable    System.Management.Automation.ParameterMetadata

To display the syntax diagram for the Get-Service cmdlet, type:

PS C:\> (Get-Command Get-Service).definition

Get-Service [[-Name] <string[]>] [-ComputerName <string[]>] [-DependentServices] [-RequiredServices] [-Include <string[]>] [-Exclude <string[]>] [<CommonParameters>]

Get-Service -DisplayName <string[]> [-ComputerName <string[]>] [-DependentServices] [-RequiredServices] [-Include <string[]>] [-Exclude <string[]>] [<CommonParameters>]

Get-Service [-ComputerName <string[]>] [-DependentServices] [-RequiredServices] [-Include <string[]>] [-Exclude <string[]>] [-InputObject <ServiceController[]>] [<CommonParameters>]

Common Parameters: All cmdlets have a set of parameters that are called Common Parameters. This feature provides a consistent interface to Windows PowerShell. Some of the cmdlets use the common parameters, but others do not. The effect of each common parameter varies from cmdlet to cmdlet, and some common parameters have no effect in some cmdlets.

Running Commands

Windows PowerShell provides a complete interactive environment. When you type a command at the Windows PowerShell command console, the command is processed immediately, and the output is returned to the console.

This is true for all command types, including cmdlets, aliases, functions, CIM commands, workflows, and executable files.

You can also send the output of a command to a file or printer, or you can use the pipeline operator (|) to send the output to another command.

Windows PowerShell also gives you the ability to arithmetic expressions which uses PowerShell built-in converters. Again, the experience is interactive. The expression is processed immediately, and the results are returned at the command console as shown below:

PS C:\> (100*20)/5 + (20/4)*5
425

Using Aliases

The cmdlet names can be cumbersome to type. To minimize typing, and to make it easier for users accustomed to other shells to use Windows PowerShell, Windows PowerShell supports the concept of an alias.

That is an alternate name for a command. You can create an alias for a cmdlet name, function name, or the name of an executable file, and then type the alias instead of the name in any command.

Windows PowerShell includes many built-in aliases, and you can create your own. The aliases that you create are valid only within the current session. To create a persistent alias, add the alias to your Windows PowerShell profile.

To find all of the aliases in your session, use Get-Alias cmdlet:

PS C:\> Get-Alias

CommandType     Name                                               Version 
-----------     ----                                               ------- 
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           asnp -> Add-PSSnapin
Alias           cat -> Get-Content
Alias           cd -> Set-Location
Alias           CFS -> ConvertFrom-String                          3.1.0.0   
Alias           chdir -> Set-Location
Alias           clc -> Clear-Content
Alias           clear -> Clear-Host
Alias           clhy -> Clear-History
Alias           cli -> Clear-Item
Alias           clp -> Clear-ItemProperty
Alias           cls -> Clear-Host
Alias           clv -> Clear-Variable
Alias           cnsn -> Connect-PSSession
Alias           compare -> Compare-Object
Alias           copy -> Copy-Item
...

If you are already familiar to Linux command line and Windows cmd.exe, you will find most of the commands used in Linux and Windows cmd.exe are used as Alias for Windows PowerShell cmdlets.

For example, cp command is used in Linux to copy a file, in PowerShell it can also be used to perform the same function since alias is by default created for Copy-Item cmdlet.

Similarly, copy command used in cmd.exe can also be used in PowerShell since copy alias is by default created for Copy-Item cmdlet.

The aliases in Windows PowerShell are supported by the Windows PowerShell Alias provider, a .NET Framework assembly that lets you view the aliases in a drive that looks much like the file system drives in Windows. The drive for aliases is Alias:

To change to the Alias drive, type Set-Location Alias: command.

PS C:\Users\admin> Set-Location Alias:
PS Alias:\> Get-ChildItem

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           asnp -> Add-PSSnapin
Alias           cat -> Get-Content
Alias           cd -> Set-Location
Alias           chdir -> Set-Location

To find the aliases for a specific cmdlet, use the following command:

PS C:\> Get-Alias -Definition Set-Location

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cd -> Set-Location
Alias           chdir -> Set-Location
Alias           sl -> Set-Location

Notice that Set-Location cmdlet has three default alias named cd, chdir and sl.

The above command can also be written in following way using aliases:

PS C:\> Get-Alias | ? {$_.Definition -eq 'Set-Location'}  # ? -> Where-Object

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cd -> Set-Location
Alias           chdir -> Set-Location
Alias           sl -> Set-Location

The above syntax seems to be very complicated if you are beginner to PowerShell, but I covered this because you will be more likely to see this syntax if you download any PowerShell script from TechNet or Microsoft Script Center. Let me explain what happened in above command:

  • At first place the Get-Alias cmdlet is run, and the output of Get-Alias is sent as input (piped) to another PowerShell cmdlet Where-Object with alias is ?.
  • The Where-Object cmdlet is used to filter objects based on any criteria you like. When you pipe to Where-Object, you need to specify an expression that tells PowerShell which objects you want.
  • In this case {$_.} is used to indicate the current pipeline object. Basically, $_. is the variable for the current value in the pipe line.

Windows PowerShell variables are declared with dollar ($) character. You may need to look at some more examples to understand the concept of $_. representation. For example, to list all the Windows Service which are currently running, you can use the following command:

PS C:\> Get-Service | Where-Object {$_.Status -eq 'Running'}

Status   Name               DisplayName
------   ----               -----------
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Software Monitor Service
Running  AnyDesk            AnyDesk Service

Coming back on Get-Alias command; if you already know the alias (for example you are familiar to cmd.exe) and want to list the PowerShell cmdlet for any alias, you can use the Get-Alias cmdlet with –Name parameter as shown below:

PS C:\> Get-Alias -Name cd

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cd -> Set-Location

PS C:\> Get-Alias -Name ren

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           ren -> Rename-Item

PS C:\> Get-Alias -Name del

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           del -> Remove-Item

Creating an Alias

To create aliases for cmdlets and commands in Windows PowerShell, use the Set-Alias cmdlet. For example, to create the gh alias for the Get-Help cmdlet, use the command as shown below:

PS C:\> Set-Alias -Name gh -Value Get-help
PS C:\> gh Get-Service

NAME
    Get-Service

SYNTAX
    Get-Service [[-Name] <string[]>] [-ComputerName <string[]>] [-DependentServices] 
    <string[]>] [-Exclude <string[]>]  [<CommonParameters>]

    Get-Service -DisplayName <string[]> [-ComputerName <string[]>] [-DependentServices] 
    <string[]>] [-Exclude <string[]>]  [<CommonParameters>]

    Get-Service [-ComputerName <string[]>] [-DependentServices] [-RequiredServices] 
    <string[]>] [-InputObject <ServiceController[]>]  [<CommonParameters>]


ALIASES
    gsv
...

Deleting an Alias

To delete an alias, use the Remove-Item cmdlet to delete the alias from the Alias: drive. For example, to remove the gh alias, use Remove-Item Alias:gh command:

PS C:\> Remove-Item alias:gh
PS C:\> gh Get-Service
gh : The term 'gh' is not recognized as the name of a cmdlet,
spelling of the name, or if a path was included, verify that 
At line:1 char:1
+ gh Get-Service
+ ~~
    + CategoryInfo          : ObjectNotFound: (gh:String) [], 
    + FullyQualifiedErrorId : CommandNotFoundException

Formatting Command Output

In traditional command-line shells, each tool or command determines the format of its output. Some tools let you customize the output, and they include special parameters to control the output format.

In Windows PowerShell, the only cmdlets that format output are the format cmdlets shown below:

  • Format-Table
  • Format-List
  • Format-Custom

There is no other cmdlet which formats the output. As a result, you do not need to learn the formatting routines and parameters of multiple tools. Just learn about the Format cmdlets and their parameters.

To find out the Format cmdlets available for your PowerShell session, use Get-Command cmdlet to display all cmdlets with Format verb as shown below:

PS C:\> Get-Command -Verb Format

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Format-Hex                                         3.1.0.0    Microsoft.PowerShell.Utility
Function        Format-Volume                                      2.0.0.0    Storage
Cmdlet          Format-Custom                                      3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Format-List                                        3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Format-SecureBootUEFI                              2.0.0.0    SecureBoot
Cmdlet          Format-Table                                       3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Format-VMHostDiskPartition                         12.3.0.... VMware.VimAutomation.Core
Cmdlet          Format-Wide                                        3.1.0.0    Microsoft.PowerShell.Utility

When you run a cmdlet, the Windows PowerShell calls the default formatter, which is determined by the type of data being displayed. The formatter determines which properties of the output are displayed and whether they are displayed in a list or table format.

For example, when you use the Get-Service cmdlet, the default display is a three-column table, such as shown below:

PS C:\> Get-Service

Status   Name               DisplayName
------   ----               -----------
Stopped  AarSvc_c2fc5c      Agent Activation Runtime_c2fc5c
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Software Monitor Service

To change the format of the output from any cmdlet, use the pipeline operator (|) to send the output of the cmdlet to one of the Format cmdlets.

For example, the following command sends the output of a Get-Service command to the Format-List cmdlet. As a result, the service data is formatted as a list for each service.

PS C:\> Get-Service | Format-List


Name                : AarSvc_c2fc5c
DisplayName         : Agent Activation Runtime_c2fc5c
Status              : Stopped
DependentServices   : {}
ServicesDependedOn  : {}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
ServiceType         : 224

In this format, there is more information about each service and the data is displayed in the form of list. Instead of three columns of data for each service, there are nine rows of data now. The Format-List cmdlet did not retrieve the extra service information. The Format-Table, the default formatter, omitted it, because it could not display more than three columns across on the screen.

In addition to determining whether the data appears in a list or table, you can also determine which properties of the object are displayed. 

For example, the default display of Get-Service display only the Status, Name, and DisplayName properties of the service object. To see all of the properties of an object, use a pipeline operator (|) to send the output of a command to the Get-Member cmdlet.  

For example, to see all of the properties of a service object, use the following command:

PS C:\> Get-Service | Get-Member -MemberType Properties


   TypeName: System.ServiceProcess.ServiceController

Name                MemberType    Definition
----                ----------    ----------
Name                AliasProperty Name = ServiceName
RequiredServices    AliasProperty RequiredServices = ServicesDependedOn
CanPauseAndContinue Property      bool CanPauseAndContinue {get;}
CanShutdown         Property      bool CanShutdown {get;}
CanStop             Property      bool CanStop {get;}
Container           Property      System.ComponentModel.IContainer Container {get;}
DependentServices   Property      System.ServiceProcess.ServiceController[] DependentServices {get;}
DisplayName         Property      string DisplayName {get;set;}
MachineName         Property      string MachineName {get;set;}
ServiceHandle       Property      System.Runtime.InteropServices.SafeHandle ServiceHandle {get;}
ServiceName         Property      string ServiceName {get;set;}
ServicesDependedOn  Property      System.ServiceProcess.ServiceController[] ServicesDependedOn {get;}
ServiceType         Property      System.ServiceProcess.ServiceType ServiceType {get;}
Site                Property      System.ComponentModel.ISite Site {get;set;}
StartType           Property      System.ServiceProcess.ServiceStartMode StartType {get;}
Status              Property      System.ServiceProcess.ServiceControllerStatus Status {get;}

Since all of these properties are in the object that Get-Service retrieves for each service, you can display any or all of them. Use the Property parameter of the Format cmdlet to select the properties to be displayed and the order in which they are displayed. For example, the following command uses the Format-Table cmdlet to display only the Name, ServiceType, and Status properties of the service.

PS C:\> Get-Service | Format-Table Name, Servicetype, Status -AutoSize -Wrap

Name                     ServiceType  Status
----                     -----------  ------
AarSvc_c2fc5c                    224 Stopped
AdobeARMservice      Win32OwnProcess Running
AdobeUpdateService   Win32OwnProcess Running
AGMService           Win32OwnProcess Running
AJRouter           Win32ShareProcess Stopped

When you use the –AutoSize parameter of Format-Table cmdlet, Windows PowerShell will calculate column widths based on the actual data you are going to display. This makes the columns more readable. You can force lengthy Format-Table data to wrap within its display column by using the Wrap parameter.

If you want to manually sort and filter the output of command, you can pipe the output of cmdlet to Out-GridView cmdlet. The Out-GridView cmdlet sends the output to an interactive table in a separate window as shown below.

9Q2gQNHPzuEmyd0bzYen4aRPvGLrBOxspEqhQ15qRbXphNVIgOTdLm9GkTE6

This is just the beginning of what you can do with Windows PowerShell output. For more details, you can read the help for all the Format cmdlets.

Running Scripts

What is a script?

A script is text file that contains one or more Windows PowerShell commands or expressions. When you run the script, the commands and expressions in the script file run, just as if you typed them at the command line.

Typically, you write a script to save command sequence that you use frequently or to share a command sequence with others.

Scripts can be as simple as a one-line command or as complex as an application program. Windows PowerShell includes a very rich and powerful scripting language that is designed especially for people who are not programmers. It supports language constructs for looping, conditions, flow-control, variable assignment, and much more.

How to Write Scripts?

To write a script, start a text editor, such as Notepad, or a script editor, such as Windows PowerShell Integrated Scripting Environment (ISE). Type commands or expressions, just as you would type them at the command line. Then save them to a file with .ps1 extension.

We recommended you use VS Code as a script editor. It’s a free, beauty and powerful text editor made by Microsoft.

For example, the following command finds PowerShell scripts in your user profile directory ($home) and its subdirectories. The $home automatic variable is equivalent to the %UserProfile% environment variable, which is written as $env:UserProfile in Windows PowerShell.

PS C:\> Get-ChildItem -Path $home\* -Include *.ps1 -Recurse

    Directory: C:\Users\admin\.vscode\extensions\ms-vscode.powershell-2023.6.0\examples\Tests

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          6/9/2023  10:18 AM           5533 PathProcessing.Tests.ps1
-a----          6/9/2023  10:18 AM            307 SampleModule.Tests.ps1

That’s all. As you become more familiar with Windows PowerShell, you’ll create more scripts and get scripts from colleagues and from safe websites.

How to Allow Scripts to Run?

Although scripts are extremely useful, even essential, they can be used to spread malicious code to potentially compromise your computer. To keep your computer secure, the default Windows PowerShell execution policy is Restricted which does not permit you to run scripts.

And, to eliminate an obvious risk, none of the execution policies in Windows PowerShell allow you to run a script by double-clicking the script file.

To get the current execution policy, use the Get-ExecutionPolicy cmdlet.

PS C:\> Get-ExecutionPolicy
Restricted

To change the execution policy for the computer, particular users or for particular sessions, use the Set-ExecutionPolicy cmdlet, as follows.

1️⃣ Start Windows PowerShell with the Run as Administrator option.

2️⃣ Run the Set-ExecutionPolicy RemoteSigned -Force command.

PS C:\> Get-ExecutionPolicy
Restricted
PS C:\> Set-ExecutionPolicy RemoteSigned -Force
PS C:\> Get-ExecutionPolicy
RemoteSigned

For more information, see PowerShell ExecutionPolicy.

How to Run PowerShell Scripts?

To run a script, type the path and name of the script file. The path is required, even when the script is located in the current directory, to make it more difficult for malicious code to run scripts. The file name extension is optional.

This approach makes Windows PowerShell safe from lurking attacks that are most common in Linux and Unix world. You will have to provide the explicit path to script which prevents the malicious script to be executed accidentally even if it is in your current working directory.

For example, to run the myscript.ps1 script, type:

PS D:\scripts> dir

    Directory: D:\scripts

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          8/9/2023   2:38 PM             48 myscript.ps1

PS D:\scripts> Get-Content .\myscript.ps1
Write-Host "This is my first PowerShell script."

PS D:\scripts> D:\scripts\myscript.ps1
This is my first PowerShell script.

If the script you want to run is in the current directory, type the directory name with a dot (.) to represent the current directory. For example, use the Set-Location command to navigate to D:\scripts directory. Then, use a dot to indicate the current directory in the path to the myscript.ps1 script.

PS C:\Users\admin> Set-Location 'D:\scripts'
PS D:\scripts> .\myscript.ps1
This is my first PowerShell script.

Run with PowerShell

There is one more way to run scripts. It is designed for particular types of scripts, so you’re likely to use it only occasionally, but it’s very handy when you need it.

Beginning in Windows PowerShell 3.0, you can run scripts from File Explorer in Windows 8 and Windows Server 2012 and from Windows Explorer in earlier versions of Windows. The Run with PowerShell feature is designed to run scripts that do not have required parameters and do not return output to the command prompt.

To use the Run with PowerShell feature. In Windows Explorer, right-click the script file name and then select Run with PowerShell.

R1Z31uMp7vJ4dDdaxS8yltR3q83LG8EyhvUVfCspGCBwWxbYd9ahLVkqovXZ

The Run with PowerShell feature starts a Windows PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.

Run the Script with Run Dialog Box

You can also execute a script right from Run dialog box (Windows+R), however the syntax is somewhat complex, but it might come handy if you want to schedule a PowerShell script in Windows Schedule Tasks. 

Before actually scheduling the script, you can test if the script could run successfully. For example, follow the steps to run myscript.ps1.

1️⃣ Open the Run dialog (Press Windows+R).

2️⃣ Type powershell.exe -noexit -file “D:\MyScripts\Get-scripts.ps1 and press Enter.

powershell.exe -noexit -file “D:\scripts\myscript.ps1"

The script will be run in PowerShell window and the window will auto close once the script execution completes. The -noexit parameter keeps the PowerShell window open even after the script execution is completed.

You can also use -WindowStyle parameter with the Minimized or Maximized value to change the behavior of the PowerShell window. The -WindowStyle Minimized parameter will run the PowerShell window minimized to task bar.

List the Properties and Methods of Objects

When you start working with any Windows PowerShell cmdlet, you might be wondering that which properties and methods are available to be used with a particular cmdlet.

The Windows PowerShell provides Get-Member cmdlet to do this for you. Once you connect to an object, you can pipe that object to Get-Member; in turn, Get-Member will enumerate the properties and methods of that object. 

For example, you can use Get-Member cmdlet to determine the Methods and Properties available for a PowerShell cmdlet.

PS D:\scripts> Get-Service | Get-Member

   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
RequiredServices          AliasProperty RequiredServices = ServicesDependedOn
Disposed                  Event         System.EventHandler Disposed(System.Object, System.EventArgs)
Close                     Method        void Close()
Continue                  Method        void Continue()
CreateObjRef              Method        System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Pause                     Method        void Pause()
Refresh                   Method        void Refresh()
Start                     Method        void Start(), void Start(string[] args)
Stop                      Method        void Stop()
WaitForStatus             Method        void WaitForStatus(System.ServiceProcess.ServiceControllerSta
CanPauseAndContinue       Property      bool CanPauseAndContinue {get;}
CanShutdown               Property      bool CanShutdown {get;}
CanStop                   Property      bool CanStop {get;}
Container                 Property      System.ComponentModel.IContainer Container {get;}

StartType                 Property      System.ServiceProcess.ServiceStartMode StartType {get;}
Status                    Property      System.ServiceProcess.ServiceControllerStatus Status {get;}
ToString                  ScriptMethod  System.Object ToString();

While working with any Windows Service, you will be most likely wanting to Start or Stop the service or change its StartupMode. Windows PowerShell offers large number of Methods and Properties (including Stop and Start) for Service objects.

Running Windows Programs

You can run Windows command-line programs and start Windows graphic programs by using Windows PowerShell. If the program generates text output, you can capture the text and use it in Windows PowerShell.

You can run many programs just by typing the program name. For example, you can start the Notepad program by using the following command.

PS C:\> notepad
PS C:\> calc.exe
5ljwNNfL1P9PkhgCXAko0AbWxRs7es8bLqnOXCPPFebjCvRe1t4QlnBMCs0f

This command works because the executable file for the Notepad program is in a location that is listed in the Path environment variable.

To start the program in other locations, type the full path to the program. If the path includes spaces, enclose the path in quotation marks and parentheses and use the call operator (&) to run the quoted string.

For example, the following command starts Microsoft Word, use the following command:

PS D:\scripts> &("C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE")
h9dWpAATHXydgBSLOK2mxM1VbjXAWhj64SPww3nLMGmTMPsPMFFZkW5bH6Ty

To make this command easier to run, create a function and save it in your Windows PowerShell profile. For example, the following command creates the Word function.

function Word {
    &("C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE")
}

Now, every time you want to start Microsoft Excel from PowerShell console, just type word in console and press Enter.

0hdVVtX4MY8chgshk8V0ls0ZF1FhKGPZtySzHKoILacXU0duudTPy3fliqEw

Managing Errors

Errors will occur occasionally when you use the Windows PowerShell, such as when you are trying to set your location to a nonexistent directory or trying to remove a file without the required privileges.

There are two types of errors in Windows PowerShell:

  • Terminating Errors: Errors that halt the execution of the command.
  • Non-terminating Errors: Errors that do not halt the execution of the command.

For example, if you are removing files from a directory, you might not want the operation to stop if one of the files cannot be removed. Typically, you want to remove all of the files that you can remove, and then go back for the files that you could not remove.

The error that occurs when you cannot remove a file is called a non-terminating error. When a non-terminating error occurs, Windows PowerShell continues despite the error and then displays the error along with the output.

More serious errors will stop command processing. These are called Terminating errors. Terminating errors stop the processing of the command. For example, if you submit data that is not valid or if you do not have the permissions required to perform the command, Windows PowerShell generates a terminating error.

Once you start writing scripts, you should become familiar with the –ErrorAction parameter. It is one of the standard parameters and is therefore available on all cmdlets. It allows you to specify a custom error action for each cmdlet or each line of code in your script.

Get-Content .\myscript.ps1 -ErrorAction Continue
Get-Content .\myscript1.ps1 -ErrorAction Stop

In the code shown above, the first line of code has –ErrorAction Continue parameter which means it informs you of an error if it occurs while retrieving the content of the myscript.ps1 file located in current directory. If an error occurs, after informing you of the problem, the script continues to the next line. The –ErrorAction for the second line of code is Stop. The script will halt if the Get-Content cmdlet is unable to find the file myscript1.ps1.

You can either use enumeration or use a numeric value with ErrorAction parameter Table 1 shows the enumeration and values which can be used with ErrorAction parameter:

jIkd6c0qtt08P37ZcDLAz5g8MVOcupbMZRKj0EpFFrkWe6KGvz8YHIzklQ1r

This means, the above code lines can also be written as follows:

Get-Content .\myscript.ps1 -ea 2
Get-Content .\myscript1.ps1-ea 1
Note Recommendations: When writing a script, I do not recommend using aliases and enumeration values directly because it makes the script very difficult to read, which in turn makes the script harder to troubleshoot. However, when working interactively from the Windows PowerShell prompt, it is perfectly acceptable to use the enumeration values and alias.
5/5 - (1 vote)
Previous Post

#3 PowerShell Learning: Writing and Running PowerShell Scripts

Next Post

How to Bypass Chrome Security Warnings Your Connection is Not Private

Related Posts

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024
Ftr19

How to Fix Windows Cannot Read the ProductKey From the Unattend Answer File in VirtualBox

July 26, 2024
Ftr25

How to Update Windows Terminal in Windows 10/11

July 26, 2024

How to Disable The Beep Sound in WSL Terminal on Windows

July 26, 2024

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory