Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all 3333 articles
Browse latest View live

PowerTip: Find PowerShell Providers

$
0
0

Summary:  Learn how to find Windows PowerShell providers and their capabilities.

Hey, Scripting Guy! Question How can I find what Windows PowerShell providers I have on my system?

Hey, Scripting Guy! Answer Use the Get-PSProvider cmdlet.

Note  Beginning with Windows PowerShell 3.0, some providers load on-demand, and therefore, they do not
appear unless they have been accessed at least once. The WSMAN provider is an example of such a provider.


Location, Location, Location in PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about managing locations in Windows PowerShell.

Hey, Scripting Guy! Question Hey, Scripting Guy! I don’t understand what is the big deal with Get-Location. I mean, I can look and see where I am at, so why do I need Get-Location? For that matter, what are a PushD and a PopD? It says it has something to do with a stack, but I don’t know where that stack is, or even what a stack is. Can you help?

—DW

Hey, Scripting Guy! Answer Hello DW,

Microsoft Scripting Guy, Ed Wilson, is here. The weather in Charlotte finally cleared up. It has been rather cold and wet the past couple days. This is kind of bad because the Windows PowerShell Summit is taking place this week in Charlotte, and we have had nice weather for the past week or so—so I was hoping my friends from other places would see the city in a better light. In fact, Windows PowerShell MVP, Sean Kearney, posted this picture on his Facebook page:

Image of rain

Oh, well. Like I said, it is clearing up, and it should be lovely for the next few days.

The thing that is important about location in Windows PowerShell is that the location can be anywhere. Remember yesterday's post, Find and Use Windows PowerShell Providers? Each of those providers exposes Windows PowerShell drives. So the location may be drive C of your file system—but it could just as easily be the Alias: drive that exposes Windows PowerShell aliases and their associated values.

As you might expect, the Get-Location cmdlet returns an object. This might not be a surprise because everything in Windows PowerShell is an object. And just like most other objects, it returns default information. But there is also additional information available. As shown here, when I type Get-Location, by default, it returns the path:

PS C:\fso2> Get-Location

Path                                                                                          

----                                                                                           

C:\fso2          

This information may seem a bit redundant. I mean, I can look at my Windows PowerShell prompt, and if it is in the default configuration, it already shows me my location. But by piping the object that is returned by the Get-Location cmdlet to the Get-Member cmdlet, I can see that I actually have a PathInfo object, and that there is more than only path information available. This is shown here:

PS C:\fso2> Get-Location | gm

   TypeName: System.Management.Automation.PathInfo

Name     MemberType    Definition                                              

----         ----------             ----------                                              

Equals       Method     bool Equals(System.Object obj)                          

GetHashCode  Method     int GetHashCode()                                       

GetType      Method     type GetType()                                          

ToString     Method     string ToString()                                        

Drive        Property   System.Management.Automation.PSDriveInfo Drive {get;}   

Path         Property   string Path {get;}                                      

Provider     Property   System.Management.Automation.ProviderInfo Provider {get;}

ProviderPath Property   string ProviderPath {get;}  

The easiest way to see the additional properties is to pipe the object returned by Get-Location to the Format-List cmdlet and select all of the properties by using the asterisk wildcard character. This command and its associated output are shown here:

PS C:\fso2> Get-Location | Format-List *

Drive        : C

Provider     : Microsoft.PowerShell.Core\FileSystem

ProviderPath : C:\fso2

Path         : C:\fso2

To change my current location, I use the Set-Location cmdlet. This is a basic command. In fact, there are three aliases created by default for this command:

PS C:\> Get-Alias -Definition set-location

CommandType     Name         ModuleName                 

-----------               ----                ----------                 

Alias           cd -> Set-Location                                                             

Alias           chdir -> Set-Location                                                         

Alias           sl -> Set-Location                                         

If I want to change my location to a particular folder, I can use any of the above aliases or type the complete cmdlet name. To go to a particular folder, I can use the command that is shown here:

PS C:\> sl c:\fso1

But if I want to return to the root of drive C, I must follow it with a backslash. For example, if I just use sl c:, it does produce an error, but it does not move to the root drive. This is shown here:

PS C:\fso1> sl c:

PS C:\fso1> sl c:\

PS C:\> 

What is a stack?

You can think of a stack as simply a pile—like the following pile of books:

Image of books

If I want to retrieve a book from the pile, in general, I will remove the book from the top of the pile (or stack). This book is the last one that I added to the stack. In computer terms, this is referred to as "last in, first out" (LIFO). In book pile terms, it is referred to as not making a mess.

So, a stack is simply a collection of elements (or items) that can be of any type. For example, I could have a stack of DVDs or stack of CDs in addition to my stack of books. My book stack has two methods: add and remove. In computer terms, a stack has two methods: push and pop. An item is pushed to the stack or popped off the stack. In Windows PowerShell, there are two associated cmdlets, Push-Location and Pop-Location. They also have aliases as shown here:

PS C:\> Get-Alias pushd, popd

CommandType     Name        ModuleName                 

-----------                ----             ----------                 

Alias           pushd -> Push-Location                                                        

Alias           popd -> Pop-Location                                                           

Location information is therefore stored in a stack. By default, this location stack is not named. So why do I care about this stuff? Well, certainly, I can CD around or SL around. But this can begin to be a lot of typing. Here is an example:

PS C:\> sl C:\fso

PS C:\fso> sl c:\

PS C:\> sl E:\Data\ScriptingGuys\2015\HSG_4_20_15

PS E:\Data\ScriptingGuys\2015\HSG_4_20_15> sl 'C:\Users\ed\SkyDrive\Pictures\Camera Roll'

PS C:\Users\ed\SkyDrive\Pictures\Camera Roll> sl E:\Data\BookDOcs\PS5_sbs_book\Scripts\Scripts_ch12

PS E:\Data\BookDOcs\PS5_sbs_book\Scripts\Scripts_ch12> 

Unfortunately, even when I remember to use Tab completion and IntelliSense in the Windows PowerShell ISE, this rapidly becomes unwieldy. One of the issues with multiterabyte drives is that the file system structure seems to become complex, and the paths go on and on and on. This makes working from the command line (even from Windows PowerShell) a major pain.

It also can become a source of errors—especially when using Tab completion. When the folder names begin to look the same (such as my weekly folders for the Hey, Scripting Guy! Blog), you really need to pay attention to what you are doing. And anytime you have to rely on paying attention, you are asking for trouble. (As an aside, on MCSE exams, anytime the answer contains “… and instruct the user how to properly…”—that is not the right answer!)

So, what is the right answer? Well, in this case, it involves using Push-Location and Pop-Location (or PushD and PopD as the alias names).

PS C:\> pushd C:\fso

PS C:\fso> pushd c:\

PS C:\> pushd E:\Data\ScriptingGuys\2015\HSG_4_20_15

PS E:\Data\ScriptingGuys\2015\HSG_4_20_15> pushd 'C:\Users\ed\SkyDrive\Pictures\Camera Roll'

PS C:\Users\ed\SkyDrive\Pictures\Camera Roll> pushd E:\Data\BookDOcs\PS5_sbs_book\Scripts\Scripts_ch12

PS E:\Data\BookDOcs\PS5_sbs_book\Scripts\Scripts_ch12> 

If I want to see where I have been, I can use the Get-Location cmdlet, but I also specify –Stack. This causes the cmdlet to return the locations stored on the current stack (the default stack). Because I have not named a stack, I am using my default unnamed stack. This makes it easy, because I now use –Stack and it returns what I want. This is shown here:

PS E:\Data\BookDOcs\PS5_sbs_book\Scripts\Scripts_ch12> Get-Location -Stack

Path                                                                                                           

----                                                                                                            

C:\Users\ed\SkyDrive\Pictures\Camera Roll                                                                      

E:\Data\ScriptingGuys\2015\HSG_4_20_15                                                                          

C:\                                                                                                            

C:\fso                                                                                                          

C:\        

Remember that a stack is LIFO. This means that if I begin to pop items off the stack (by using the alias PopD for Pop-Location), I should return to the last place I was. This is shown here:

PS E:\Data\BookDOcs\PS5_sbs_book\Scripts\Scripts_ch12> popd

PS C:\Users\ed\SkyDrive\Pictures\Camera Roll> 

What does the stack look like? I use the Up arrow and retrieve the Get-Location –Stack command. As shown here, the content of the default location stack now appears:

PS C:\Users\ed\SkyDrive\Pictures\Camera Roll> Get-Location -Stack 

Path                                                                                                           

----                                                                                                            

E:\Data\ScriptingGuys\2015\HSG_4_20_15                                                                         

C:\                                                                                                            

C:\fso                                                                                                         

C:\   

Now if I use PopD, I will go to the Scripting Guy folder. To get a feel for the way it works, I once again check the stack all the way until the stack is empty. This is shown here:

PS C:\Users\ed\SkyDrive\Pictures\Camera Roll> popd

PS E:\Data\ScriptingGuys\2015\HSG_4_20_15> Get-Location -Stack

Path                                                                                                           

----                                                                                                           

C:\                                                                                                            

C:\fso                                                                                                         

C:\                                                                                                             

PS E:\Data\ScriptingGuys\2015\HSG_4_20_15> popd

PS C:\> Get-Location -Stack

Path                                                                                                            

----                                                                                                           

C:\fso                                                                                                         

C:\                                                                                                             

PS C:\> popd

PS C:\fso> Get-Location -Stack

Path                                                                                                           

----                                                                                                           

C:\                                                                                                             

PS C:\fso> popd

PS C:\> 

Now that I am back to the root drive, I check the stack. It is empty.

PS C:\> Get-Location -Stack

PS C:\> 

DW, that is all there is to using location in Windows PowerShell. Provider Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Find PowerShell Cmdlets and Synopsis

$
0
0

Summary: Use Windows PowerShell to find cmdlets and their associated synopsis.

Hey, Scripting Guy! Question How can I easily find a list of specific Windows PowerShell cmdlets and their associated meanings?

Hey, Scripting Guy! Answer Use the Get-Command cmdlet, pipe the results to the Foreach-Object and Get-Help cmdlets,
           then select the name and synopsis, for example:

gcm -Noun item* | % {get-help $_} | ft name, synopsis

Using Named Location Stacks in PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using named location stacks in Windows PowerShell.

Hey, Scripting Guy! Question Hey, Scripting Guy! If I need to move around in two types of locations, how would I do it? Suppose I need to look in various places in my profile, and then I need to do some work in data locations elsewhere on my hard drive. How would I be able to keep track of the different locations?

—AK

Hey, Scripting Guy! Answer Hello AK,

Microsoft Scripting Guy, Ed Wilson, is here. Today is the last day of the Windows PowerShell Summit in Charlotte. In fact, tonight the Charlotte Windows PowerShell User Group is having a special meeting to celebrate. We have invited Lee Holmes and Paul Higinbotham from the Windows PowerShell team to talk about their favorite Windows PowerShell tips and tricks. This will be a highly interactive session, and there are only a few seats left for this free event. To register for this unique opportunity, go to Everyday PowerShell – My Favorite PowerShell Hacks with Lee Holmes.

One of the things that makes navigating around in the Windows PowerShell console or prompt a bit annoying is typing the long path names. Of course, Tab expansion helps this task, but it only expands subdirectory by subdirectory, and therefore, for deeply nested folders, there is still a lot of stopping and starting.

Of course, using a mouse in File Explorer is not necessarily any faster. In fact, it usually is not due to the amount of time that it takes for thousands of files to scroll into the pane each time one clicks a new subfolder. With the Back button in File Explorer, this task became a bit easier. So, where is the Back button in the Windows PowerShell console? Well, this is where location stacks can come into play.

Note  This post continues yesterday's Hey, Scripting Guy! Blog post, Location, Location, Location in PowerShell. If you have not read that one yet, you should before you continue reading today’s post.

If I am working in multiple locations, and I can logically group them, then I like to create named locations. This is easily done by supplying a name for the stack when I call the Push-Location (PushD is the alias) cmdlet. If the stack name does not exist, it is created. If the stack name does exist, the new location is added to that particular named stack.

In the following example, I am working with a bunch of folders that are all named FSO in some fashion. So I create a new stack named FSO, and add the locations to that stack.

When you use Push-Location, the location being navigated to is added to the location stack, then the current location changes to the path specified. In the following examples, I begin at drive C, and navigate to the C:\fso folder. My current location changes to C:\fso and the path is stored in a location stack named FSO. I then change my current location to C:\fso1, and once again, add the path to the location stack named FSO. I again change my location to C:\fso2, and I also add that location to the stack. Here are the commands and the associated output:

PS C:\> pushd -StackName fso -Path C:\fso

PS C:\fso> pushd -StackName fso -Path C:\fso1

PS C:\fso1> pushd -StackName fso -Path C:\fso2

PS C:\fso2> 

Because I have not used Pop-Location (PopD is the alias), all three locations are stored on the FSO stack. Now I want to navigate to a few locations in my profile. I also want to store those locations, but I want them to be accessible via a different name. So I create a new location stack named Ed. Once again, I navigate to the different locations by using PushD. Here are the commands and the output:

PS C:\fso2> pushd -StackName ed -Path C:\Users\ed\Documents

PS C:\Users\ed\Documents> pushd -StackName ed -Path C:\Users\ed\Downloads

PS C:\Users\ed\Downloads> pushd -StackName ed -Path C:\Users\ed\Pictures

PS C:\Users\ed\Pictures>

I have added six locations to two differently named stacks. If I use Get-Location –Stack, but I do not specify any names, I will retrieve the default location stack. This command is shown here:

PS C:\> Get-Location -Stack

Because all six of my locations are on named stacks, nothing returns from the command. I then use the Up arrow, and try to look at the FSO stack. The command generates an error message. This command and its output are shown here:

Image of error message

The reason the error occurs is that the –Stack parameter is used for the default stack only. I cannot specify a name here. Instead, I need to use the –StackName parameter. When I do this, I can retrieve the locations as shown here:

PS C:\> Get-Location -StackName fso

Path                                                                                                            

----                                                                                                           

C:\fso1                                                                                                        

C:\fso                                                                                                          

C:\   

As shown here, I can also retrieve locations from the Ed stack:

PS C:\fso2> Get-Location -StackName ed

Path                                                                                                            

----                                                                                                           

C:\Users\ed\Downloads                                                                                           

C:\Users\ed\Documents                                                                                          

C:\fso2    

When it comes time to revisit the locations, I use Set-Location to change my default location stack name. Then I can use PopD to move through the directories. This command is shown here:

PS C:\> Set-Location -StackName fso

PS C:\> popd

PS C:\> Get-Location -Stack

Path                                                                                                           

----                                                                                                           

C:\                                                                                                             

C:\fso1                                                                                                        

C:\fso                                                                                                          

C:\                                                                                                            

PS C:\> popd

PS C:\> popd

PS C:\fso1> popd

PS C:\fso> popd 

PS C:\> 

When I reach the end of the stack, I change to my new stack by again calling the Set-Location cmdlet and then walking through those locations by using Pop-Location (PopD):

PS C:\Users\ed\Downloads> Set-Location -StackName ed

PS C:\Users\ed\Downloads> Get-Location -Stack

Path                                                                                                           

----                                                                                                            

C:\Users\ed\Documents                                                                                          

C:\fso2                                                                                                        

PS C:\Users\ed\Downloads> popd

AK, that is all there is to using named locations in Windows PowerShell. Provider Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Display Locations Stored on Stack

$
0
0

SummaryUse Windows PowerShell to display locations stored on the default stack.

Hey, Scripting Guy! Question How can I use Windows PowerShell to see the locations that are stored on my default location stack?

Hey, Scripting Guy! Answer Use the –Stack parameter of Get-Location:

Get-Location -Stack

Using Transactions with PowerShell Registry Provider

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using transactions with the Windows PowerShell Registry provider.

Hey, Scripting Guy! Question Hey, Scripting Guy! I was looking at the various providers and their capabilities (see Find and Use Windows PowerShell Providers). I see that the Registry provider says it does transactions. What’s that all about?

—JS

Hey, Scripting Guy! Answer Hello JS,

Microsoft Scripting Guy, Ed Wilson, is here. This morning I am sipping a cup of tea from some tea that Windows PowerShell MVP, Sean Kearney, brought me from Ottawa. There just happens to be an awesome tea shop there, and Sean volunteered to bring me some. WooHoo!!

A transaction is a unit of work that must complete completely, or it must fail and roll back completely. An example of this might be transferring money from one bank account to another bank account. The steps might include:

  1. Access the first bank account.
  2. Remove money from the first bank account.
  3. Access the second bank account.
  4. Add money from the first bank account to the second account.

Obviously, I would not want the first two steps to complete and the last two steps to fail.

Anyway JS, yes indeed, the Registry provider supports transactions. In fact, it has supported transactions since Windows PowerShell 2.0. But the operating system must be Windows Vista or later. Theoretically, any provider could support transactions, but the only default provider that does support transactions is the Registry provider. I can use the following command to find providers that support transactions:

PS C:\> Get-PSProvider | ? capabilities -match 'transactions'

Name                 Capabilities                                  Drives                                      

----                 ------------                                  ------                                      

Registry             ShouldProcess, Transactions                   {HKLM, HKCU}                                

To begin a transaction, I use the Start-Transaction cmdlet. When I do this, it appears as if nothing happens. This command is shown here:

PS C:\> Start-Transaction

PS C:\> 

The next thing I do is type in the command that I want to perform. Each command that I type does not have to be part of the transaction, but if I want it to be included in the transaction, I must use the –UseTransaction switch. My current location does not have to be one of the Registry drives, but the path needs to resolve to a registry drive (or to another drive that is exposed by another Windows PowerShell provider that supports transactions).

In the output shown here, I start a transaction and create a registry key:

PS C:\> Start-Transaction

PS C:\> New-Item -Name trans -Path HKCU:\Software\ScriptingGuys -Value "transaction" -UseTransaction

    Hive: HKEY_CURRENT_USER\Software\ScriptingGuys

Name                           Property                                                                        

----                           --------                                                                        

trans                                                                                                          

It looks like the registry key is already created. But because I have not completed my transaction, I know that it has not actually been created yet. I can verify this by opening the Registry Editor and looking up my registry key. I can see that the registry key is not there:

Image of menu

I can create additional registry keys or complete my transaction.

To complete the transaction, I call the Complete-Transaction cmdlet. One thing that is perhaps a bit disconcerting, is that nothing comes back when I call Complete-Transaction. This is shown here:

PS C:\> Complete-Transaction

PS C:\> 

So once again, I pop back over to the Registry Editor. I hit the Refresh button, and now I can see that the transaction did complete:

Image of menu

The commands and the output from the commands are shown here:

Image of command output

JS, that is it. It is really easy to do transactions with the Windows PowerShell Registry provider. Provider Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Set Default Location Stack with PowerShell

$
0
0

Summary: Use Windows PowerShell to set your default location stack.

Hey, Scripting Guy! Question How can I use Windows PowerShell to set the default for some named location stacks that I created?

Hey, Scripting Guy! Answer Use the Set-Location cmdlet and specify the stack name, for example:

Set-Location -StackName REG

Use PowerShell to Move User Files and Update Registry

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to move user files and update the registry.

Hey, Scripting Guy! Question Hey, Scripting Guy! I need to move a bunch of user files from their local computer to a network share so we can back up the user's data prior to migrating their desktops. I know there are various tools I can use to do this, but our scenario is pretty simple because the user profile data is all located in specific folders. After I have moved their data, I need to update a registry key. That key will be read by another app, and the machines will be wiped before we drop a new image. Needless to say, I need to ensure I do not update the registry before I have moved the data. Can you help me?

—WM

Hey, Scripting Guy! Answer Hello WM,

Microsoft Scripting Guy, Ed Wilson, is here. Well, this is the end of a pretty cool and exciting week. It begin with the Windows PowerShell Summit in Charlotte, and then we had a way cool Windows PowerShell User Group meeting with Lee Holmes and Paul Higinbotham. Here is a picture from the user group meeting:

Photo of participants

The Scripting Wife has been busy finalizing the schedule for the guests who will be at the Scripting Guys booth at Ignite. That guest list will be published tomorrow right here on the Hey, Scripting Guy! Blog. If you are one of the lucky ones who were able to get tickets to Ignite, you will want to make sure you add our guests to your schedule, so you do not miss out on a unique opportunity to talk one-on-one with some of the awesome people in the Windows PowerShell community.

Yep, it has been busy and crazy fun.

You know, WM, I am reminded of an incident that happened when I was in consulting many years ago. The IT admin at one of my customer's work sites wrote a script that did the following:

  1. Copy files from users computers.
  2. Make connection to network share.
  3. Copy the files to the network share.
  4. Delete files from the user's computers.

Unfortunately, steps 2 and 3 failed. More unfortunately, step 4 completed, and so they had the opportunity to test their restore procedures. Luckily, they had good backups—but still, it wasted most of the day, and it actually continued to plague them for several weeks after that.

Set up the environment

The first thing I want to do is to create a few folders, to play with. To do this, I wrote a bit of code that will copy the contents of my scratch folder to three different destinations. Here is the code:

$source = "C:\fso"

$path = "c:\fso1","c:\fso2","c:\fso3"

$path | % { Copy-Item -Path $source -Destination $_ -Force -Recurse}

Next, I wrote a simple two-line bit of code to copy the contents of the three folders to a backup folder. I decided it would be useful to include the computer name under the backup folder, and then have a folder for each of the three folders I created earlier. Here is the code:

$paths = "C:\fso1", "C:\fso2", "C:\fso3"

Copy-Item -Path $paths -Destination "c:\backup\$env:computername" -Force -Recurse –Container

Unfortunately, when I run this little script, the contents of the C:\FSO1 folder ends up in the root, and then I get the folders for the second and the third folder. Here is what this looks like in the file explorer:

Image of folder

Well, that is not what I wanted. What I wanted was three folders under the computer name folder. I talked with Microsoft PFEs extraordinaire and Honorary Scripting Guys, Brian Wilhite and Jason Walker, and they figured out that if I create the first folder, when I do the copy, it will come out correctly. So I played around and came up with the following script.

$paths = "C:\fso1", "C:\fso2", "C:\fso3"

$destination = "c:\backup\$env:computername"

If(!(Test-Path $destination))

  { md -Path ("{0}\{1}" -f $destination, $paths[0].Substring(3))| out-null }

Copy-Item -Path $paths -Destination  $destination -Force -Recurse -Container 

Here is what the folders look like now:

Image of folder

So now I have my code to copy the folders to a destination. Unfortunately, the Windows PowerShell FileSystem provider does not support transactions, so I cannot start a transaction to move my files. But what I can do is use Try/Catch/Finally, and if no errors occur, then I can delete the files. Here is what that might look like:

$paths = "C:\fso1", "C:\fso2", "C:\fso3"

$destination = "c:\backup\$env:computername"

$ErrorActionPreference = "Stop"

If(!(Test-Path $destination))

  { md -Path ("{0}\{1}" -f $destination, $paths[0].Substring(3))| out-null }

Try {

Copy-Item -Path $paths -Destination  $destination -Force -Recurse -Container

get-item -Path $paths | Remove-Item -Recurse -Force

"Backup successful"

}

Catch [System.Exception]

 {

  "Backup failed"

  }

A [System.Exception] is the most generic error. If anything goes wrong with the Copy-Item operation, an error arises, and it moves to the Catch block.

The last thing to do is to add the registry update. To do this, I add it to the Finally block. To know if the backup was successful, I added $success = $true in the Try block and $success = $false in the Catch block. My Finally block writes the success or failure of the backup to the registry. If the backup is successful, it writes the time of the backup, otherwise, it writes that the backup failed. Here is the script:

$paths = "C:\fso1", "C:\fso2", "C:\fso3"

$destination = "c:\backup\$env:computername"

$ErrorActionPreference = "Stop"

If(!(Test-Path $destination))

  { md -Path ("{0}\{1}" -f $destination, $paths[0].Substring(3))| out-null }

Try {

Copy-Item -Path $paths -Destination  $destination -Force -Recurse -Container

get-item -Path $paths | Remove-Item -Recurse -Force

$success = $true

"Backup successful"

}

Catch [System.Exception]

 {

  $success = $false

  "Backup failed"

  }

Finally {

 Start-Transaction

 If($success)

  {New-Item -Name backup -Path HKCU:\Software\ScriptingGuys -Value `

   "Backup $((Get-Date).Tostring())" -UseTransaction -Force}

 else

 {New-Item -Name backup -Path HKCU:\Software\ScriptingGuys -Value `

  "Backup Failed" -UseTransaction -Force}

 Complete-Transaction

}

WM, that is all there is to using transactions to update the registry after moving data from one folder to another. This is also the end of Provider Week. Join me tomorrow when Windows PowerShell MVP, Teresa Wilson, will talk about all of the cool guests she has lined up for the Scripting Guys booth at the Ignite Conference in Chicago.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


PowerTip: Roll Back Active PowerShell Transaction

$
0
0

SummaryLearn how to roll back an active Windows PowerShell transaction.

Hey, Scripting Guy! Question I started a transaction to modify the registry on my computer running Windows 8.1, but something failed,
           and I want to roll back the transaction. How can I do this?

Hey, Scripting Guy! Answer Use the Undo-Transaction cmdlet to roll back the active transaction.

Weekend Scripter: Scripting Guys Ignite Booth Schedule

$
0
0

Summary: Microsoft PowerShell MVP, Teresa Wilson, talks about the Scripting Guys booth schedule.

Microsoft Scripting Guy, Ed Wilson, is here. It is that time of year again. Conference time. TechEd North America is no more, but Microsoft Ignite is on the horizon. May 4-8, 2015 in Chicago! It is already sold out, but you can see the presentations as they are being recorded. Windows PowerShell MVP, Teresa Wilson (aka The Scripting Wife) is with us today to share the schedule of special guests you can meet at the Scripting Guys booth. Take it away, Teresa...

I have a working schedule to share with you regarding who you can find at the Scripting Guys booth at specific times. Keep in mind that some of these people may be there at other times, and you are always welcome to stop by to chat.

You may know that I am the treasurer for PowerShell.org, so don’t be surprised if you find board members  Don Jones, Jason Helmick, or Jeff Hicks at the Scripting Guys booth more than only the scheduled meet and greet times. The booth staff this year (in addition to Ed and me) is going to include three Microsoft premiere field engineers, and they are all Honorary Scripting Guys: Gary Siepser, Jason Walker, and Brian Wilhite. Each of these gentlemen work daily with Microsoft customers with Windows PowerShell.

The cool thing about this schedule is that there are also some great Windows PowerShell scripters who have agreed to hang out at our booth for a while. This is a perfect time for you to come by and have one of these experts share their knowledge with you. There will normally be some really cool people hanging out at the Scripting Guys booth, and some attendees use the booth as their base of operations and swing by periodically to see who happens to be there. With this schedule, you can also make sure that you do not miss the chance to talk to some really top-flight experts.

Ed will update this page if there are any changes before we leave for Chicago. When we are there, you may want to watch Twitter for any last minute updates, or you can send Ed or me a tweet to inquire about schedule updates.

I know for a fact, that some of the Windows PowerShell team members will be added to this list in addition to Mark Minasi and Steven Murawski. So as of now, here is the list. These are 30-minute Meet-n-Greet sessions.

Monday May 4

1:00 PM   Don Jones

2:00 PM   Yuri Diogenes

Tuesday May 5

2:00 PM   June Blender

3:00 PM   Todd Klindt

Wednesday May 6

10:00 AM   Jeff Hicks

10:30 AM   Jason Helmick

2:30 PM    Hal Rottenberg

3:00 PM    Jeffrey Snover

That is everyone I have scheduled for now. Be sure to let me know if there are Windows PowerShell people who you would like to meet. If they are attending Microsoft Ignite, we will invite them to come to the Scripting Guys booth.

Remember that we will be updating this list because I am awaiting scheduling times for other visitors. We can’t wait to see you in Chicago at Microsoft Ignite.

~Teresa

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerTip: Determine if Property is Member of Object

$
0
0

Summary: Determine if a property is a member of an object in Windows PowerShell.

Hey, Scripting Guy! Question How can I determine if a specific property is actually a member of an object in my Windows PowerShell script?

Hey, Scripting Guy! Answer Use the Get-Member cmdlet, and cast the response into a Boolean data type by using the [bool] type
            accelerator, for example:

[bool](Get-member -Name time -InputObject (get-date) -MemberType Property)

Note  I got this idea from Microsoft PFE, Clint Huffman. He uses it in his PAL data collector. He has a note
in that script that says he got the idea from Jeffery Snover. Cool…

Weekend Scripter: My First PowerShell Summit

$
0
0

Summary: Microsoft PowerShell MVP, Will Anderson, talks about his first Windows PowerShell Summit.

Microsoft Scripting Guy, Ed Wilson, is here. Wow! What a week...or part of a week. Windows PowerShell Summit North America 2015 was here in Charlotte, NC this past week. The Scripting Wife and I met a lot of new people and made new friends. One of these friends is a brand new Windows PowerShell MVP, Will Anderson. Will wrote a blog post about his time here in Charlotte. First a little about Will...

Photo of Will Anderson

Will Anderson is a thirteen-year infrastructure veteran with a specialization in patch management, compliance, and System Center Configuration Manager. Working in environments ranging from 80 users to over 150,000, Will has acquired knowledge about a broad range of products and service lines, ranging from Exchange Server, Active Directory, and Group Policy, to the operating system platforms and a variety of applications.

In recent years, he's become quite the nerd about Windows PowerShell, and he blogs about the latest cool things he finds or creates to make his life as an admin and engineer easier. You can find him on PowerShell.org as a moderator, webmaster, and occasional writer for the PowerShell TechLetter. He is also a cofounder of the Toronto PowerShell Users Group (PowerShellTO) and a member of the Association for Windows PowerShell Professionals.

Will received his first Microsoft MVP in 2015 for Windows PowerShell. You can find him at various places on the Internet, including PowerShellTO, PowerShell.org, Twitter, and his personal blog: Last Word in Nerd.

Here’s Will...

Greetings fellow scripters! Ed Wilson was gracious enough to let me take the reins for a session on the Hey! Scripting Guy! Blog so I can tell you about my experience at the greatest Windows PowerShell community gathering in North America—the Windows PowerShell Summit!

Last week, the third annual Windows PowerShell Summit North America took place in Charlotte, North Carolina. I, like many of my fellow Windows PowerShell enthusiasts, headed to the Microsoft campus with the purpose of meeting like-minded individuals to discuss everything PowerShell. The Summit, it would turn out, would be one of the most educational experiences that I’ve ever had the pleasure to attend.

Desired State Configuration and the Nano Server announcement were obviously the hottest conversation topics at the Summit, but there were a lot of topics for Windows PowerShell lovers of all skill levels to enjoy. Some of my favorite topics were:

Members of the Windows PowerShell team and Jeffrey Snover were present at the Summit. Often they would sit down with us and discuss our challenges and inputs into their product. Like us, they were enthusiastic about the waves that the technologies living on top of Windows PowerShell are making, and the culture of innovation and automation that it is driving. They listened to and considered every idea and issue with careful thought and enthusiasm. I tell you that nothing makes you more proud of being part of a community that supports a product more than knowing your opinion matters to the people making it!

What I found most enjoyable, however, was being given the opportunities to meet with so many of my peers—many of whom I had talked to on a regular basis through social media or on the PowerShell.org forums. Being able to put a voice and face to the names and to sit down over coffee and discuss our past accomplishments, current challenges, and future aspirations was a value-add on par with all of the fantastic speaker engagements we attended.

Every attendee, be they a Windows PowerShell developer, a Microsoft MVP, or a hard-core enthusiast, took an equal part in the conversations. I can safely say that everyone involved walked away from the Windows PowerShell Summit more enlightened, more knowledgeable, and more proud to be a part of the community.

If you’re looking for a real value-add experience to attend next year, I highly recommend the Windows PowerShell Summits in North America or Europe. The knowledge, experience, and memories that you will gain from going will last you a lifetime! In the meantime, you can take a look at this year’s sessions on the PowerShell.org YouTube channel. Also, keep your eyes on PowerShell.org for announcements about both Summits. Hope to see you next year!

~Will

Thanks Will. It was a pleasure to meet you, and we look forward to seeing you again.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerTip: Find Current Directory in PowerShell

$
0
0

Summary: Easily find the current directory in Windows PowerShell. 

Hey, Scripting Guy! Question How can I return a path object that contains information about the current working directory in Windows PowerShell?

Hey, Scripting Guy! Answer Use the $pwd automatic variable:

PS C:\> $pwd

Favorite PowerShell Tips and Tricks

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about Windows PowerShell tips and tricks from the Charlotte User Group meeting.

Microsoft Scripting Guy, Ed Wilson, is here. Last week was a special meeting at the Charlotte Windows PowerShell User Group. It followed immediately after the Windows PowerShell Summit, and as a result, the user group included five members of the Windows PowerShell team, nearly a dozen MVPs, and at least that many Microsoft employees. All in all, there were nearly a hundred people in the room, and that, I believe, makes it the largest Windows PowerShell User Group meeting so far in Charlotte.

Lee Holmes led the meeting, and the subject was Windows PowerShell tips and tricks. But instead of Lee standing in front of us, doing a show-and-tell, he showed a trick, and then asked for one from the audience. The trick had to be something that people used on a regular basis, which means they are useful, not simply esoteric. The meeting was amazing, and this week I am going to share the best with you in Tips and Tricks Week.

Add resource usage to your Windows PowerShell prompt

This tip actually incorporates several tips at once. One tip involves making sure that you read the automatic variables list and descriptions from time-to-time (see about_Automatic_Variables). As Lee Holmes said, “If the Windows PowerShell team takes the time to create an automatic variable and to include it in everything, then it is obviously important.”

There are a lot of automatic variables, and some of them only appear at certain times and at certain places. So, one cannot simply use Get-Variable and see all of the automatic variables.

Two more tips involve creating and using a Windows PowerShell profile and modifying the Windows PowerShell prompt. For more information, read these Hey, Scripting Guy! Blog posts:

One of the attendees at the Charlotte Windows PowerShell User Group meeting mentioned that he once ran into trouble with a long running Windows PowerShell job that soaked up a lot of resources. To help to indicate what was going on with the long running job, he modified his Windows PowerShell prompt to include information about Windows PowerShell resource usage.

The Windows PowerShell prompt, is simply a function that is named “prompt.” It is a bit different, depending on whether one is running in the Windows PowerShell console or in the Windows PowerShell ISE. But if I use the following command, I will always return the appropriate prompt function:

PS C:\> Get-Content Function:\prompt

"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel

+ 1)) "

# .Link

# http://go.microsoft.com/fwlink/?LinkID=225750

# .ExternalHelp System.Management.Automation.dll-help.xml

I like to copy the contents of the function, so I have something to begin playing around with:

Image of command output

From looking over the automatic variable list, I found a $pid automatic variable. This variable displays the process ID for the Windows PowerShell process that hosts the current Windows PowerShell session. This is shown here:

PS C:\> $pid

2972

This means that I can use the Get-Process cmdlet to retrieve performance information about the current Windows PowerShell process. This is important to do because there could be multiple Windows PowerShell processes running, and I want to return the correct one. This technique is shown here:

PS C:\> Get-Process -Id $pid

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                              

-------  ------    -----      ----- -----   ------     -- -----------                             

   1093      79   167652     196780  1070    11.44   2972 powershell_ise                          

Note  It is important to supply the –ID parameter when using $pid with Get-Process because the default parameter for Get-Process is name, and an error occurs if I use $pid and do not supply the appropriate parameter. In other words, the cmdlet is not smart enough to recognize a number, and realize that I am supplying a process ID.

In addition to the process ID, I want to include information about the CPU, virtual memory, working set, and paged memory. To do this, I store the results from Get-Process into a variable:

$ps = Get-Process -id $pid

Then I use parameter substitution and the format operator to supply the process information. I do this because I also want to format the numbers to two decimal places to make things easier to read. I can write my prompt function, and when I run it, it will change my Windows PowerShell ISE prompt in the output pane. The function is shown here:

function prompt

{

 $ps = Get-Process -id $pid

 "PS PID: $pid PM(M) {0:N2} WS(M) {1:N2} VM(M) {2:N2} CPU(s) {3:N2}

$($executionContext.SessionState.Path.CurrentLocation)$('>' * `

($nestedPromptLevel + 1))" `

-f ($ps.PM/1MB), ($ps.ws/1MB), ($ps.vm/1MB), $ps.cpu

}

Here is the modified output pane after I run the function:

Image of command output

Now I start a background job, and see what happens. Here is a simple background job that will run for a while, and use a bit of memory and CPU time:

start-job -ScriptBlock {

1..1000000000 | % {[math]::Cos([math]::Sin($_)) } }

As shown here, as soon as I run my background job, I can see that the memory changes and the CPU time is going up:

Image of command output

Because this is a background job, I can continue to work in my Windows PowerShell ISE. I can, for example, look at other things in the Windows PowerShell output pane. Here, I look at all processes that have a name that includes PowerShell

Image of command output

Because I have not added this particular prompt function to my Windows PowerShell ISE profile, when I close the Windows PowerShell ISE and open it again, the prompt reverts to the original prompt. This is shown here:

Image of prompt

But, even if I did add the function to my Windows PowerShell ISE profile, I can always open the Windows PowerShell ISE by using Run and specifying the –NoProfile parameter:

Image of command

There is a beginning for Windows PowerShell tips and tricks. Tips and Tricks Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Find User's Home Directory in PowerShell

$
0
0

Summary: Find the path to the current user's home directory in Windows PowerShell.

Hey, Scripting Guy! Question How can I easily find the current user's home directory for a script I am writing?

Hey, Scripting Guy! Answer Use the $home automatic variable:

PS C:\> $HOME


Use PSReadLine for More Efficient PowerShell Console

$
0
0

SummaryMicrosoft Scripting Guy, Ed Wilson, presents a tip from the Charlotte User Group meeting about using PSReadLine.

Microsoft Scripting Guy, Ed Wilson, is here. One really big tip that came out during the Charlotte User Group meeting was to use the PSReadLine module. It provides is syntax highlighting, which makes it easier to understand commands and spot errors because I can see how Windows PowerShell is interpreting something. For example, in the following image, the cmdlet is colored yellow, parameters are gray, variables are green, and the output is white.

Image of command output

If I am trying to run a command and it keeps failing, I can easily spot that I left out a hyphen (for example). The following image shows that the command failed. I can immediately see that Windows PowerShell thinks FileVersionInfo is text, not a parameter (because it is white, not gray). This color coding is actually easier to understand than the error message “A positional parameter cannot be found that accepts argument FileVersionInfo.”

Image of error message

The first thing I need to do is to install PSReadLine. I talk about this in the Hey, Scripting Guy! Blog post The Search for a Better PowerShell Console Experience.

Note  If I install PSGet first, I can easily use the Install-Module cmdlet to install PsReadLine. In addition, I can use the Update-Module cmdlet to update the version easily. If I do not use PSGet to do the installation, I will not be able to use Update-Module to do the update.

One thing I like about PSReadline is the enumeration of command options. For example, if I type a .NET class in square brackets, and I press CTRL plus Spacebar, it will list possible command completion options. I can then tab between the options to select the one I need. This is shown here where I am looking for static members of arrays:

Image of command output

One of the things that PSReadLine excels at is making the command-line editing experience much richer. I talk about this in the Hey, Scripting Guy! Blog post A Better PowerShell Command-Line Edit. This post has a couple of tables that detail the options and short-cut key bindings that exist. I also provide a short video that illustrates an edit session in Windows PowerShell by using PSReadLine.

I have written a number of Hey, Scripting Guy! Blog posts about working with Windows PowerShell history, but the PSReadLine module provides a rich command history experience. I wrote about PSReadLine history in Better PowerShell History Management with PSReadLine.

I also documented a number of useful shortcuts that are available in PSReadLine in Useful Shortcuts from PSReadLine PowerShell Module.

PSReadLine is extremely flexible, and it permits me to work the way I want to. One way that it becomes even more useful, is because it is completely customizable. I wrote about customizing PSReadLine in the A Better PowerShell Console with Custom PSReadLine Functions.

That is all there is to using the PSReadLine module. PowerShell Tips and Tricks Week will continue tomorrow when I will talk about more way cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Retrieve Last Token Received by PowerShell

$
0
0

Summary: Learn how to retrieve the last token that was received by Windows PowerShell.

Hey, Scripting Guy! Question How can I retrieve the last token received by Windows PowerShell?

Hey, Scripting Guy! Answer Use the $$ automatic variable:

PS C:\> notepad C:\fso\AMoreComplete.txt

PS C:\> $$

C:\fso\AMoreComplete.txt

PowerShell Tips and Tricks: Extended History

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about a module that provides extended command history.

Microsoft Scripting Guy, Ed Wilson, is here. One of the things that came up during the Charlotte Windows PowerShell User Group meeting was the HistoryPx module that was written by Windows PowerShell MVP, Kirk Munro. This module adds additional history information to the Windows PowerShell console. For example, he adds information about the duration of a command, the output of the command, and errors generated by the command.

Installing  HistoryPx

Installing the HistoryPx module is really easy because it is hosted on GitHub, and therefore I can use PSGet to download and install the module.

Note  PSGet is a community-developed module that streamlines the installation of modules. It is available from PSGet.net. It provides cmdlets such as Install-Module and Update-Module.

To install the HistoryPx module, I also need to ensure that I have the SnippetPX module. Luckily, I can install both modules by using the following command, which will install the modules for all users:

Install-Module HIstoryPx, SnippetPx

Note  Running this command requires elevated permissions.

I can also install the modules for me only. If I do not want to be prompted with the EULA, then I use the –AcceptEula switch. This command is shown here:

Install-Module HistoryPx, SnippetPx  -Scope CurrentUser -AcceptEula

Using the extended history module

After I have installed the HistoryPx module and the SnippetPx module, I can import the HistoryPx module by using the Import-Module cmdlet:

Import-Module HistoryPx

I can now use the standard Get-History cmdlet to retrieve my command history. This is because the HistoryPx module creates proxy functions (that is, it extends the standard Get-History cmdlet).

Note  There are several posts on the Hey, Scripting Guy! Blog about proxy functions. A good starting point is one by Windows PowerShell MVP, Shay Levy, called Proxy Functions: Spice Up Your PowerShell Core cmdlets.

Here is the output from the Get-History cmdlet now (h is an alias for Get-History):

Image of command output

One of the cool things about the module is that it automatically captures output in a variable, $__ ,(it has two underscores). This means that when I am working interactively in the Windows PowerShell console, I do not need to use an intermediate variable. I can use the $__ variable and filter it directly. This technique is shown here, where I look for commands that contain the word Install:

PS C:\> $__.where{$_.commandline -match 'install'

 Id   CommandLine       Duration     Success   #Errors   Output

  --      -----------               --------       -------       -------     ------

   2 Install-Module HistoryPx, S... 00:00:02.515   True

  10 $__.where({$psitem.commandl... 00:00:00.015   True    0       {}

  12 $__.where{$_.commandline -m... 00:00:00.000   True    0       {}

I see the command I was interested in is command number two. So I can now use Get-History to look directly at the command history for that command. This is shown here:

PS C:\> h 2

  Id   CommandLine       Duration     Success   #Errors   Output

  --      -----------               --------       -------       -------     ------

   2 Install-Module HistoryPx, S... 00:00:02.515   True

There is a lot more I can do with this module, and Kirk has documented it well in his GitHub project HistoryPx. You may want to install the modules, play around with them, and see if they help you work more effectively.

Windows PowerShell Tips and Tricks Week continues tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Find PowerShell Profiles

$
0
0

Summary: Learn how to easily find Windows PowerShell profiles.

Hey, Scripting Guy! Question How can I Question: You want to find the path to Windows PowerShell profiles?

Hey, Scripting Guy! Answer Use the $Profile automatic variable, but pipe the output to the Format-List cmdlet and use
           the –Force parameter. Here is an example that uses the FL alias for Format-List):

$profile | fl * -Force

Select History Via PowerShell Out-Gridview

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, continues his tips and tricks series by talking about select Windows PowerShell commands via Out-GridView.

Microsoft Scripting Guy, Ed Wilson, is here. One of the great things about getting a bunch of Windows PowerShell people together is that they begin to share tips and tricks they have figured out. One reason for this is that Windows PowerShell is highly discoverable. Another reason is that there is a whole lot of Windows PowerShell, and therefore, there is a whole bunch of stuff to discover. Many times (at least for me), the coolest tips and tricks are not something that I have never heard of, but they are new ways of doing things that I am already doing.

An example is the trick for today—using the Out-GridView cmdlet to pick commands from Windows PowerShell history to create an initial script. For me, what is cool about this, is that I already do both elements of the trick. That is, I already pick the command lines from history and I pipeline them to create a script.

I also already use the Out-GridView cmdlet’s –Passthru parameter so that I can cherry pick stuff from the displayed grid and return it to the Windows PowerShell console for further processing. But I never thought about putting the two techniques together. Obviously, Lee Holmes had thought of it, and he shared it with the Windows PowerShell User Group in Charlotte.

Suppose I have a number of Windows PowerShell commands in my command history. I would like to select from them and create a script based upon them. One way I can do this is to use Get-History, redirect the command lines to a file, and then open that file in the Windows PowerShell ISE to edit it. But an easier way is to create a temporary file to hold my script, and then pipe my history to Out-GridView so I can see which commands I want to select. I can then pipe the selected commands to my file and open it in the Windows PowerShell ISE.

First, I need to create a temporary file. Well, I really don’t need to create a temporary file, but it is easier. I could create the script file that I want to use in my script folder, and use that. But that means I need to think of a name and all of that. A temp file is easier to create and use. Here, I create a temp file in the temp folder, and store the path to the file in a variable named $file:

$file = [io.path]::GetTempFileName()

Now I use the Get-History cmdlet to retrieve my command history. But I am only interested in the commandline property, so I can select it directly. This is shown here (using the H variable as an alias for the Get-History cmdlet):

(h).commandline

I pipe the returned command lines to the Out-GridView cmdlet, and I specify the –PassThru parameter. This means that Windows PowerShell displays the output in a grid. I can then select the items I want from that grid. The GridView control is shown here:

Image of command output

The selected items return to the Windows PowerShell console. (I will pick them up, and then pass and redirect them to my temp file). The command now looks like the following:

(h).commandline | Out-GridView -PassThru

I now write my selected commands to the temp file. I do this by using the redirection operator. Here is the command as it now stands:

(h).commandline | Out-GridView -PassThru >> $file

I want to open the file in the Windows PowerShell ISE so I can play with the commands, add additional information, or even save the output as a Windows PowerShell script. To do this, all I do is add the call to open the Windows PowerShell ISE and specify my file:

(h).commandline | Out-GridView -PassThru >> $file ; ise $file

Here are my two complete commands:

$file = [io.path]::GetTempFileName()

(h).commandline | Out-GridView -PassThru >> $file ; ise $file

Because the output is not a PS1 type of file, I cannot simply press F-8 and run the script. But I can select the commands in the script pane, and press F-5 to run the selection.

Image of command output

I can also use my Copy-ScriptToNewTab function (from my Windows PowerShell ISE module) and THAT will run directly.

Image of command output

That is all there is to using Out-GridView to select commands via Windows PowerShell history. Tricks and Tips Week will continue tomorrow when I will talk about more way cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Viewing all 3333 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>