Share via


PowerShell V3: Tips and Tricks

 

PowerShell Language and Features

This section looks at new features within the basic PowerShell Language. The aim of the team for V3 has been to remove the "scripting wall".

New syntax for Where-Object

The old syntax of:

 Where-Object { $_.<property name> }

Can now be written as:

 Where-Object <property name>

# Example 1

# Old ver.2 syntax

Get-ChildItem | Where-Object { $_.PSIsContainer }

# New syntax

Get-ChildItem | Where-Object PSIsContainer

# Example 2

$oldDate = (Get-Date).AddDays(-30)

Get-ChildItem | Where-Object lastwritetime -le $oldDate

#Example 3

Get-Process | Where-Object { $_.handles -gt 1000}

Get-Process | ? handles -gt 1000 

New Alias for Select-String

Now there is a built-in alias for Select-String. This is sls.

# Example of select string new alias

sls -path c:\test.txt -pattern 'Hello' 

New -in and -notin operator

In PowerShell 1 and 2, we have the *-contains *and -notcontainsoperator. In addition to this, we now have the -in and -notinoperators, which works similarly, but the opposite way around:

# Example 1:

$value = 3

if ($value -in (1,2,3)) {"The number $value is a member of the array"}

# Example 2:

4 -notin (1,2,3)

#prints True

ISE Features

Two Pane ISE

In V2. the ISE had three panes - a script pane, a command pane and an output pane. You typed commands into the command pane, but saw the output within the output pane. There were related $PSISE features to manage these. In V3, the output and command pane are merged so that they resemble the normal shell.

Turn off Command Pane at ISE startup

By default, the new ISE opens the Command Pane on the right-hand side of the screen by default. Some may find this annoying. To turn it off, un-check "Show Commands" in the "View" menu of the ISE.

Intellisense

This is tab-completion on steroids. As you type, ISE recognises partially typed cmdlet names, cmdlet parameter names, enums, etc, and offers possibly alternatives. If you type, say Get- and pause, PowerShell ISE brings up a set of useful items beginning with 'Get-;, such as Get-AsciiEncoding, etc. This provides a huge benefit for those writing scripts - not only will PowerShell cut down on the typing, but things such as parameter names now get spelled out in full (a good thing for production scripting).

Cmdlet and Provider Changes

New -Append parameter for Export-CSV

There is now an -Append parameter for Export-CSV, which works in the same way as it does for Out-File. Note that the field names exported must have corresponding field names in the existing csv file that is being appended to. 

If the names do not correspond, you receive a message similar to the following:

Export-Csv : Cannot append CSV content to the following file: Users.csv. The appended object does not have a property that corresponds to the following column: UserName. To proceed with mismatched properties, add the -Force switch and retry.

As you can see, you can use the -Force parameter to force mismatched fields.

New Parameters for Get-ChildItem

There are a number of  new parameters for Get-ChildItem, implemented as simple switches. The key switches are : -Directory, -File and -Attributes.

The -Directory switch gets folders only. It has the following syntax.

-Directory [<SwitchParameter>]

There is a corresponding -File switch:

-File [<SwitchParameter>]

To get only directories, use the -Directory parameter and omit the -File parameter. To exclude directories, use the -File parameter and omit the Directory parameter, or use the Attributes parameter.

The -Attributes parameter allows you to specify file/folder parameters and get back just those that meet the parameter type. with syntax as follows:

-Attributes <FileAttributes]>

Gets files and folders with the specified attributes. This parameter supports all attributes and lets you specify complex combinations of attributes.

For example, to get non-system files (not directories) that are encrypted or compressed

Get-ChildItem -Attributes !Directory+!System+Encrypted, !Directory+!System+Compressed

To find files and folders with commonly used attributes, use the -Attributes parameter, or the Directory, File, Hidden, ReadOnly, and System switch parameters.

The -Attributes parameter supports the following attributes: Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary. For a description of these attributes, see the FileAttributes enumeration at http://go.microsoft.com/fwlink/?Link201508.

Three other new and switches for Get-Child Item are:

-Hidden, -ReadOnly, -System

Setting any of these retrieves only the files and folders with the relevant attribute. These switches can be used in combination. For simple use, using just these switches may be easier than using the -Attributes switch.

# Example

Get-ChildItem -path c:\foo -Hidden -ReadOnly

# Gets any folder of file that is both hidden and read/only

Get-Command: New Capability

Get-Command will now let you search for commands in three different ways:

  1. By Command Type
    • Types available are: Alias, Function, Filter, Cmdlet, ExternalScript, Application, Script, Workflow, All
  2. 2. By Command Capability
    • Capabilities available are:  Unknown, Cmdlet, Script, Workflow, CIM, ScripFile, Application
    • The ability to search by Capability is a new feature of Get-Command.
  3. By Command Verb and/or Noun and Module
    • See the following article on examples of the various usages of this command:  Get-Command Examples

Note, too, that Get-Command will list all the commands available from all installed modules, regardless of whether the modules have been loaded into the current session or not.

Restart-Computer -Wait

Restart-Computer now has a Wait parameter, with associated Delay, Timeout, and For parameters.

The following table explains how these can be used:

Parameter

Description

Wait

Prevents any further commands from running until the specified computers have restarted.

For

Considers the computer to have restarted when the specified resources are available. Valid values are WMI, WinRM, and PowerShell.

Timeout

Specifies the amount of time (in seconds)  to wait for the computer to restart. When the timeout interval expires, subsequent commands are run even if the computer is not restarted.

Delay

Determines how often Windows PowerShell queries the service that is specified by the For parameter to determine whether it is available after the computer is restarted. The default value is 5 (seconds).

Credential support for New-PSDrive

There is now credential support for the New-PSDrive cmdlet. Although this parameter was there in Version 2, it was not implemented, and resulted in an error such as :

The provider does not support the use of credentials. Perform the operation again without specifying credentials.

At line:1 char:1

+ <<<< New-PSDrive -Name x -PSProvider FileSystem -Root C:\Scripts -Credential

 (Get-Credential)

 + CategoryInfo : NotImplemented: (:) [], PSNotSupportedException

 + FullyQualifiedErrorId : NotSupported

This is now fully implemented.

# Example:

New-PSDrive -Name x -PSProvider FileSystem -Root C:\Scripts -Credential (Get-Credential)

This code will now work as expected.

Get-Content -Raw parameter

Get-Content now has a -Raw parameter, which causes it to read text files in a text stream, keeping newline character intact. The resulting type is different too: Get-Content returns a string type, instead of and array type, when the -Raw switch parameter is specified.

# Example:

$t = Get-Content 'test.txt' -Raw

$t.gettype()

# Output:

IsPublic IsSerial Name BaseType


True True String System.Object

Out-Gridview More Functional

Out-GridView now has three additional parameters: Wait, PassThru, and OutputMode. Of these, OutputMode is the most interesting.

Wait simply does what it says: It will wait until the Out-Gridview window is closed before continuing code execution.

OutputMode has three options: Single, Multiple, or None. None is not useful, because it causes Out-Gridview to behave as if you had not specified -OutputMode.   But Single and Multiple allow you to select from a list, and this selection will be passed further down the pipeline.

Edit (@mjolinor) The None value seems useless, because it causes the cmdlet to behave as if you had not specified -OutputMode at all. I now believe it was necessary to include this option because of the Default Parameter Values feature. Used in command line work, the cmdlet is most useful with an Output mode of "Multi". This option allows multiple or single item select (but does not enforce single item selection). To make this the default, add it to the default parameter definitions:

 $PSDefaultParameterValues  = @{'Out-Gridview:Outputmod'='Multi'}

Having done this, you will now need to explicitly use -OutputMode None if you want Out-Gridview to operate in the normal default manner.

An example of this is as follows: We call Get-Process with no arguments, to present an Out-Gridview of all the running processes. The user can then select either a single item (Single), or multiple items (Multiple), and when the user clicks OK, these selected items are sent down the pipeline for further processing, in this case to send these to Get-Process again for more detail.

# Example:

Get-Process | Out-GridView -OutputMode Multiple | Get-Process | Format-List *

If the user clicks Cancel, nothing is passed down the pipeline.

Credits

This article was originally written by @Bigteddy, with significant edits by @DoctorDNS

See Also