What is New in Powershell 6.0


PowerShell: PowerShell for every system!

Version 6 of PowerShell is finally released to the final version on January 19, 2018. With that, go out "Windows PowerShell" and put "PowerShell" at the short! Eyelid

Can I say it as "PowerShell Core 6.0"

Although rename may seem trivial, it is not! We have a turning point in our favorite Shell's history, in this version, Microsoft is no longer supported by the PowerShell and .NET Framework on Net Core. What is a big change, because PowerShell (and .NET Core) is not an open source, so:

To download PowerShell Core on Windows, see https://aka.ms/getps6-windows.
To download PowerShell Core on macOS and Linux, see https://aka.ms/getps6-linux.

You can contribute to the development of PowerShell and access its source code freely, PowerShell is a multi-platform and can be installed: Windows, Linux, MacOS, and even Raspberry Pi!

Hey What a change!

Small flat, however, this change of architecture can affect your old script. You have to test them because some features may not be missing because the .NET Core does not have all the operational coverage.

Another good news: You can install PowerShell 6 without leaving anything in the previous version of Windows PowerShell. Indeed, PowerShell 6 operating system separately installs in a directory and it embeds .NET Core. Establishing is as minimal as a prerequisite!

What's the difference between Windows PowerShell and PowerShell Core?

Windows Powershell Powershell Core
Built on top of .NET FrameworkBuilt on top of .NET Core
Available on WindowsPowerShell Core is cross-platform, available on Windows, macOS, and Linux
PowerShell is launched as powershell.exePowerShell Core is launched as pwsh.exe
$PSVersionTable.PSEdition set to Desktop$PSVersionTable.PSEdition set to core
This means Windows PowerShell’s .NET usage is limited to the functionality exposed by the .NET Framework and .NET StandardPowerShell Core is limited to the functionality exposed by .NET Core and .NET Standard

Example

Example

Hello World

Copy and Try it

Try it Yourself

What's New in Windows PowerShell 5.0 Windows PowerShell 5.0 includes significant new features that extend its use, improve its usability, and allow you to control and manage Windows-based environments more easily and comprehensively.

  • Contains updates for Windows PowerShell and Windows PowerShell ISE.
  • Package Management cmdlets.
  • Network Switch cmdlets.
  • Windows PowerShell Desired State Configuration (DSC)

note: You will need .NET Framework 4.5.

Example

Example

# Windows PowerShell Version Check
Clear-Host
$Host

Copy and Try it


Try it Yourself

PowerShell Version 5 New Feature: New Parameters added to the New-DscCheckSum and Test-DscConfiguration Cmdlets

PowerShell Version 5 New Feature: SkipLast Parameter added to Select-Object

We will see how it helps in getting only table without header and footer information while fetching windows roles, So that you can load data into some object and then you can work on it.

Scenario 1 : if you fire below command then you will get data with header and footer

Example

Example

dism /online /get-features /format:table 

Copy and Try it


Try Example

Example

Example

Deployment Image Servicing and Management tool
Version: 10.0.17134.1

Image Version: 10.0.17134.165

Features listing for package : Microsoft-Windows-Foundation-Package~31bf3856ad364e35~amd64~~10.0.17134.1


----------------------------------------------------- | --------
Feature Name                                          | State   
----------------------------------------------------- | --------
LegacyComponents                                      | Disabled
DirectPlay                                            | Disabled
SimpleTCP                                             | Disabled
SNMP                                                  | Disabled
WMISnmpProvider                                       | Disabled
MicrosoftWindowsPowerShellV2Root                      | Disabled
MicrosoftWindowsPowerShellV2                          | Disabled
.
.
.
Internet-Explorer-Optional-amd64                      | Enabled 

The operation completed successfully.

PS C:\WINDOWS\system32> 

Copy and Try it


Try it Yourself

Scenario 2 : if you fire below command then you will get data without header and footer using Skip top 12 lines of header and last 2 lines of footer.

Example

Example

Example

dism /online /get-features /format:table | Select -skip 12| Select -SkipLast 2

Copy and Try it


Try it Yourself

Output

Example

LegacyComponents                                      | Disabled
DirectPlay                                            | Disabled
SimpleTCP                                             | Disabled
SNMP                                                  | Disabled
WMISnmpProvider                                       | Disabled
MicrosoftWindowsPowerShellV2Root                      | Disabled
MicrosoftWindowsPowerShellV2                          | Disabled

Copy and Try it


After that I use this info for enable and disable role using User interface using c#.

c# Example

Example

string fileName = "DismPS2.ps1";
string pathToCreate = AppDomain.CurrentDomain.BaseDirectory + fileName;

if (!File.Exists(pathToCreate))
{
	// Create a file to write to.
	using (StreamWriter sw = File.CreateText(pathToCreate))
	{
		foreach (var feature in EnableFeatureList)
		{
			sw.WriteLine("dism /online /get-features /format:table | Select -skip 12| Select -SkipLast 2");
			log.Info("dism /online /get-features /format:table | Select -skip 12| Select -SkipLast 2");
		}
	}
}

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
var path = @"& '" + AppDomain.CurrentDomain.BaseDirectory + fileName + "'";
startInfo.Arguments = path;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();

output = process.StandardOutput.ReadToEnd();
errors = process.StandardError.ReadToEnd();
var featureCollection = output.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
var dict = new Dictionary();
foreach (string s in featureCollection)
{
	dict.Add(
		s.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)[0].Trim(),
		s.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim());
}

Copy and Try it


To disable feature use below command

Example

 
dism /NoRestart /Online /Enable-Feature /FeatureName:IIS-BasicAuthentication

Copy and Try it


OR to disable feature use below command

c# Example

Example

dism /NoRestart /Online /Disable-Feature /FeatureName:IIS-BasicAuthentication

Copy and Try it


Powershell 4.0 Released


Windows PowerShell 4.0 Released for Windows 7, Windows 2008 R2, and Windows Server 2012

I've read through TechNet forum threads where customers scoffed that somehow Microsoft would be able to make PowerShell 4.0 available in October 2013 - so soon after the release of Windows 8.1 and the R2 wave. But, it happened, and it's here.

PowerShell 4.0 comes preinstalled for Windows 8.1 and Windows Server 2012 R2, but there are those who still prefer Windows 7 and other earlier server operating systems. So, it's great to see that Microsoft has finally released PowerShell 4.0 as part of the Windows Management Framework (WMF) 4.0 release. The release supports Windows 7, Windows Embedded Standard 7, Windows Server 2008 R2, and Windows Server 2012.

WMF 4.0 actually includes a bunch more than just PowerShell 4.0, but most will be downloading this latest release specifically for the new cmdlets and functionality that PowerShell 4.0 offers. However, here's everything that is included in WMF 4.0:

WMF 4.0 actually includes a bunch more than just PowerShell 4.0, but most will be downloading this latest release specifically for the new cmdlets and functionality that PowerShell 4.0 offers. However, here's everything that is included in WMF 4.0:

  • Windows PowerShell
  • Windows PowerShell ISE
  • Windows PowerShell Web Services
  • Windows Remote Management (WinRM)
  • Windows Management Instrumentation (WMI)
  • Server Manager WMI provider
  • Windows PowerShell Desired State Configuration (DSC) Download WMF 4.0 here: Windows Management Framework 4.0 P.S. WMF 4.0 also requires Microsoft .NET 4.5 be installed first.

Now that Server 2012 R2 has been released, PowerShell 4.0 has also become available. Unfortunately it is not yet available as a standalone download, older operating systems will have to wait for the Windows Management Framework to become available as an optional download.
Some notable features that are available for PowerShell 4.0 are as follows:

  1. Desired State Configuration - This allows for configuration of a computer in a way that was previously not possible with PowerShell.
  2. Remote debugging - In PowerShell 4.0 it is now possible to set breakpoints for PSSessions, which allows for easier debugging of scripts that are running remotely
  3. Get-Process now supports User names - No more Get-WmiObject -Class Win32_Process!!
  4. Several language improvements and bug fixes.
    For a full list of all changes have a look a the corrosponding TechNet Article which is available here: what's new in windows powershell

PowerShell Providers


PowerShell Providers are .NET programs that allow us to work with data stores as if they were mounted drives. This simplifies accessing external data outside the PowerShell environment. For example, we can access the registry as if it were a file system. This translates to being able to use the same cmdlets as working with files and folders, which are shown in the table below.

Cmdlet

Alias

Cmd Commands

Descritption

Get-Location

gl

pwd

Current Directory.

Set-Location

sl

cd, chdir

Change current directory.

Copy-Item

cpi

copy

Copy Files.

Remove-Item

ri

del

Removes a File or directory.

Move-Item

mi

move

Move a file.

Rename-Item

rni

rn

Rename a file.

New-Item

ni

n/a

Creates a new empty file or folder.

Clear-Item

cli

n/a

Clears the contents of a file.

Set-Item

si

n/a

Set the contents of a file.

Mkdir

n/a

md

Creates a new directory.

Get-Content

gc

type

Sends contents of a file to the output stream.

Set-Content

sc

n/a

Set the contents of a file.

Take a look at the "about file" for more information:

Get-Content $PSHOME\about_Provider.help.txt<enter>

SHORT DESCRIPTION
Windows PowerShell providers provide access to data and components that
would not otherwise be easily accessible at the command line. The data
is presented in a consistent format that resembles a file system drive.

LONG DESCRIPTION
Windows PowerShell providers are .NET programs that make the data in a
specialized data store available in Windows PowerShell so that you can
easily view and manage it.

The data that a provider exposes appears in a drive, much like a hard drive.
You can use any of the built-in cmdlets that the provider supports to manage
the data in the provider drive, in addition to custom cmdlets that are
designed especially for the data.

The providers can also add "dynamic parameters" to the built-in cmdlets.
These are parameters that are available only when using the cmdlet with the
provider data.

A Provider is also called a "snap-in" which is a dynamic link library (.dll) built into PowerShell. A library is code that instructs PowerShell to preform an action when we execute a command. What this means is that we no longer have to write code, as we did in VBScript, to connect to the registry. The code is provided for us, simplifying our efforts. New and Custom Providers can be written, but this goes beyond the scope of this tutorial. The PowerShell Software Developers Kit provides documents should you wish to build your own Providers.

List Providers available in PowerShell

Using the "Get-PSProvider" cmdlet, we obtain a list of available PowerShell Providers:

Get-PSProvider<enter>

PowerShell Training PSProvider Image

PowerShell Providers

Image 5.0

Here is the list of the PoweShell Providers available:

  • Alias
  • Environment
  • FileSystem
  • Function
  • Registry
  • Variable
  • Certificate

PowerShell Drive "PSDrive"

We connect to PowerShell Providers by mounting the Providers PowerShell Drive(PSDrive). Most Providers have only one PSDrive, the exceptions are the FileSystem Provider(depends on the number of drives on the system) and the Registry Provider(HKLM and HKCU). Here is how to get a list of the available PowerShell Drives:

Get-PSDrive<enter>

PowerShell Training PSdrive

PS Drives

Image 5.1

The "Name" column reveals the PSDrives available on the system. We connect to each Provider using the PSDrive appended with a colon (:). Note: The example in image 5.1 shows the PSDrives without the (:) so you have to remember to use it when mounting a PSDrive.

Let's use this PowerShell training session to explore each of these providers.

The PowerShell Alias Provider

We discussed what an Alias "is" in PowerShell tutorial 3. The Alias Provider enables access to all the aliases in PowerShell. To mount a PSDrive we use the "Set-Location" cmdlet. In this example, we want to mount the "Alias:" PSDrive. Don't Forget the colon(:).

Set-Location Alias:<enter>

PowerShell Training Alias Provider Image

Set Alias Drive

Image 5.2

As shown in image 5.2, we are now connected to the "Alias:" PSDrive. Just a quick note, PSDrives are only available in the PowerShell environment. You would not able to access the "Alias:" drive from a legacy windows command shell.

Now that we are mapped to the Alias: PSDrive we can use the same cmdlets as working with files and folders.

Eample 1. View a list of all aliases.

Get-ChildItem<enter>

PowerShell Training gci

All Aliases

Image 5.2

Example 2. List the properties and methods.

Get-ChildItem | Get-Member<enter>

PowerShell Training Alias GM

Properties and Methods

Image 5.3

Example 3. Use the -Name parameter to list all Aliases that start with the letter "R". PowerShell supports the use of wild cards() to filter the results.

Get-ChildItem -Name R*<enter>

PowerShell Training Alias Name Parameter

Name Parameter

Image 5.4

Example 4. Building on example 3; instead of using a parameter to filter results, let's filter using the "name" property of the Alias object.

Get-ChildItem | Where-Object {$_.name -like "R*"}<enter>

PowerShell Training Alias Filter.

Where-Object Filter

Image 5.5

We have worked a lot with aliases in a previous tutorial, so I'm going to move along to the next Provider. Feel free to use the commands listed in the table (above) and experiment with the Alias Provider.

The PowerShell Environment Provider

You may already be familiar with what the Environment Providers is, it is equivalent to running the "set" command in a windows CMD command shell. It provides a listing of all the environment variable defined on the system. Graphically, you can view the environment variables by going to System Properties -> Advanced Tab -> Click the "Environment Variables" button.

PowerShell Training Evironment Variables

ENV Variables

Image 5.6

Example 1. List Environment Variables

1. Get list of available PowerShell Providers.

Get-PSDrive<enter>

2. Map PSDrive to Environment Provider.

Set-Location env:<enter>

3. Get listing of Environment Variables.

Get-ChildItem<enter>

PowerShell Training Get Environment Variable

List Variables

Image 5.7

Example 2. Obtain the value of an Environment Variable

1. Output the value of the "OS" variable.

Get-ChildItem OS<enter>

2. Output all properties for the "OS" variable.

Get-ChildItem OS | Format-List *<enter>

Example 3. Create a new Environment Variable

1. Create a new variable using the "New-Item" cmdlet. Let's call the new variable "MyVariable" and give it a value of "This is my new variable." The Path argument will be a dot (.) meaning current location, which would be "env:"

New-Item -Path . -Name MyVariable -Value "This is my new variable"<enter>

PowerShell Training New Environment Variable

Create Variable

Image 5.8

Use "Get-ChildItem" cmdlet to verify that the new variable exists.

Example 4. Renaming the Environment Variable

1. Let's rename the "MyVariable" variable to "MyRenVar."

Rename-Item -Path env:MyVariable -NewName MyRenVar<enter>

2. Now use the "Get-ChildItem" cmdlet to verify the change.

Get-ChildItem<enter>

Example 5. Removing the Environment Variable

1. To remove the "MyRenVar" variable we us the "Remove-Item" cmdlet.

Remove-Item MyRenVar<enter>

2. Use "Get-ChildItem" to verify the variable has been removed.

Get-ChildItem<enter>

PowerShell File System Provider

By default, the File System Provider is accessed when PowerShell is launched. The File System Provider allows you to create, retrieve, and remove files and folders. Also, the File System Provider allow you to modify files by either appending or overwritting data. This section of the PowerShell Providers tutorial explains how to do this.

Example 1. Listing Files and Directories

1. Connect to the File System Provider. Close and re-launch PowerShell -or- connect to the File System Provider using the "Set-Location" cmdlet. Use the backslash (\) character to connect to the root of C: Drive

Set-Location C:\<enter>

2. List Files and Directories under the root of C: Drive.

Get-ChildItem<enter>

3. List Files and Directories including sub-direcories.

Get-ChildItem -Recurse<enter>

If your file system is large, the command in step 3 may take awhile. Use "Ctrl + C" to stop processing commands in PowerShell, just like you did in CMD command shell.

What is the "Mode" column? 5 bits of information you need to know.

· First entry is either "d" (indicates item is a directory) or "-" (indicates item is a file).

· The last 4 entries present the properties of a File and/or Directory (a r h s). "a" = archive bit is set, "r" = read only, "h" = hidden, and "s" = system. A "-" in any of these entries means the bit is not set.

PowerShell Training Mode

Mode

Image 5.9

Note: By default, "Get-ChildItem" cmdlet or an Alias does not show hidden files and Directories. To show hidden files use the "-force" parameter.

Get-ChildItem -Force<enter>

As stated earlier in this PowerShell tutorial, Providers allow the use of the same cmdlets. Here is a second look at the cmdlet table, so that you don't have to scroll back to the top.

Cmdlet

Alias

Cmd Commands

Descritption

Get-Location

gl

pwd

Current Directory.

Set-Location

sl

cd, chdir

Change current directory.

Copy-Item

cpi

copy

Copy Files.

Remove-Item

ri

del

Removes a File or directory.

Move-Item

mi

move

Move a file.

Rename-Item

rni

rn

Rename a file.

New-Item

ni

n/a

Creates a new empty file or folder.

Clear-Item

cli

n/a

Clears the contents of a file.

Set-Item

si

n/a

Set the contents of a file.

Mkdir

n/a

md

Creates a new directory.

Get-Content

gc

type

Sends contents of a file to the output stream.

Set-Content

sc

n/a

Set the contents of a file.

Example 2. Using "Get-Location" Cmdlet

Use "Get-Location" to show current directory.

Get-Location<enter>

Using Alias and CMD Command.

gl<enter>

pwd<enter>

Example 3. Creating files and Directories

Use "New-Item" cmdlet to create a New Directory.

New-Item -Path C:\NewFolder -Type Directory<enter>

A cool thing about PoweShell, it will assist you when you leave out required information. For example, let's say your creating the directory in the example above but you forget the -Type paramter.

New-Item -Path C:\NewFolder <enter>
PowerShell will prompt you for the missing parameter...
Type:

Continuing with the "New-Item" cmdlet, let's create a file in our new directory.

New-Item -Path C:\NewFolder\NewFile.txt -Type File<enter>

Example 4. Move NewFile to the root of "C:\" using "Move-Item" cmdlet

Move-Item -Path C:\NewFolder\NewFile.txt C:\<enter>

Verify file moved.

Get-ChildItem N*<enter>

Example 5. Renaming Files and Directories

Let's rename the NewFile.txt to RenFile.txt.

Rename-Item -Path C:\NewFile.txt RenFile.txt<enter>

Verify the file has been renamed.

Get-ChildItem R*<enter>

Rename Directroy NewFolder to RenFolder.

Rename-Item -Path C:\NewFolder RenFolder<enter>

Again, verify the change.

Get-ChildItem R*<enter>

Example 6. Removing Files and Directories

in our last example of this PowerShell training section, let's remove the RenFolder and RenFile.txt. Just for fun, let's add the -confirm parameter so that PowerShell prompts us to confirm the action.

Remove-Item -Path C:\RenFile.txt -Confirm<enter>

Press "Y" to confirm the deletion of the file and verify the files has been removed.

Get-ChildItem R*<enter>

You should still see the RenFolder but the RenFile is no longer present. Now remove the directory.

Remove-Item -Path C:\RenFolder -Confirm<enter>

Again, press "Y" to confirm and verify Directory has been removed.

Get-ChildItem R*<enter>

There are other cmdlets such as "Clear-Item" and "Set-Item" that enable you to work with data within files. Use "Get-Help" on these cmdlets to read about how to use these cmdlets in the PowerShell FileSystem Provider. I personally like to use "Get-Content" to output a files contents to the screen and "Set-Content" to add information to a file.

PowerShell Function Provider

PowerShell has a set of Functions specified in the PowerShell engine. The PowerShell Function Provider allows us to access these functions using, hope this is starting to sound redundant, the same cmdlets as working with Files and Folders.

Not familiar with what a function is? A function allows you to make calls to a block of code. When scripting, if you notice that you are using the same code over and over (within the same script), you should consider creating a function. A function would reduce the amount of code and keep your scripts clean and readable. The examples in the section will help define a Function. Be aware that we are discussing Functions defined in PowerShell, not how to create PowerShell Functions. Creating your own Functions comes later in the PowerShell Scripting tutorials.

Example 1. Listing Functions

1. Use "Set-Location" cmdlet and connect to the PowerShell Function Provider's PSDrive.

Set-Location Function:<enter>

2. You should be familiar with what cmdlet comes next...

Get-ChildItem<enter>

PowerShell Training List Functions

Functions Provider

Image 5.10

Image 5.10 displays the Functions that are defined in PowerShell. "Name" is the name given to the function and the "Definition" is the code that runs when we call the name.

What does it mean to "call" a function? In PowerShell, we are only required to type a function name and the corresponding code will execute. For example, typing "set-Location C:" navigates to the root of C: drive. We can also navigate to the root of C: just by typing(calling) the "C:" function name. PowerShell runs the "Set-Location C:" code which places us at the root of C: drive. Let's take a look at another example.

Example 2. Viewing the Code of a PowerShell Function

1. We are going to use the "Get-Content" cmdlet to view the code block of the Clear-Host Function.

Get-Content Clear-Host<enter>

Output:

$spaceType = [System.Management.Automation.Host.BufferCell]; $space = [Sys
tem.Activator]::CreateInstance($spaceType); $space.Character = ‘ ‘; $space
.ForegroundColor = $host.ui.rawui.ForegroundColor; $space.BackgroundColor
= $host.ui.rawui.BackgroundColor; $rectType = [System.Management.Automatio
n.Host.Rectangle]; $rect = [System.Activator]::CreateInstance($rectType);
$rect.Top = $rect.Bottom = $rect.Right = $rect.Left = -1; $Host.UI.RawUI.S
etBufferContents($rect, $space); $coordType = [System.Management.Automatio
n.Host.Coordinates]; $origin = [System.Activator]::CreateInstance($coordTy
pe); $Host.UI.RawUI.CursorPosition = $origin;

So my guess is that you would be more inclined to calling the "Clear-Host" function than actually typing the code required to clear the screen. Can you see how calling a function reduces the amount of code written in the script?

Before getting in too deep and making your head swim, I'm going to end this discussion about this Provider until we talk more about PowerShell Functions and Scripting. For now, let's move on to the coolest PowerShell Provider in the world!!!

The PowerShell Registry Provider

If you ever wanted to work with the registry with the same ease as working with the file system, your wish has come true. The Registry Provider allows us to connect to two PSDrives; HKCU (HKEY_CURRENT_USER) and HKLM (HKEY_LOCAL_MACHINE). With the Registry Provider we can:

  • Navigate the registry.
  • Search the registry.
  • Create new registry keys.
  • Delete registry keys.
  • Add new values.
  • Modify existing values.
  • Manage ACLs (Access Control Lists).

Eample 1. Connect to the HKLM PSDrive and List Registry Keys.

1. The two PSDrives we can connect to are HKLM and HKCU. Verify this by checking which PSDrives are available.

Get-PSDrive<enter>


Image 5.11

PowerShell Training PSdrive

Registry Provider

2. Connect to HKLM PSProvider using the "Set-Location" cmdlet.

Set-Location HKLM:<enter>

3. We can also connect anywhere in the path. Let's connect to the SOFTWARE Key:

Set-Location HKLM:\Software<enter>

4. From the Software location let's list the keys available.

Get-ChildItem<enter>

Image 5.12

PowerShell Tutorial - HKLM

HKLM

We're all familiar with the warnings of making changes to the Registry. Since I wish to only help and do no harm, I'm not going to provide examples of making registry changes. Just note that you can use the same cmdlets used when working with all PowerShell Providers.

Cmdlet

Alias

Cmd Commands

Descritption

Get-Location

gl

pwd

Current Directory.

Set-Location

sl

cd, chdir

Change current directory.

Copy-Item

cpi

copy

Copy Files.

Remove-Item

ri

del

Removes a File or directory.

Move-Item

mi

move

Move a file.

Rename-Item

rni

rn

Rename a file.

New-Item

ni

n/a

Creates a new empty file or folder.

Clear-Item

cli

n/a

Clears the contents of a file.

Set-Item

si

n/a

Set the contents of a file.

Mkdir

n/a

md

Creates a new directory.

Get-Content

gc

type

Sends contents of a file to the output stream.

Set-Content

sc

n/a

Set the contents of a file.

I will show you one very cool example of using the "Get-ChildItem" cmdlet to list installed Hot Fixes on a system:

Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\HotFix"<enter>

Note: In the -Path parameter, quoting the path statement was required as there is a space between Windows and NT.

You should now see a list of "Hot Fixes" that have been installed on the system. Staying with the theme of this PowerShell tutorial, I'm going to use the "CD" alias to navigate to one of the "Hot Fix" keys. Choose any hot fix you wish to enumerate.

CD KB888240<enter>

Next question should be... How do we enumerate the information inside the registry key? Simply use the "Get-ItemProperty" cmdlet.

Get-ItemProperty .<enter>

I used the "." as we are currently working within the registry path location. You can also get the properties using the -Path parameter. Here's the example:

Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\HotFix\KB888240″<enter>

Now we see all the properties, how about just a specific property?

Get-ItemProperty . -Name Comments<enter>

Create and Remove a New Registry Key and Property

First, Let's work from the root of SOFTWARE.

Set-Location -Path HKLM:\SOFTWARE<enter>

Create new registry Key and Default Property using "New-Item" cmdlet from the table.

New-Item -Name Test -Value "This is a test string"<enter>

Verify "Test" key exists

Get-ChildItem T*<enter>

Verify the default property has the string value we created.

Get-ItemProperty -Path .\Test<enter>

Next, Let's delete the new key using the "Remove-Item" cmdlet.

Remove-Item Test<enter>

Verify the key has been removed.

Get-ChildItem T*

Using the Registry Provider we are able to navigate, enumerate, create, and delete registry items just like files and folders.

Real-World Example: An associate of mine started working for a banking institution. We're talking multiple locations around the United States. His boss didn't like the naming convention for network printers as they provided no clue of printer type or location. His task was to create new print queues (with a new naming convention) and cut all the user over to the new print queues. Because he was dealing with multiple locations, it was impossible for a tech to be on-site to remap clients to the new print queues. Another requirement was to automate the process so that clients would not experience down time when printing. He told the boss... "No Problem."

I'm only going to describe what he did in pseudo code as it would take another tutorial to examine his script. Network Print Queues are stored in the registry as a UNC (\\PrintServer\PrinterName). He created a second print queue for each printer on all his print servers. Created a printer script which used an array to store the old printer names and their new counterparts. The script would change the registry setting from \\PrintServer\OldQueue to \\PrintServer\NewQueue while also preserving the default printer setting. He replicated the new script to all Domain Controllers in his environment and edited the company's logon script to call the printer script. When the printer script runs, it looks at the registry keys and if it finds reference to an old print queue name, it would edit that key with the new value. He allowed the script to run for a month or two to ensure that everyone using shared PCs would get the new print queues. After that time period, if he received calls from clients stating they could not connect to a new printer, he would just turn on the print script (uncomment it in the main logon script) and ask the client to re-logon the Domain.

This example shows just how powerful connecting the registry can be. Needless to say, his boss thought he was brilliant (which he is) an sent him off to Hawaii (ok - maybe not! But it is a nice thought).

The PowerShell Variable Provider

What is a variable? I like to think of a variable as a "little box" that is used to store information. The Variable Provider shows us which PowerShell and user defined variables are available. Again, we will be working with variables when scripting, so this is just an introduction.

Example 1. Connect to the PSDrive Variable: and Show a List of Available Variables

Connect to the PSDrive.

Set-Location Variable:<enter>

Use.. What Command to list variables?

Get-ChildItem<enter>

Example 2. List the Information in the PSHome Variable

In PowerShell, variables are preceded by the dollar sign character ($). However, the list of variables in example 1. don't show a "$" sign. To view the information stored in the PSHome variable, just add the "$" before the variable name.

$PSHome<enter>

The $PSHome variable holds the information of the PowerShell installation path. Check out the information stored in other variables such as the $Profile and $Home variables.

Example 3. Create a User Defined Variable

There are a few ways to create variables. Since were talking about File System cmdlets used with providers, sticking with theme we would do the following:

New-Item MyVar -Value "This is my new variable."<enter>

You can also use the "Set-Variable" cmdlet to accomplish the same:

Set-Variable MyVar2 -Value "This is my second variable."<enter>

This last example is most commonly used when scripting. You will find yourself using this example more than the others:

$MyVar3 = "This is my third variable."<enter>

Let's sort the listing of variables by name and verify our newly created variables exist.

Get-ChildItem | Sort {$_.Name}<enter>

Do you see MyVar, MyVar2, and MyVar3 user-defined variables?

Example 4. Remove Variables

Let's use the "Remove-Item" cmdlet to remove the variables we created:

Remove-Item MyVar,MyVar2,MyVar3<enter>

Let's verify the variables have been removed:

Get-ChildItem | Sort {$_.Name}<enter>

By now your asking yourself, what is $_.Name? We can see that $_ must be a variable (all variables are noted by the dollar sign in PowerShell)... and it is. As defined, variables hold information. $_ is a special variable the holds the object piped from the "Get-ChildItem" cmdlet. The .Name is the Name Property of the object. I know your sick of me saying this but, we will explore script blocks in a later PowerShell tutorial.

One more PowerShell Provider to go...

The PowerShell Certificate Provider

Here is the last PowerShell Provider we need to cover. Using "Get-PSDrive" cmdlet we can see that we need to connect to the "cert" drive.

Example 1. Set Location to the Cert PSDrive and List all the Certificates on the System

Set-Location cert:<enter>

Get-ChildItem<enter>

This command truncates the "StoreNames" for good reason, there are a lot of entries. If you want a report of all certificates on a system may I suggest the following:

Get-ChildItem -Recurse | Export-CSV "C:\Certificates.csv"<enter>

View results:

Invoke-Item "C:\Certificates.csv"<enter>

PowerShell Training Certs

Certificates

Image 5.13

The basic concepts to take away from this tutorial are that PowerShell Providers allow us to use common cmdlets outside of the PowerShell environment. We only have to learn a few cmdlets, shortening the learning curve, to be affective working with:

  • PowerShell Aliases
  • Environment Variables
  • Files and directories
  • Functions
  • The Registry
  • Variables in PowerShell
  • Certificates

Powershell 3.0


What is new Powershell 3.0?

  • Language enhancements - improvements that came with PowerShell Version 3
  • Online help
  • New integrated scripting environment.
  • New features such as snippets and collapsible regions
  • Workflow support
  • PowerShell Web Access and Management OData Web Services
    • Language Enhancements
      Windows PowerShell 3.0 includes many features that are designed to make its language simpler, easier to use, and to avoid common errors. The Auto-complete feature saves typing time, and reduces my typos. As you begin to type a cmdlet so you see a pick-List of likely nouns to append to your verb.
      Property enumeration, count, length properties on scalar objects and New Core Cmdlets.
      Where-Object
      Old: Where-Object { $_. }
      New: Where-Object
      Select-String
      sls -path c:\test.txt -pattern 'Hello'

    • Disconnected Sessions
      Persistent user-managed sessions ("PSSessions") that you create by using the New-PSSession cmdlet are saved on the remote computer. They are no long dependent on the session in which they were created.

      Note:The Disconnected Sessions feature is supported only when the computers at both the originating ("client") and terminating ("server") ends of the connection are running Windows PowerShell 3.0.

      Also supports Robust Session Connectivity means PowerShell 3.0 detects unexpected losses of connectivity between the client and server and attempts to reestablish connectivity and resume execution automatically.

    • The new ISE
      Integrated Scripting Environment (ISE) has many new features, including Intellisense, Show-Command window, a unified Console Pane, snippets, brace-matching etc.

    • Cmdlet and Provider Changes For New Parameters for Get-ChildItem
      -Directory [ ]
      -File [ ]
      -Attribute [ ]
      -Hidden, -ReadOnly, -System

      For Get-Command
      Adds by command capability (Unknown, Cmdlet, Script...)

      For Restart-Computer
      -Wait
      Delay, Timeout and For parameters

    • PS Enhancements
      Modules can now be autoloaded
      When a member of a known module is accessed, the module is automatically loaded into the PowerShell session.

    • PowerShell Web Access
      Windows Server 2012 feature that lets users run Windows PowerShell commands and scripts in a web-based console.

      Help


      Online Help
      Get-Help Get-Module -Online

      Updatable Help
      Update-Help

    • Workflow

    • Management OData Web Services

    Microsoft Windows PowerShell 3.0 marks a significant advance for the Windows network administrator. It is combination of the power of a full-fledged scripting language with access to command-line utilities, Windows Management Instrumentation (WMI), and even VBScript.
    Windows PowerShell provides the power and ease of use that have been missing from the Windows platform since the beginning of time.
    Perhaps the biggest obstacle for a Windows network administrator in migrating to Windows PowerShell 3.0 is understanding what PowerShell actually is. In some respects, it is a replacement for the venerable CMD (command) shell.
    You can still use cd to change the working directory, and then use dir to produce a directory listing.
    PS C:\Users\Dev1> cd c:\
    PS C:\> dir
    Directory: C:\
    Mode LastWriteTime Length Name
    ---- ------------- ------ ----
    d---- 3/22/2012 4:03 AM PerfLogs
    d-r-- 3/22/2012 4:24 AM Program Files

    You can also combine traditional CMD interpreter commands with some of the newer utilities, such as fsutil.

    e.g.
    PS C:\> fsutil file createnew C:\test\myfirstfile.txt 1000
    test\myfirstfile.txt 1000
    File C:\test\myfirstfile.txt is created
    Above commands we used in an interactive manner. You can group them together like a batch file.

    What is cmdlets?
    In addition to using Windows console applications and built-in commands, you can also use the cmdlets (pronounced commandlets) that are built into Windows PowerShell
    Windows PowerShell 3.0 comes with about 1,000 cmdlets on Windows 8,
    e.g. Get-Help, Get-EventLog, or Get-Process
    e.g. Set-Service,
    Running ipconfig commands
    1. Start Windows PowerShell by choosing Start | Run | Windows PowerShell. The PowerShell prompt will open by default at the root of your Documents folder.
    2. Enter the command ipconfig /all. This is shown here:
    PS C:\> ipconfig /all
    3. Pipe the result of ipconfig /all to a text file. This is illustrated here:
    PS C:\> ipconfig /all >ipconfig.txt
    4. Open Notepad to view the contents of the text file, as follows:
    PS C:\> notepad ipconfig.txt

    Security issues with Windows PowerShell

    Example

    [PSCustomObject] {
    Name = "William"
    Age = 35
    }
    

    Copy and Try it