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

Using Azure Automation: Part 4

$
0
0

Summary: Learn how to report output from Azure Automation and publish to production.

Honorary Scripting Guy, Sean Kearney, is here again to show you more about Azure Automation and to empower you in automating your assets in Azure. This is the fourth post in a five-part series. To catch up, read:

Our current task is trying to see what is happening in the magic genie bottle that contains our Azure Automation runbook. I say "magic genie bottle" because up to this point, we really can't see what's going on, can we? There's no Windows Powershell console, no ISE.

Nothing…

Not a sausage!

Well actually, that's not true. I fibbed a bit. We do have an output pane that is waiting for output. When you run Test on the runbook, you'll see a window at the bottom of the webpage that shows nothing other than Status StartingBut we can have some output go to this window. It's actually pretty easy. Simply use the Write-Output cmdlet with some information.

Image of menu

We can add some status reports to our workflow now by injected in some appropriate Write-Output statements.

Image of script

Now the runbook will send status messages to the output pane, as you can see here:

We now have confirmation that it's running properly!

At this point, we take the next big step: promoting to production and making it a real runbook (yes, Pinocchio, it's your time). This is done by clicking the Publish button after you click Save:

Image of menu

You will be prompted for confirmations to continue each time. When done, you'll get a happy status message like this one:

Image of message

You'll also notice that your runbook lettering is greyed out because it's now a production runbook. If you click Draft again, you'll notice a new option to edit the existing production runbook. Go ahead!

Image of message

When you click Edit, you'll see a copy of your production runbook. Take note of the operative word "copy." If you make changes, you are not editing the main runbook. Nothing will change in the main runbook until you save and publish again. As shown here, you'll see a DiscardDraft button now, which allows you to scrap the current draft:

Image of script

Now that we have a functional runbook, the next step is running it.

That we will. Tomorrow...

Tomorrow, young scripter. We'll end the week on a solid note with Windows PowerShell!

I invite you to follow The Scripting Guys on Twitter and Facebook. If you have any questions, send an email to The Scripting Guys at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then remember eat your cmdlets every day with a taste of creativity.

Sean Kearney, Windows PowerShell MVP and Honorary Scripting Guy 


PowerTip: Start Azure Automation Job from PowerShell

$
0
0

Summary: Use Azure PowerShell cmdlets to launch a remote Azure Automation job.

Hey, Scripting Guy! Question How can I trigger an Azure Automation job from a regular computer?

Hey, Scripting Guy! Answer Use the Start-AzureAutomationRunbook cmdlet. For example, to trigger the runbook called 
           HSG-StopAzureVM that is attached to the HSG-AzureAutomation instance, run:

Start-AzureAutomationRunbook -Name HSG-ShutdownAzureVM -AutomationAccountName HSG-AzureAutomation

Using Azure Automation: Part 5

$
0
0

Summary: Schedule an Azure Automation runbook to get Azure to work for you.

Honorary Scripting Guy, Sean Kearney, is here to show you the most importance piece of Azure Automation: the actual scheduling of runbooks to allow you to let Azure do all the automation for you! This is the final post in a five-part series. To catch up, read: 

Yesterday, we finished our script to power down the virtual machines in Microsoft Azure, including sending some output to indicate the status of the shutdown.

If we go back into our runbook, things look a little different now. Instead of defaulting to the draft editing window, we are in the published runbook window as shown here:

Image of menu

Clicking Start will trigger the runbook just as if you were at a Windows PowerShell command prompt running a script.

You will see a status bar that indicates that the job is running. You can check the status of the job by selecting the View Job option on the status bar in Azure. Clicking this will open a status window that shows you the ongoing results of the job:

Image of menu

Drilling down further (near the bottom), we can view the Output. This window will show us any output that would normally echo to a Windows PowerShell console, including the data we specified with the Write-Output cmdlet.

Image of menu

If you look at the upper right of the screen, you'll see a History tab, which allows you to view a log of the working runbooks.

But now for the fun stuff...setting this as scheduled task. As shown here, to the right of Author, you'll see a tab marked Schedule. Click that to begin creating a schedule.

Image of menu

With a new Azure Automation instance, you'll have a blank schedule as you see in the following image. It has two simple options: Link to a New Schedule or Link to an Existing Schedule.

Click Link to a New Schedule to create a new schedule for your Azure Automation runbook.>>5

The first part will require a name and a description for the scheduled task. Again lets be sensible. Naming the scheduled task "Marvin the Paranoid Android" might be funny, but it won't make a lick of sense later (unless your description is really good—but even then, I wouldn't suggest that).

In the following example, we call this scheduled task EndOfDayShutdownTask:

Image of menu

If we click our friendly neighborhood checkmark to continue, we'll see that we have three basic scheduling options:

  • One time: Do this once and only once.
  • Hourly: Repeat on a scheduled hourly cycle (minimum every hour, but you can increase the gap).
  • Daily: Repeat this on a scheduled daily cycle (minimum every day, but you can increase the gap).

With the daily and hourly choices, you can also provide a date that this should stop running. In our example, this task will occur every day (Saturdays and Sundays included) at 5 P.M.:

Image of menu

We'll click that lovely little checkmark at the bottom of the wizard. Our schedule is created, and we can see our runbook set up as an available job:

Image of menu

As shown here, you'll see three for options for your scheduled runbook. They are Link, View Details,and Unlink:

Image of menu

Link is the same wizard you previously saw on the screen. Unlink allows you to remove that runbook as a scheduled task.

Now here is where you can schedule a runbook the fun way. If you'd like to use Windows PowerShell to do exactly what we just did, you can! In the Azure module, there is a cmdlet called New-AzureAutomationSchedule. We could use it do define our daily schedule like so:

$StartTime=(GET-Date "17:00")

$AzureAutomationAccount='HSG-AzureAutomation'

$TaskName='EndOfDayShutdownTask'

$DailyFrequency=1

$Description='Daily Task to occur at 5pm EST to shut down my Azure VMs'

New-AzureAutomationSchedule –AutomationAccountName $AzureAutomationAccount –Name $TaskName –Starttime $StartTime –DailyInterval $DailyFrequency –Description $Description

There is, of course, far more that you can do. This series has given you a quick entry level introduction to Azure Automation. If nothing else, it's a great way to keep costs under control when people forget to shut things down at the end of the day!

I invite you to follow The Scripting Guys on Twitter and Facebook. If you have any questions, send an email to The Scripting Guys at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then remember eat your cmdlets every day with a taste of creativity.

Sean Kearney, Windows PowerShell MVP and Honorary Scripting Guy 

PowerTip: Get List of Scheduled Job Results in Azure Automation

$
0
0

Summary: Use Azure cmdlets to audit for scheduled job results in Azure Automation.

Hey, Scripting Guy! Question How can I use Windows PowerShell to view the results of my scheduled runbooks in Azure Automation?

Hey, Scripting Guy! Answer Use the Get-AzureAutomationJob cmdlet from the Azure PowerShell module. For example, to see the results
           of all jobs in the 'HSG-AzureAutomation' instance, type:

Get-AzureAutomationJob –automationAccountname 'HSG-AzureAutomation'

Weekend Scripter: Find Coolest PowerShell Parameter Names

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about finding the coolest Windows PowerShell parameter names.

Microsoft Scripting Guy, Ed Wilson, is here. This morning, my friend and colleague, Dr. Thomas Shinder, posted on Facebook that his favorite Windows PowerShell parameter name is –NoClobber. Interestingly enough, when I was writing my Windows PowerShell Step by Step book, one of the editors suggested that I change –NoClobber to something else. I had to tell her that I could not change it because it was actually part of the code.

So what are the parameters that are used by Windows PowerShell cmdlets and functions? To an extent, that depends on what modules are installed. For example, I have the MSOnline module installed, in addition to the PSCX module. So, the available parameters on my system could be a bit different than those on your system. Luckily, I can use Windows PowerShell to solve the problem.

The first thing I like to do is look at one cmdlet. If I can find the information I want with one cmdlet, I can easily abstract the methodology to all cmdlets and functions. For exploration, I will use the Get-Alias cmdlet. Obviously, I will be using the Get-Command cmdlet because it knows how to look at cmdlets. Here is my first foray:

PS C:\> Get-Command Get-Alias

CommandType     Name                            ModuleName

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

Cmdlet               Get-Alias                          Microsoft.PowerShel...

OK. That was not too exciting. So I decide to pipe the output to the Format-List cmdlet:

Get-Command Get-Alias | Format-List *

In the following image, I can see that there is lots of cool information that Get-Command obtains about the Get-Alias cmdlet:

Image of command output

I know that I am most interested in the Parameters property. I also can see from the previous image that there are objects stored in the Parameters property, so I know that I want to expand the property. To do this, I pipe the output to the Select-Object cmdlet (Select is an alias), and I use the –ExpandProperty parameter:

Get-Command Get-Alias | select -ExpandProperty parameters

The output from the command is shown here:

Image of command output

Obviously, I need the Key property. As shown here, when I select the Key property, nothing happens:

PS C:\> Get-Command Get-Alias | select -ExpandProperty parameters | select key

key

---

What has happened is that they renamed the property. I find this by piping the output to the Get-Member cmdlet (gm is an alias). I see the property is actually Keys.

PS C:\> Get-Command Get-Alias | select -ExpandProperty parameters | gm

   TypeName: System.Collections.Generic.Dictionary`2[[System.String, mscorlib,

Version=4.0.0.0, Culture=neutral,

PublicKeyToken=b77a5c561934e089],[System.Management.Automation.ParameterMetadata,

System.Management.Automation, Version=3.0.0.0, Culture=neutral,

PublicKeyToken=31bf3856ad364e35]]

Name              MemberType            Definition

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

Add               Method                void Add(string key, System.Management.Automat...

Clear             Method                void Clear(), void ICollection[KeyValuePair[st...

Contains          Method                bool ICollection[KeyValuePair[string,Parameter...

ContainsKey       Method                bool ContainsKey(string key), bool IDictionary...

ContainsValue     Method                bool ContainsValue(System.Management.Automatio...

CopyTo            Method                void ICollection[KeyValuePair[string,Parameter...

Equals            Method                bool Equals(System.Object obj)

GetEnumerator     Method                System.Collections.Generic.Dictionary`2+Enumer...

GetHashCode       Method                int GetHashCode()

GetObjectData     Method                void GetObjectData(System.Runtime.Serializatio...

GetType           Method                type GetType()

OnDeserialization Method                void OnDeserialization(System.Object sender), ...

Remove            Method                bool Remove(string key), bool IDictionary[stri...

ToString          Method                string ToString()

TryGetValue       Method                bool TryGetValue(string key, [ref] System.Mana...

Item              ParameterizedProperty System.Management.Automation.ParameterMetadata...

Comparer          Property              System.Collections.Generic.IEqualityComparer[s...

Count             Property              int Count {get;}

IsFixedSize       Property              bool IsFixedSize {get;}

IsReadOnly        Property              bool IsReadOnly {get;}

IsSynchronized    Property              bool IsSynchronized {get;}

Keys              Property              System.Collections.Generic.Dictionary`2+KeyCol...

SyncRoot          Property              System.Object SyncRoot {get;}

Values            Property              System.Collections.Generic.Dictionary`2+ValueC...

In the following command, I choose the Keys property:

(Get-Command  | select -ExpandProperty parameters).keys

As shown here, I receive a rather random output of parameter names:

Image of command output

I want to sort the parameter names, and I also want to group them. I do not want the elements, so I come up with the following command:

(Get-Command  | select -ExpandProperty parameters).keys | sort | group –NoElement

The command and its associated output are shown here:

Image of command output

This gives me an alphabetical list of parameters. If I want to find the coolest parameter names, all I need to do is to scroll down the list. There are some pretty cool ones, but I think I like –XPATH…it is sort of like an XFiles, only different.

What cmdlet uses XPath as a parameter name? Easy. I use the Get-Command cmdlet to find it. Here is the command and output:

PS C:\> Get-Command -ParameterName xpath

CommandType     Name                           ModuleName

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

Cmdlet               Select-Xml                     Microsoft.PowerShel...

If I want to see which parameters are most popular, I simply add an additional sort. This command is shown here:

(Get-Command  | select -ExpandProperty parameters).keys | sort | group –NoElement | sort count –Descending

The command and its associated output are shown in the following image:

Image of command output

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 Which PowerShell Cmdlets Contain Specific Parameter

$
0
0

Summary: Find which Windows PowerShell cmdlets contain a specific parameter.

Hey, Scripting Guy! Question How can I find which cmdlets contain the –Force parameter?

Hey, Scripting Guy! Answer Use the Get-Command cmdlet and specify the parameter name, for example:

Get-Command -ParameterName force

Weekend Scripter: Best PowerShell Resources on the Web

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about the best fundamental resources on the web for Windows PowerShell.

Microsoft Scripting Guy, Ed Wilson, is here. One of the great things about the Microsoft Ignite conference in Chicago was getting to see and talk with so many people. Previously, there was a core group of people who went to TechEd and a core group of people who went to MEC, but there were not many people who went to both. As a result, groups were pigeon-holed. By combining the conferences into one giant conference, we were able to see, talk to, and meet people that otherwise would not be in our circles. This was true for me and for other people who attended the conference.

I got to talk to a lot of people who were looking at Windows PowerShell for the first time. One person asked me, "What are the fundamental resources for learning about Windows PowerShell, for getting together with other people who use Windows PowerShell, and for finding out how to begin learning Windows PowerShell?"

So I have compiled some links to the fundamentals—some of the best places to learn about Windows PowerShell.

User groups

For me, getting connected with a user group is the most basic thing you can do. In a user group, you will find others who are learning Windows PowerShell and those who are experts in the subject. This diversity of learning helps. Like in college, sometimes the graduate teaching assistant is a better teacher than the professor for a level 101 class because they recently learned the material. Sometimes a beginner in Windows PowerShell can help point the way better than a Windows PowerShell MVP. There are two basic places to find Windows PowerShell user groups:

Forums

Next to user groups, an awesome place to start is a user support forum. There are several forums available for users of Windows PowerShell. One thing to keep in mind is that when asking a question, you should always try to solve the problem first. You should state what you tried and why it did not work.

A Windows PowerShell forum is not a place to ask for a Windows PowerShell script. So, you should not say, “I need a script that does this, this, and this. Can someone write it for me?”

Instead, you might say, "I need a script that does this, this, and that. I found some code that does this and this, but I still cannot find out how do that. I tried searching MSDN and the Hey, Scripting Guy! Blog, but I did not find anything. Can someone point me to a location that can help me?"

Here is a list of good forum locations:

Script Center Repository

I said that with forums, you should not say, “I need a script.” But in the Script Center Repository, we actually have a feature called What script do we need? The way this works is that you request a script, and maybe someone else will see the request and vote that they also need the script. Eventually, if enough people vote for the script, maybe it will be written.

This is not a free script service, but it is a great place to request a script if you have tried everything else, and you simply cannot figure it out. At this point in time, there are over 11,000 scripts in the Script Center Repository, so in all likelihood, there is already a script that does basically what you need—but hey, who knows.

If you can only find a script in another scripting language, it does not mean that you are out of luck. If the sample is in Perl, Java, or even VBScript, there is a good chance you can look at it, figure out what it does, and use that as a starting point in making a way cool Windows PowerShell script.

By the way, of the 11,000 scripts, over 5,700 are Windows PowerShell, so we now have more Windows PowerShell scripts than anything else. WooHoo! Here is the link:

MVPs

MVPs are a valuable resource of knowledge. They are MVPs because they love the product and because they love sharing their knowledge with others. If you are ready, you can find a Windows PowerShell user group that has one or more MVPs associated with it.

But there are more than only Windows PowerShell MVPs—there are MVPs for all Microsoft specialties (in some form). Here is the list of MVPs, which is updated quarterly:

Blogs

There are many blogs about Windows PowerShell or that have content related to Windows PowerShell. I am going to weasel out and only mention two: The Hey, Scripting Guy! Blog and the Windows PowerShell Team blog.

Of course, the Hey, Scripting Guy! Blog has more Windows PowerShell content than any other blog on the Internet, and it is written by more people than me. I have had hundreds of guest bloggers over the years, who have written about some way cool, and sometimes downright strange, Windows PowerShell stuff. It is one of the things that makes the blog fun. The Honorary Scripting Guys are the real strength of the Hey, Scripting Guy! Blog.

Of course, for the latest and greatest information about what is new with Windows PowerShell, check out the Windows PowerShell team blog. It contains great insights as to where Windows PowerShell is going.

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: Use PowerShell to Create New File

$
0
0

Summary: Create a new file with Windows PowerShell.

Hey, Scripting Guy! Question How can I use Windows PowerShell to create a new text file that will be empty until I add content?

Hey, Scripting Guy! Answer Use the New-Item cmdlet and specify a path, name, and type, for example:

New-Item c:\fso\AnEmptyFile.txt -ItemType file


Find PowerShell Reference Documentation

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about where to find Windows PowerShell reference documentation.

Microsoft Scripting Guy, Ed Wilson, is here. I am eagerly anticipating Saturday because Saturday is the Jacksonville IT Pro Camp, and the Scripting Wife and I will be speaking. I believe there are still tickets available, so if you are in the area, you should definitely check it out. It will be an awesome time.

In addition to giving the Keynote, I think I am doing two additional sessions. It will be tremendous fun. The last time we were down there (a couple of years ago), we got to see some friends who we had not seen in a long time, and this should also be a special time with them.

Speaking of presentations...

The other day, I was making a presentation at the Cincinnati Windows PowerShell User Group. After the presentation, a person came up to me and asked about Windows PowerShell reference documentation. Basically, he said, "Where is it?"

This stumped me for a minute, and I started to say, "Well, there are a bunch of videos on Channel 9, MVA, and even YouTube, that talk about Windows PowerShell, and…"

Then he cut me off. He said, "I know I can find stuff that talks about how to learn Windows PowerShell or how to use Windows PowerShell, but where is a systematic presentation of Windows PowerShell itself?"

And I say, "Well, there is the Help, the cmdlet documentation, and the About conceptual articles..."

And he stops me again. "No," he said, "I need something better organized and put together than that."

OK! Welcome to Windows PowerShell Fundamentals Week. Today I am providing some links to what I consider good reference documentation for Windows PowerShell.

TechNet Library

The TechNet Library is the basic place to start for people seeking Windows PowerShell documentation and reference material. It has a collection of great information from our official Windows PowerShell documentation team. In addition, to documenting new features for each version of Windows PowerShell, there are a number of conceptual articles and an awesome collection of links to other references about Windows PowerShell. This is the number one place to start:

Books

One of the great things about Windows PowerShell is there are a lot of books about the subject. Hey, go to Amazon or some other place and look for all the great books about Windows PowerShell. I am highlighting three publishers, but there are many others. Microsoft Press has a number of books about Windows PowerShell, as do O’Reilly and Manning Publications.

Windows PowerShell Language Specification

A great free resource is the Windows PowerShell Language Specification. This is the technical document that tells you exactly how Windows PowerShell works. Versions were created for Windows PowerShell 2.0 and Windows PowerShell 3.0. I printed this reference, and had it bound. It sits near my desk, and I reference it on a regular basis.

This is a tremendous resource. I guarantee that if you read it from cover to cover, you will discover at least one thing you did not know about Windows PowerShell. Me? I learn something new each time I pick it up. Here is a link to the Windows PowerShell 3.0 version

That is all there is to finding the best Windows PowerShell reference materials. 

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: Use PowerShell to Add Content to File

$
0
0

Summary: Learn how to use Windows PowerShell to add content to a file.

Hey, Scripting Guy! Question How can I use Windows PowerShell to add content to a file?

Hey, Scripting Guy! Answer Use the Add-Content cmdlet, and specify the path to the file and the value of the content, for example:

Add-Content C:\fso\AnEmptyFile.txt -Value "This is content"

Help! It Says PowerShell…Now What?

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about how to run a Windows PowerShell command.

Hey, Scripting Guy! Question Hey, Scripting Guy! Help! I am reading through TechNet, and I found this command that seems like it will solve my problem, but I do not know how to do it. It says something about Windows PowerShell, but I do not know what that is, or how to run the command. I opened the command prompt, but all it did was give me errors. So where do I type the command?

—WB

Hey, Scripting Guy! Answer Hello WB,

Microsoft Scripting Guy, Ed Wilson, is here. One of the bad things about working at Microsoft, is that time sort of becomes skewed. By this, I mean that it is hard to remain in sync with the rest of the world. What am I talking about?

Well, I have been using Windows PowerShell 5.0 for a long time, and yet, Windows PowerShell 5.0 has not even released. I began using Windows PowerShell before it was even called Windows PowerShell, so I tend to think that everyone is using Windows PowerShell. In fact, the other day, I was speaking at a Windows PowerShell user group, and I pretty much assumed that everyone knew what Windows PowerShell was, and that they were using it. As I found out after the meeting, this is not the case.

In fact, when I was at Ignite in Chicago, I talked to several people who had not ever used Windows PowerShell—and it seemed that they had not even heard of Windows PowerShell. "Strange," I thought.

I pretty much assumed that everyone knows about Windows PowerShell, and has been using it for a long time—at least, that is my world. But Microsoft is not the rest of the world. I even talked to a person at Ignite, who said they were still running Windows 2000 on some of their servers.

Basic Windows PowerShell

Where do I get Windows PowerShell? If you have Windows 7, you have Windows PowerShell 2.0 already installed. If you have Windows 8, you have Windows PowerShell 3.0, and if you have Windows 8.1, you have Windows PowerShell 4.0. If you want to install Windows PowerShell 4.0 on Windows 7, you can refer to this blog post by Windows PowerShell MVP, Teresa Wilson, where she take you through the installation process step-by-step: Install PowerShell 4.0 in Windows 7.

When you have Windows PowerShell installed, you need to launch it. You can do this by simply typing PowerShell on the Windows 8.1 or Windows 8 Start screen. When you start to type, the Search dialog box appears automatically. In Windows 7, use the Start/Search command and type PowerShell.

There are actually two (maybe 4) versions of Windows PowerShell: the Windows PowerShell x86 version and x64 version. Plus there are the same potential flavors of the Windows PowerShell ISE. The Windows PowerShell ISE is the script editor, and for this exercise you do not need to start the ISE.

I like to create a shortcut to Windows PowerShell and place it on my desktop. To do this, I right-click the desktop and choose New/Shortcut from the action menu, type PowerShell in the dialog box, and click next.

When Windows PowerShell first launches, support for scripts is disabled. This is fine because I do not need to run a script right now. All I want to do is to run a Windows PowerShell command.

Running a Windows PowerShell command

As an example, I can obtain a list of all the processes on my system. To do this, I use the Get-Process cmdlet. Cmdlets are Windows PowerShell commands that return information. I can simply type Get-Process (that is a hyphen in between the words Get and Process). By the way, I do not have to capitalize Get and Process, I can type get-process and the command works fine. Here is the command and the output:

Image of command output

Using Tab expansion

I also do not have to type the entire words Get and Process if I do not want to do so. I can simply type Get-Pro and then press the Tab key. When I do this, Windows PowerShell uses what is called Tab expansion, and it will complete the command for me. If I type Get-P and then press the Tab key, I will have to press the Tab key 20 or so times until I finally get to Get-Process. If I type Get-Pr and then press Tab key, I will need to press the Tab key a dozen or so times.

So I have a choice of typing more of the command name, and hitting the Tab key less, or typing less of the command name, and hitting the Tab key more. If I start hitting the Tab key a bunch of times really quickly, and I go too far (meaning I see the command flash on the screen, and then I go to the next one accidently), I have two choices:

  • I can continue pressing the Tab key and cycle through all the options again.
  • I can hold down the Shift key while I hit the Tab key, and it will cycle through the options in reverse.

So if I went two command names too far, I would hold down the Shift key and hit the Tab key only twice.

 Using WhatIf

If I am going to use a command and I do not know what it will do (such as Stop-Process), I can use the –WhatIf parameter. This will permit to see what would happen if I were to run the command for real. Or to think of it another way, “What would happen if I run this command?”

I can use the –WhatIf parameter for any Windows PowerShell cmdlet that will make a change to my system. This means the cmdlet will create something (New), change something (Set), delete something (Remove), or stop something (Stop).

Each Windows PowerShell cmdlet has a two-part name. The first part of the name is a verb, such as Get, Set, Stop, or Remove. The second part of the name is a noun, such as Process or Service. So the two part names help me know what a cmdlet will do and remember the command name.

For example, if I want to start a process, I would use the Start verb and the Process noun: Start-Process. Another good thing is that the cmdlets are (mostly) singular. So it is Process, not Processes, and it is Service, not Services.

Because starting a process will change the state of my computer (by starting a service), it means that I can use the –WhatIf cmdlet. Here is an example:

start-service bits –WhatIf

Here is the command and the output from the command:

Image of command output

If I see a Windows PowerShell command in a TechNet article, and I am not sure what it will do, I take the following steps:

  1. Start Windows PowerShell.
  2. Copy the Windows PowerShell code from the article.
  3. Paste the Windows PowerShell code from the article into the Windows PowerShell console and make sure that I add the –WhatIf parameter to the command.
  4. Press ENTER to run the command. I should see an output similar to that shown in the previous image, which tells me what the command will do.
    • If I like what it will do, then I press the Up arrow to retrieve the command that I just pasted, and I delete the
      –WhatIf parameter and press ENTER to run the command for real.
    • If I do not like what the command will do, I close Windows PowerShell by clicking the X in the upper-right corner of the Windows PowerShell console window. This will keep me from accidently running the command.

For example, if I copy a command into my Windows PowerShell console, I add the –WhatIf parameter, and it returns an output such as I see in the following image, I know that I do not want to run that command. So I close the Windows PowerShell console to avoid making a mistake that will crash my system.

Image of command output

WB, that is all there is to using a Windows PowerShell command. Windows PowerShell Fundamentals Week will continue tomorrow when I will talk about more cool Windows PowerShell 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: Convert to Decimals and Display Unicode Characters

$
0
0

Summary: Use Windows PowerShell to convert hexadecimal values to decimal and display Unicode characters.

Hey, Scripting Guy! Question I found a cool Unicode table on the Internet, but all of the values are displayed as hexadecimal values.
           How can I use Windows PowerShell to translate them to integers and display the Unicode characters?

Hey, Scripting Guy! Answer Use the [Convert] class, call the ToInt32 method, specify the value and 16, and call the [char] class so you
           can convert the character to its Unicode character, for example:

PS C:\> [convert]::ToInt32("2326",16)

8998

PS C:\> [char]8998

Note  Use the Windows PowerShell ISE because the Windows PowerShell console does not always display
Unicode characters properly.

Windows PowerShell, Scripting Guy!, PowerTip

Help: It Says Run a PowerShell Script

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about running a Windows PowerShell script.

Microsoft Scripting Guy, Ed Wilson, is here. Ninety two degrees Fahrenheit and sunny—that is what the weather is supposed to be this Saturday in Jacksonville when Teresa and I will be speaking at the Jacksonville IT Pro Camp.

I can’t think of a better way to spend a sunny day in Jacksonville, Florida than in a building with the air conditioning on high, and talking about the way cool stuff in Windows PowerShell. Well, maybe I could think of one or two other things to do, but certainly, IT Pro Camp is at the top of the list.

Is it a script?

A Windows PowerShell script is not a script until it is saved with a .ps1 file extension. So, if I copy a script directly from anywhere, and paste it into the Windows PowerShell ISE, and I do not save it, it is not a script.

In the following image, I have copied a random script from the Script Center Repository. I pasted it into the Windows PowerShell ISE, but I have not saved it.

Image of script

I could run the script, modify the script, or whatever I want to do with it. But if the title pane says Untitled*.ps1, it is not actually a script. So regardless of the Windows PowerShell script execution policy, I can run a script here.

Script execution policies

When I first open Windows PowerShell on a client computer running Windows 7 or later, the script execution policy is set to Restricted (actually, this was also the case for Windows PowerShell 1.0). On the server side of the house, beginning with Windows Server 2008 R2, the Windows PowerShell script execution policy was set to Remote Signed, which means that scripts downloaded from a remote location must be signed to run without prompting.

I can see the script execution policy by using the Get-ExecutionPolicy cmdlet:

PS C:\> Get-ExecutionPolicy

Unrestricted

But there is more than one script execution policy. To see the value of all of the script execution policies, I use the Get-ExecutionPolicy cmdlet with the –List parameter. This is shown here:

Image of command output

To change the script execution policy, I use Set-ExecutionPolicy cmdlet. If I want to change the script execution policy for only myself, I can use the –Scope and specify CurrentUser, for example:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

When I run the Set-ExecutionPolicy cmdlet, the following prompt appears:

Image of menu

To bypass this prompt, use the –Force parameter. The command is shown here:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force

Script execution policy via Group Policy settings

If the network administrator sets a Windows PowerShell script execution policy with a Group Policy setting, I cannot change my local script execution policy—even to make it more restrictive.  For example, if the network administrator set the script execution policy to Remote Signed, but I thought it would make more sense to set it to All Signed, I could not do that. This is why it is important to look at the results of Get-ExecutionPolicy –List when troubleshooting script execution in Windows PowerShell.

If no policy is set via Group Policy (these are the Computer Configuration and the User Configuration settings), I can set a script execution policy for all users on a computer (Local Computer Group Policy setting) if I have local admin rights and if I open the Windows PowerShell console with elevated rights.

I normally, do not do that however. Instead, I prefer to set the policy only for the current user (which is me), and I do not have to open the Windows PowerShell console with elevated rights to do that. I can do it in a non-elevated manner. I did this earlier when I set the –Scope for CurrentUser.

If I need to run scripts, and I am running with non-elevated rights, and if a Group Policy setting has not disallowed me from running scripts, I can set my Windows PowerShell script execution policy easily. I just use Set-ExecutionPolicy and apply the appropriate policy to the CurrentUser scope.

Of course, there are lots of caveats to consider, but this will get you up and running quickly.

Windows PowerShell Fundamentals 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: Use PowerShell to Add Content to File Stream

$
0
0

Summary: Use Windows PowerShell to add content to the file system stream of a file.

Hey, Scripting Guy! Question How can I use Windows PowerShell to add data to an alternate NTFS file system stream of a file?

Hey, Scripting Guy! Answer Use the Add-Content cmdlet and specify the name of the stream for the Stream parameter,
           then specify the data in the –Value parameter, for example:

Add-Content C:\fso\AnEmptyFile.txt -Stream Data -Value "datastream"

Note If the stream does not exist, Windows PowerShell creates it. 

Table of Basic PowerShell Commands

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, provides a table of basic Windows PowerShell commands.

Microsoft Scripting Guy, Ed Wilson, is here. Some questions are simply confusing, and other questions can be misleading, or even wrong. What do I mean? Well, I recently received a question from a person who wanted to know how to “use WMI to do xyz…”

Such a question betrays an assumption. For example, it may be that the best way to accomplish a specific task is to not use WMI, but to use “native Windows PowerShell” functionality. Certainly, for example, I would use Get-Process to retrieve process information on my local computer—unless there was something that WMI would do differently or provide an alternate capability.

At times, I will clarify a person's question, intention, and goals. At other times, I will directly answer the question, and then suggest a better way to accomplish what I think the goal is. Other times, I will answer what I think their question is and be done with it.

When a person asks about Windows PowerShell commands, are they really talking about native Windows PowerShell commands (such as the language statements For, Foreach, or Switch)? Or are they talking about Windows PowerShell cmdlets? Or are they talking about a string of Windows PowerShell cmdlets that taken together become a unique Windows PowerShell command?

When I am writing my Windows PowerShell books (such as my book, Windows PowerShell Best Practices), I tend to call a collection of Windows PowerShell cmdlets that are strung together to accomplish a specific task in a Windows PowerShell command.

But at other times, I actually vary my answer according to what I perceive to be the level of expertise of the questioner. For example, often people will come to me after I have spoken at a conference (such as the IT Pro Camp in Jacksonville where Teresa and I will be speaking this Saturday). If they ask something like, “I know nothing about Windows PowerShell. Can you tell me the most basic Windows PowerShell commands?” I will not necessarily take the time to tell them that they are probably asking about cmdlets, not commands.

With this in mind, the following chart lists Windows PowerShell command aliases, the Windows PowerShell cmdlet name, and a description of what the command actually does.

Command alias

Cmdlet name

Description of command

%

ForEach-Object

Performs an operation against each item in a collection of input objects.

?

Where-Object

Selects objects from a collection based on their property values.

ac

Add-Content

Appends content, such as words or data, to a file.

asnp

Add-PSSnapIn

Adds one or more Windows PowerShell snap-ins to the current session.

cat

Get-Content

Gets the contents of a file.

cd

Set-Location

Sets the current working location to a specified location.

chdir

Set-Location

Sets the current working location to a specified location.

clc

Clear-Content

Deletes the contents of an item, but does not delete the item.

clear

Clear-Host

Clears the display in the host program.

clhy

Clear-History

Deletes entries from the command history.

cli

Clear-Item

Deletes the contents of an item, but does not delete the item.

clp

Clear-ItemProperty

Deletes the value of a property but does not delete the property.

cls

Clear-Host

Clears the display in the host program.

clv

Clear-Variable

Deletes the value of a variable.

cnsn

Connect-PSSession

Reconnects to disconnected sessions

compare

Compare-Object

Compares two sets of objects.

copy

Copy-Item

Copies an item from one location to another.

cp

Copy-Item

Copies an item from one location to another.

cpi

Copy-Item

Copies an item from one location to another.

cpp

Copy-ItemProperty

Copies a property and value from a specified location to another location.

curl

Invoke-WebRequest

Gets content from a webpage on the Internet.

cvpa

Convert-Path

Converts a path from a Windows PowerShell path to a Windows PowerShell provider path.

dbp

Disable-PSBreakpoint

Disables the breakpoints in the current console.

del

Remove-Item

Deletes files and folders.

diff

Compare-Object

Compares two sets of objects.

dir

Get-ChildItem

Gets the files and folders in a file system drive.

dnsn

Disconnect-PSSession

Disconnects from a session.

ebp

Enable-PSBreakpoint

Enables the breakpoints in the current console.

echo

Write-Output

Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console.

epal

Export-Alias

Exports information about currently defined aliases to a file.

epcsv

Export-Csv

Converts objects into a series of comma-separated (CSV) strings and saves the strings in a CSV file.

epsn

Export-PSSession

Imports commands from another session and saves them in a Windows PowerShell module.

erase

Remove-Item

Deletes files and folders.

etsn

Enter-PSSession

Starts an interactive session with a remote computer.

exsn

Exit-PSSession

Ends an interactive session with a remote computer.

fc

Format-Custom

Uses a customized view to format the output.

fl

Format-List

Formats the output as a list of properties in which each property appears on a new line.

foreach

ForEach-Object

Performs an operation against each item in a collection of input objects.

ft

Format-Table

Formats the output as a table.

fw

Format-Wide

Formats objects as a wide table that displays only one property of each object.

gal

Get-Alias

Gets the aliases for the current session.

gbp

Get-PSBreakpoint

Gets the breakpoints that are set in the current session.

gc

Get-Content

Gets the contents of a file.

gci

Get-ChildItem

Gets the files and folders in a file system drive.

gcm

Get-Command

Gets all commands.

gcs

Get-PSCallStack

Displays the current call stack.

gdr

Get-PSDrive

Gets drives in the current session.

ghy

Get-History

Gets a list of the commands entered during the current session.

gi

Get-Item

Gets files and folders.

gjb

Get-Job

Gets Windows PowerShell background jobs that are running in the current session.

gl

Get-Location

Gets information about the current working location or a location stack.

gm

Get-Member

Gets the properties and methods of objects.

gmo

Get-Module

Gets the modules that have been imported or that can be imported into the current session.

gp

Get-ItemProperty

Gets the properties of a specified item.

gps

Get-Process

Gets the processes that are running on the local computer or a remote computer.

group

Group-Object

Groups objects that contain the same value for specified properties.

gsn

Get-PSSession

Gets the Windows PowerShell sessions on local and remote computers.

gsnp

Get-PSSnapIn

Gets the Windows PowerShell snap-ins on the computer.

gsv

Get-Service

Gets the services on a local or remote computer.

gu

Get-Unique

Returns unique items from a sorted list.

gv

Get-Variable

Gets the variables in the current console.

gwmi

Get-WmiObject

Gets instances of Windows Management Instrumentation (WMI) classes or information about the available classes.

h

Get-History

Gets a list of the commands entered during the current session.

history

Get-History

Gets a list of the commands entered during the current session.

icm

Invoke-Command

Runs commands on local and remote computers.

iex

Invoke-Expression

Runs commands or expressions on the local computer.

ihy

Invoke-History

Runs commands from the session history.

ii

Invoke-Item

Performs the default action on the specified item.

ipal

Import-Alias

Imports an alias list from a file.

ipcsv

Import-Csv

Creates table-like custom objects from the items in a CSV file.

ipmo

Import-Module

Adds modules to the current session.

ipsn

Import-PSSession

Imports commands from another session into the current session.

irm

Invoke-RestMethod

Sends an HTTP or HTTPS request to a RESTful web service.

ise

powershell_ise.exe

Explains how to use the PowerShell_ISE.exe command-line tool.

iwmi

Invoke-WMIMethod

Calls Windows Management Instrumentation (WMI) methods.

iwr

Invoke-WebRequest

Gets content from a web page on the Internet.

kill

Stop-Process

Stops one or more running processes.

lp

Out-Printer

Sends output to a printer.

ls

Get-ChildItem

Gets the files and folders in a file system drive.

man

help

Displays information about Windows PowerShell commands and concepts.

md

mkdir

Creates a new item.

measure

Measure-Object

Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text.

mi

Move-Item

Moves an item from one location to another.

mount

New-PSDrive

Creates temporary and persistent mapped network drives.

move

Move-Item

Moves an item from one location to another.

mp

Move-ItemProperty

Moves a property from one location to another.

mv

Move-Item

Moves an item from one location to another.

nal

New-Alias

Creates a new alias.

ndr

New-PSDrive

Creates temporary and persistent mapped network drives.

ni

New-Item

Creates a new item.

nmo

New-Module

Creates a new dynamic module that exists only in memory.

npssc

New-PSSessionConfigurationFile

Creates a file that defines a session configuration.

nsn

New-PSSession

Creates a persistent connection to a local or remote computer.

nv

New-Variable

Creates a new variable.

ogv

Out-GridView

Sends output to an interactive table in a separate window.

oh

Out-Host

Sends output to the command line.

popd

Pop-Location

Changes the current location to the location most recently pushed to the stack. You can pop the location from the default stack or from a stack that you create by using the Push-Location cmdlet.

ps

Get-Process

Gets the processes that are running on the local computer or a remote computer.

pushd

Push-Location

Adds the current location to the top of a location stack.

pwd

Get-Location

Gets information about the current working location or a location stack.

r

Invoke-History

Runs commands from the session history.

rbp

Remove-PSBreakpoint

Deletes breakpoints from the current console.

rcjb

Receive-Job

Gets the results of the Windows PowerShell background jobs in the current session.

rcsn

Receive-PSSession

Gets results of commands in disconnected sessions.

rd

Remove-Item

Deletes files and folders.

rdr

Remove-PSDrive

Deletes temporary Windows PowerShell drives and disconnects mapped network drives.

ren

Rename-Item

Renames an item in a Windows PowerShell provider namespace.

ri

Remove-Item

Deletes files and folders.

rjb

Remove-Job

Deletes a Windows PowerShell background job.

rm

Remove-Item

Deletes files and folders.

rmdir

Remove-Item

Deletes files and folders.

rmo

Remove-Module

Removes modules from the current session.

rni

Rename-Item

Renames an item in a Windows PowerShell provider namespace.

rnp

Rename-ItemProperty

Renames a property of an item.

rp

Remove-ItemProperty

Deletes the property and its value from an item.

rsn

Remove-PSSession

Closes one or more Windows PowerShell sessions (PSSessions).

rsnp

Remove-PSSnapin

Removes Windows PowerShell snap-ins from the current session.

rujb

Resume-Job

Restarts a suspended job

rv

Remove-Variable

Deletes a variable and its value.

rvpa

Resolve-Path

Resolves the wildcard characters in a path, and displays the path contents.

rwmi

Remove-WMIObject

Deletes an instance of an existing Windows Management Instrumentation (WMI) class.

sajb

Start-Job

Starts a Windows PowerShell background job.

sal

Set-Alias

Creates or changes an alias (alternate name) for a cmdlet or other command element in the current Windows PowerShell session.

saps

Start-Process

Starts one or more processes on the local computer.

sasv

Start-Service

Starts one or more stopped services.

sbp

Set-PSBreakpoint

Sets a breakpoint on a line, command, or variable.

sc

Set-Content

Replaces the contents of a file with contents that you specify.

select

Select-Object

Selects objects or object properties.

set

Set-Variable

Sets the value of a variable. Creates the variable if one with the requested name does not exist.

shcm

Show-Command

Creates Windows PowerShell commands in a graphical command window.

si

Set-Item

Changes the value of an item to the value specified in the command.

sl

Set-Location

Sets the current working location to a specified location.

sleep

Start-Sleep

Suspends the activity in a script or session for the specified period of time.

sls

Select-String

Finds text in strings and files.

sort

Sort-Object

Sorts objects by property values.

sp

Set-ItemProperty

Creates or changes the value of a property of an item.

spjb

Stop-Job

Stops a Windows PowerShell background job.

spps

Stop-Process

Stops one or more running processes.

spsv

Stop-Service

Stops one or more running services.

start

Start-Process

Starts one or more processes on the local computer.

sujb

Suspend-Job

Temporarily stops workflow jobs.

sv

Set-Variable

Sets the value of a variable. Creates the variable if one with the requested name does not exist.

swmi

Set-WMIInstance

Creates or updates an instance of an existing Windows Management Instrumentation (WMI) class.

tee

Tee-Object

Saves command output in a file or variable and sends it down the pipeline.

trcm

Trace-Command

Configures and starts a trace of the specified expression or command.

type

Get-Content

Gets the contents of a file.

wget

Invoke-WebRequest

Gets content from a webpage on the Internet.

where

Where-Object

Selects objects from a collection based on their property values.

wjb

Wait-Job

Suppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are complete.

write

Write-Output

Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console.

Windows PowerShell Fundamentals Week will continue tomorrow when I will talk about more cool Windows PowerShell 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: Read NTFS File System Stream with PowerShell

$
0
0

Summary: Use Windows PowerShell to read a specific NTFS file system stream.

Hey, Scripting Guy! Question How can I use Windows PowerShell to read a specific NTFS file system stream?

Hey, Scripting Guy! Answer Use the Get-Content cmdlet and specify the name of the file and the name of the stream.
           This example reads a stream named Data:

Get-Content C:\fso\AnEmptyFile.txt -Stream data

Five Best PowerShell Cmdlets

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about the five best Windows PowerShell cmdlets.

Microsoft Scripting Guy, Ed Wilson, is here. OK, I will admit that this post is completely arbitrary. What do I mean when I talk about the five best Windows PowerShell cmdlets (commands)? Well, I am thinking about the cmdlets I use on a daily basis and the cmdlets that make my life really easy.

The best cmdlet: Get-Command

For me, the best Windows PowerShell cmdlet is probably Get-Command. I use this cmdlet every single day. In fact, I often use it multiple times a day. Why? Because I simply cannot remember thousands of cmdlet names. Even if I do remember thousands of cmdlet names, I cannot remember their various command sets and all of the available parameters. Here is an example:

S C:\> Get-Command -Noun *tcp*

CommandType     Name                                  ModuleName                         

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

Function        Get-NetTCPConnection                NetTCPIP                           

Function        Get-NetTCPSetting                       NetTCPIP                           

Function        Send-TcpRequest                         PowerShellCookbook                 

Function        Set-NetTCPSetting                        NetTCPIP                            

Other cool Windows PowerShell cmdlets

Get-Help

When I want to see exactly what a new cmdlet will do or find detailed information about a particular parameter, I turn to Get-Help. I also like to use Get-Help to look for examples of how to use a new cmdlet. Here is an example:

PS C:\> get-help Get-Command -Parameter verb

-Verb <String[]>

    Gets commands (cmdlets, functions, workflows, and aliases) that have names that include the

    specified verb. Enter one or more verbs or verb patterns. Wildcards are permitted.

    Required?                    false

    Position?                    named

    Default value                All verbs

    Accept pipeline input?       True (ByPropertyName)

    Accept wildcard characters?  false

Get-Member

Everyone knows that Windows PowerShell is object-oriented and that it returns objects instead of strings. But what kind of object is actually returned? What are the members, properties, and methods that are available from a specific object? To answer these and other types of questions such as this, I use Get-Member. Here is an example:

PS C:\> Get-Command | Get-Member -MemberType ScriptProperty

   TypeName: System.Management.Automation.AliasInfo

Name              MemberType        Definition                                                          

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

DisplayName         ScriptProperty System.Object DisplayName {get=if ($this.Name.IndexOf('-') -lt 0)...

HelpUri             ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPref...

ResolvedCommandName ScriptProperty System.Object ResolvedCommandName {get=$this.ResolvedCommand.Name;}

   TypeName: System.Management.Automation.FunctionInfo

Name              MemberType        Definition                                                          

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

HelpUri ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference...     

   TypeName: System.Management.Automation.FilterInfo

Name              MemberType        Definition                                                          

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

HelpUri ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference...     

   TypeName: System.Management.Automation.CmdletInfo

Name              MemberType        Definition                                                          

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

DLL     ScriptProperty System.Object DLL {get=$this.ImplementingType.Assembly.Location;}              

HelpUri ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference... 

The big three

Anyone who has ever read a book about Windows PowerShell, attended a class about Windows PowerShell, or even attended a one-hour introduction to Windows PowerShell session at a community event has heard about the big three cmdlets:

  • Get-Command
  • Get-Help
  • Get-Member

The cool thing about Windows PowerShell is that it is self-discovering. This means that I can use Windows PowerShell to discover how to use Windows PowerShell and how to continue to learn more things about Windows PowerShell.

I continue to use these three cmdlets every day, so learning nuances about the cmdlets pays great dividends. And how do I learn nuances about these three cmdlets? Well, by using the three cmdlets. For example, I can use the following commands:

  • Get-Help Get-Help                                                                                
  • Get-Command Get-Help                                                                             
  • Get-Help | Get-Member                                                                            

The other two

The other two cmdlets that I use on a daily basis are Select-Object and Out-GridView. Both of these cmdlets are very useful, and they help me solve problems. In addition, Out-GridView is a great exploring cmdlet.

Select-Object

One reason I use Select-Object so much is that it is an easy way to create a custom object. I can even use a script block to calculate a value, and then use the result as a value of a custom property. Because Windows PowerShell is object-oriented, the Select-Object cmdlet becomes even more important. Here is an example:

PS C:\> Get-Help Get-Member | Select-Object name, synopsis

Name                                    Synopsis                                          

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

Get-Member                         Gets the properties and methods of objects.        

Out-GridView

I use Out-GridView so much because it is an easy intermediate step that permits me to select columns or properties, filter data, and visualize what I am actually dealing with. Here is an example of such a command:

Get-Command -Verb get | Get-Help | Select-Object name, synopsis | Out-GridView

The output is shown in the following image:

Image of command output

That is all there is to using the five best Windows PowerShell cmdlets. Join me tomorrow when I will talk about more Windows PowerShell coolness.

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 Graphical PowerShell Help​

$
0
0

Summary: Learn how to display graphical Windows PowerShell Help.

Hey, Scripting Guy! Question How can I see Windows PowerShell Help in a graphical way so I can float the Help?

Hey, Scripting Guy! Answer Use the –ShowWindow parameter from the Get-Help cmdlet, for example:

Get-Help Get-Process -ShowWindow

Weekend Scripter: Jacksonville IT Pro Camp Is Here

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about the Jacksonville IT Pro Camp.

Microsoft Scripting Guy, Ed Wilson, is here. This is a day I have been looking forward to for some time—and now it is here. It is time for the Jacksonville IT Pro Camp. Teresa (aka The Scripting Wife) and I are keynoting the event. That is right. You will get a chance to hear her speak for a change. We will be talking about the importance of community and getting involved in community. It will be awesome.

I am also presenting two sessions. I will be doing the Data Grooming session that I presented at the Windows PowerShell Summit in Charlotte, and I will be talking about Windows PowerShell best practices. Both sessions are really fun.

My Data Grooming (or Garbage In/Garbage Out) session is similar to this Hey, Scripting Guy! Blog post: Oh No! Oh Wait...PowerShell for the Win! And my PowerShell Best Practices session is based in part to some information from my book, Windows PowerShell Best Practices.

You can register for the event on Eventbrite: IT Pro Camp Jacksonville 2015/ MTA Test Fest. The event is free, so the tickets are simply a way to make sure that too many people don’t overfill the rooms.

It runs from 8:00 A.M through 4:30 P.M. Attendance vouchers are provided for people who need to maintain CPE credits for certificates such as the CISSP, CISA, or CISM. This is a good way to pick up 6–8 hours of CPE credits. Make sure you request the voucher when you sign-in if you need to track your credits.

Hope to see you there.

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 All PowerShell Cmdlets Except…

$
0
0

Summary: Learn how to find all Windows PowerShell cmdlets except those from a specific module.

Hey, Scripting Guy! Question How can I find all Windows PowerShell cmdlets that begin with the verb "get" but are not contained in the
           Windows PowerShell module named “PowerShellCookbook”?

Hey, Scripting Guy! Answer Use the Get-Command cmdlet, and use the Where method to filter that the module name does not equal
           “PowerShellCookbook”:

(Get-Command -Verb get).where({$_.modulename -ne 'powershellcookbook'})

Viewing all 3333 articles
Browse latest View live


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