Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Instant Windows PowerShell Guide

You're reading from  Instant Windows PowerShell Guide

Product type Book
Published in Nov 2013
Publisher Packt
ISBN-13 9781849686785
Pages 86 pages
Edition 1st Edition
Languages
Author (1):
Harshul Patel Harshul Patel
Profile icon Harshul Patel
Toc

Dealing with PSDrive (Simple)


A few changes have been introduced with respect to files and drives in Windows PowerShell Version 3.0. Windows PowerShell has a built-in drive mechanism for things such as registry, certificate, alias, function, variable, and so on. You can treat these drives as filesystems.

Getting ready

There are some functionality changes when we create a new custom PSDrive using PowerShell Version 3.0. Let's walk through them.

New-PSDrive

This CMDLET creates a new temporary or persistent drive with various Windows PowerShell provider types.

How to do it...

  1. You can get the list of default Windows PowerShell providers by executing the following CMDLET:

    PS C :\> Get-PSProvider
    Name         Capabilities                         Drives
    ----         ------------                         ------
    Alias        ShouldProcess                        {Alias}
    Environment  ShouldProcess                        {Env}
    FileSystem   Filter, ShouldProcess, Credentials   {C, D, E, F}
    Function     ShouldProcess                        {Function}
    Registry     ShouldProcess, Transactions          {HKLM, HKCU}
    Variable     ShouldProcess                        {Variable}
    Certificate  ShouldProcess                        {Cert}
    WSMan        Credentials                          {WSMan}
    
  2. The following command statement creates a new persistent PSDrive named T from the location \\FileSrv\Temp; it uses the credential PSDomain\PSAdmin and it prompts for a password:

    PS C :\> New-PSDrive -Name T -PSProvider FileSystem -Root \\FileSrv\Temp -Credential PSDomain\PSAdmin -Persist
    

    The Credential parameter is generally used to provide explicit user credentials that have the privilege to create new PSDrives. By default, it takes the current user session credential.

    Using the Persist parameter name, we ensure that the new PSDrive acts as a normal filesystem drive with a new drive letter, for example, T. You can further use the T drive using file explorer or the net use utility.

How it works…

Let's get the full information of the PowerShell drive named T earlier:

PS C :\> Get-PSDrive -Name T
Name         Provider        Root
----         --------        ----
T            FileSystem      T:\

In Version 3.0, the following are a few functionality changes with respect to the New-PSDrive CMDLET.

  • -Persist: Using the –Persist parameter name with the New-PSDrive CMDLET, you can create mapped network drives that are not limited to the current Windows PowerShell sessions. They are stored in the Windows configuration and, moreover, you can open them using file explorer or the net use utility.

  • -Credential: If you are using the UNC path to create New-PSDrive, you can leverage the Credential parameter name that is introduced in Windows PowerShell v3.0 along with the New-PSDrive CMDLET. Apart from the UNC path, the Credential parameter name is not mandatory with all the other possible scenarios.

  • External drives: If you attach any external drive to your local computer, it automatically creates a new PSDrive that represents your external drive. We need not restart our machine to see these changes in effect. Likewise, if you remove the drive, Windows PowerShell automatically deletes the PSDrive that was mapped with your external drive earlier.

Note

Issues with mounting and unmounting VHDs using the FileSystem provider in Windows PowerShell 4.0 have been fixed. Windows PowerShell is now able to detect new drives when they are mounted in the same session.

There's more…

There are couple of more parameters that are introduced with various CMDLETs in Version 3. The information is as described in this section.

Get-Credential

In Version 3.0, the Get-Credential CMDLET has one additional parameter name called the Message parameter. Using the Message parameter, you can specify customized messages to the users on prompted credential windows.

For example:

PS C :\> Get-Credential -Message "Enter your valid Username and Password" -UserName PSDomain\PSAdmin

Select-Object

The Select-Object CMDLET is generally used to select objects or object properties. In Version 3.0, it is known by a new parameter name called Wait, which is used to turn off the object optimization.

Usually, Windows PowerShell has the behavior to generate all objects and throw them to the pipeline flawlessly. If you use Select-Object with either the First or Index parameter and proceed with the Wait parameter, the console will stop creating further objects after the specified value.

PS C :\> Get-Process | Select-Object Name -First 5 –Wait

The previous command statement retrieves the first five process objects instead of generating all the process objects for running processes.

Note

With PowerShell v4.0, Select-Object –Expand no longer fails or generates an exception if the value of the property is null or empty.

Import-Csv

In the previous versions of Windows PowerShell, if you have the header row value as a null value, the Import-Csv CMDLET fails. But, in Version 3.0, the Import-Csv CMDLET has the Header parameter name, which helps to overcome this error.

The Header parameter name manually adds the header row to the CSV file before importing it to the console. It gives a warning message with the output displayed.

For example, assume there is a CSV file named Services.csv placed in a present directory with all the information about the running services stored in it with a null header row value:

PS C :\> $header = "Current State", "Service Name", "Description"

The $header variable contains manually defined header row values.

PS C :\> Import-Csv –Path .\Services.csv -Header $header 

The preceding command statement manually attaches header row values and imports the specified CSV file to the console.

In PowerShell v3.0, the Import-Csv CMDLETs don't work well if your CSV file has any blank lines; the output spits empty objects. But, in PowerShell v4.0, blank lines are ignored and the Import-Csv CMDLET works as expected.

Dealing with JSON-formatted objects

In Version 3.0, the team has extended covert CMDLET's chains to ConvertTo-Json and ConvertFrom-Json. In previous versions, we had similar CMDLETs, for example, ConvertTo-Csv, ConvertFrom-Csv, ConvertTo-Html, ConvertFrom-Html, and so on.

The ConvertTo-Json CMDLET converts Windows PowerShell objects to JSON-formatted string objects.

PS C :\> Get-Process | ConvertTo-Json

The preceding command statement returns JSON-formatted process string objects. The ConvertTo-Json CMDLET converts all process objects into JSON-formatted string objects.

The ConvertFrom-Json CMDLET behaves exactly opposite to the ConvertTo-Json CMDLET. It converts JSON-formatted string objects to custom Windows PowerShell objects.

PS C :\> Get-Process | ConvertTo-Json | ConvertFrom-Json

The preceding command statement returns custom process objects. The ConvertTo-Json CMDLET converts all process objects into JSON-formatted string objects. Again, the ConvertFrom-Json CMDLET converts all JSON-formatted string objects into custom Windows PowerShell objects.

Note

ConvertTo-Json and ConvertFrom-Json can now accept terms within double quotes and its error messages are now localizable.

Windows PowerShell custom object enhancements

In Version 2.0, we have the New-Object CMDLET to create Windows PowerShell objects as syntaxes:

PS C :\> $Objv2 = New-Object –TypeName PSObject -Property @{x=1; y=2; z=3}

This creates a new Windows PowerShell object with three mapped property values.

PS C :\> $Objv2 | Format-List
y: 2
z: 3
x: 1

In Version 3.0, we have the PSCustomObject type to create Windows PowerShell custom object as syntaxes:

PS C :\> $Objv3 = [PSCustomObject]@{x=1; y=2; z=3}

This also creates a custom Windows PowerShell object with three mapped values.

PS C :\> $Objv3 | Format-List
x: 1
y: 2
z: 3

In both the cases, it creates PSCustomObject using NoteProperties.

PS C :\> $Objv3 | Get-Member

It lists out all the methods and node properties with respect to PSCustomObject.

TypeName: System.Management.Automation.PSCustomObject
Name            MemberType     Definition
----            ----------     ----------
Equals          Method         bool Equals(System.Object obj)
GetHashCode     Method         int GetHashCode()
GetType         Method         type GetType()
ToString        Method         string ToString()
x               NoteProperty   System.Int32 x=1
y               NoteProperty   System.Int32 y=2
z               NoteProperty   System.Int32 z=3

The only benefit we get out of this is that it maintains the property order, rendering it to be utilized reliably.

You have been reading a chapter from
Instant Windows PowerShell Guide
Published in: Nov 2013 Publisher: Packt ISBN-13: 9781849686785
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}