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

Use PowerShell Environmental Variables to Store Temporary Information

$
0
0

Summary: Use the Windows PowerShell environmental drive to store temporary information, and still use the Set-StrictMode cmdlet.

Microsoft Scripting Guy, Ed Wilson, is here. It is exactly 11 days until the 2012 Scripting Games commence. Here is how I found out that salient piece of information.

New-TimeSpan -Start (get-date) -End "april 2, 2012"

Note   Thanks to Windows PowerShell MVP, Richard Siddaway, for recently pointing out that typing a date in the fashion, 4/2/12 can lead to problems in international locations. (I knew that, but I tend to forget at times.)

The excitement of the 2012 Scripting Games is really growing. In fact, this year I am proud to announce that the Scripting Manager has caught the excitement from all my weekly status reports, and he has volunteered to be a judge for the games this year! Check out Dave Bishop’s biography on the Announcing the PowerShell Judges for the 2012 Scripting Games page.

Speaking of excitement…

Tomorrow, the long awaited Charlotte IT Pro Appreciation Day commences at 9:00 Eastern Time. So if you are in the Charlotte, North Carolina area, hopefully you will be able to attend this event. Luckily, you do not have to preregister for this event, so if your day looks slack tomorrow, come on out and join the nearly 1000 other people who are expected to turn out. The Scripting Wife will be helping with registration, so you will have a chance to meet her, and I will be making two presentations about Windows PowerShell. It will be a great occasion, and I hope to see you there.

The past several days I have talked about using the Set-StrictMode cmdlet to avoid certain types of Windows PowerShell errors. On Tuesday, I wrote Use Strict Mode for PowerShell to Help You Write Good Code, and yesterday I posted Avoid PowerShell Errors by Initializing Variables. Last night I received an email on scripter@microsoft.com that asked the following question.

What if I want my script to continue to increment?

In yesterday blog, I talked about initializing a variable to avoid continuously incrementing a variable each time the script runs. In the script that follows, each time the script runs, the value of the $a variable increases by five.

UninitializedVariable.ps1

1..5 | foreach{

 $a++}

$a

The output is shown in the image that follows.

Image of command output

Normally, the output from the previous script is an error, and the way to correct it is to initialize the value of the $a variable prior to incrementing it. In this way, the script produces the same output each time it runs. The best way to ensure that you initialize variables prior to use is to use the Set-StrictMode cmdlet as discussed yesterday. Here is the code that sets -Version 1 checking so that directly accessing a noninitialized variable causes an error, but using a noninitialized variable in a string does not generate an error.

InitializedVariable.ps1

Set-StrictMode -Version 1

$a = 0

1..5 | foreach{

 $a++}

$a

Using the environmental drive to persist information

The question that came into Scripter was how to use the Set-StrictMode cmdlet and yet be able to increment the value of the $a variable each time the script runs. The solution is to persist the final value of the $a variable, and to read it the next time the script runs. One way to do this is to write the value to the registry, but that would also presume some sort of clean up between Windows PowerShell sessions to avoid completely polluting the values. Another way to do this is to store the value in a temporary text file, but clean up once again becomes a problem (I hate leaving temporary files laying around on the file system).

A better approach is to write the value to an environmental variable. By using Windows PowerShell and the environmental drive, this is a piece of cake—and better yet, when the Windows PowerShell session ends, the environmental variable goes away. This is exactly what I need. The InitializeVariableFromEnv.ps1 script that follows illustrates one way to persist the value of the $a variable to permit incrementing it with each run of the script.

InitializeVariableFromEnv.ps1

Set-StrictMode -Version 1

if(test-path -path env:\a)

  { [int]$a = $env:a }

else

  { New-Item -Name a -Path env: -Value 0 | out-null

    [int]$a = $env:a }

1..5 | foreach{

 $a++}

$env:a = $a

$a

In the InitializeVariableFromEnv.ps1, script the first thing I do is use the Set-StrictMode cmdlet to set the strict mode to -Version 1. Next, I use the Test-Path cmdlet to see if an environmental variable named a exists. If it does exist, I read the value and populate the value of $a. One thing that is really important is to cast the value from env:\a to an integer, or else it is interpreted as a string and the ++ operator fails. This is shown here.

Set-StrictMode -Version 1

if(test-path -path env:\a)

  { [int]$a = $env:a }

If the env:\a variable does not exist, I use the New-Item cmdlet to create a new instance of it. I set the value to 0, and pipe the returned object to the Out-Null cmdlet to avoid cluttering the output with distracting information. I then set the value of $a to the value of $env:a. This code is shown here.

else

  { New-Item -Name a -Path env: -Value 0 | out-null

    [int]$a = $env:a }

The last things I do are increment the value of $a five times, and assign the present value of the $a variable to the $env:a variable. Lastly, I display the value of $a. This code is shown here.

1..5 | foreach{

 $a++}

$env:a = $a

$a

The code and the output associated with running the script three times is shown in the image that follows.

Image of command output

Well, that is about it. Join me tomorrow for 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 


See Why It Is Important for IT Pros to Learn PowerShell

$
0
0

Summary: The Scripting Wife sees why it is important for IT Pros to learn about Windows PowerShell.

Microsoft Scripting Guy, Ed Wilson, is here. Morning comes early, especially when it is still morning. Today is the Charlotte IT Pro Appreciation Day conference in downtown Charlotte, North Carolina. The Scripting Wife needs to be there early to help with registration, and so I will go along with her. Traversing Charlotte can take nearly two hours depending on traffic. We are getting a real early start to ensure that we are there when we need to be there.

It is oh dark thirty, and I am sitting on the lanai sipping a cup of English Breakfast tea and munching on a left over blueberry scone from yesterday’s bounty. I have my laptop with me, and I am checking the email sent to the scripter@microsoft.com alias because I will be out of the office all day today due to the conference. I don’t know if I have mentioned this before, but the Scripting Wife is sort of like a bear—she loves to hibernate, and it can be downright dangerous waking a sleeping bear. So I just sort of hope that she has set her alarm on her Windows 7 phone to awaken in time to get to the conference. In the meantime, I am enjoying a bit of early morning solitude.

“You really do not know how to make breakfast, do you?” the Scripting Wife’s voice cut like a hot knife through a stick of warm butter.

“Sometimes I wish you would announce yourself,” I complained as I wiped hot tea off the front of my shirt.

“I just did. You know I am here, don’t you?” she replied in a logical tone of voice. “I was hoping you would have made breakfast, instead of sneaking around and eating the last blueberry scone.”

“It did not have any ownership tags on it that I saw,” I replied rather defensively.

“So what are you up to?” she asked.

“Well, aside from getting ready to go put on a clean shirt, I was reviewing the Scripter email, and thinking about my presentation for today,” I said.

“What are you going to talk about?” she asked.

“Windows PowerShell,” I replied.

“Don’t be a smart alec,” she replied.

“I am going to talk about why it is important for people to learn about Windows PowerShell,” I said.

“OK. Why do you think it is important for people to learn it?” she asked.

“There are a number of reasons. For one thing, it is fun. For example, someone actually wrote a Windows PowerShell version of the old-fashioned Space Invaders game. Here, let me show you,” I said as I turned my laptop so the Scripting Wife could see the screen. I then launched psinvaders.ps1.

Image of game

“That is cool,” she remarked, “I also know that you have written lots of silly scripts that draw pictures like cats sitting on fences.”

“In addition to being fun,” I said, ignoring her comment about silly scripts, “Windows PowerShell is pretty easy to learn. All the cmdlets use a verb-noun naming convention. For example, if I want to get information about a process it is Get-Process.”

“I know that one,” said the Scripting Wife, “I used that a couple weeks ago when I asked you about easy commands I could teach my friends.”

“If I want to find information about services, I use the Get-Service cmdlet,” I continued.

“I know that one as well. We worked with that one back in February to find service accounts,” she said.

“If I want to shut down my computer, what do I use?” I asked.

“Shutdown-Computer?” she queried.

“You are close. It is Stop-Computer. Remember, we worked with that one last year,” I gently reminded.

“Yeah, I guess so. Now that you mention it, it does make sense.”

“One easy way to learn about the Windows PowerShell cmdlets is to use the Get-Verb command to list all the verbs available to use in Windows PowerShell. Here let me show you,” I said as I leaned over to type on my keyboard, “See, here is the list”.

Image of command output

“Nice,” the Scripting Wife replied.

“But the most important reason is that Windows PowerShell is the management solution moving forward. All of the new Microsoft products are building-in Windows PowerShell cmdlets. It is really important for any IT Pro to learn Windows PowerShell now,” I paused to catch my breath.

“You mean, Learn PowerShell Now Before It Is an Emergency,” quipped the Scripting Wife, as she parodied the name of one of my week long Live Meeting Series.

I smiled, and said, “Absolutely.”

“Why are you still sitting around the lanai? If you are not going to fix breakfast, you can at least take me out for breakfast. But first, you have got to change your shirt. Honestly, you cannot drink a cup of tea without making a mess. I am thinking about fitting you for a bib.”

And with that she left. I am not certain where she went—maybe to find a bib, but I hope not.

Join me tomorrow for more Windows PowerShell 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 

Learn How to Manually Create a CSV File in PowerShell

$
0
0

Summary: The Scripting Wife learns how to manually create a CSV file in this beginner Windows PowerShell blog.

Microsoft Scripting Guy, Ed Wilson, is here. Ah, it is the weekend. It seems that this week has been rather long, although I know that is a misconception because each week only has 168 hours in it. I guess it is kind of like one of the characters in One Flew Over the Cuckoo's Nest, a book I read in high school. They assumed that the staff sped up the clock when they were having fun, and slowed down the clock when they were doing things they disliked as a way of punishing them. Anyway, this morning I am in my office busily working on my new Microsoft Press book, Windows PowerShell 3.0 Step by Step.

“Hmmm…I like the new Where clause syntax in Windows PowerShell 3.0,” I said to myself.

“So what is a CSV?” said the Scripting Wife as she jolted me from my mental revelry.

“Is it a model of a car?” I facetiously queried.

“No. Not even close, Script Monkey,” she shot back, “Try again.”

“OK. It is a comma-separated value type of text file,” I said.

“Correct. Give the Script Monkey a peanut,” she said.

“So why do you want to know about CSV files?” I asked.

“Because silly, it is in the 2012 Scripting Games Study Guide, and the games start in exactly nie days,” she replied.

“OK. What do you want to know about CSV files?” I asked.

“Everything.”

“I see. Well, you could start by reading all the CSV blogs I have written on the Hey, Scripting Guy! Blog.”

“I could, but I want you to teach me. After all, you are the world famous Scripting Guy.”

Manually creating a CSV File

“What I am going to show you today is how to create CSV file manually. The first thing you need to do is to create a here string,” I said while turning my laptop screen so she could see.

“A hear string? What is this? Like a symphony or something?” she quipped.

“Try to stay with me. A here string allows you to create a string without worrying about any sort of formatting like quotation marks and commas, which are two things that CSV files really love, and that Windows PowerShell in general balks at.”

“OK. So how do I create this magical here string?” she asked with obvious signs of skepticism.

Use @” to begin and “@ to end a here string

“The first thing I do is use a variable to hold the resulting string. Then I begin the here string with the at plus quotation symbols (@”). Then I immediately press ENTER, and I add my column headings. A comma separates each heading, and then I again press ENTER. Now I add the value for each column and I use a comma to separate the values.”

“That is why it is called a comma-separated value file?” she asked.

“Exactly. When all of the rows of data are typed, press ENTER again, and I close the here string with the quotation mark plus at symbols (“@) and again press ENTER.”

“OK,” she said somewhat skeptically.

“Why don’t you give it a try,” I said as I turned the laptop over to her.

The Scripting Wife opened the Windows PowerShell console, and typed the following on the first line. In the following code, <enter> represents the ENTER or Return key (ASCII 13) (8 ).

$csv = @"<enter>

Next she added the column headings by typing the following.

"index","name"<enter>

After the columns were added, the Scripting Wife added the data. This is shown here.

1,"ed"<enter>

2,"teresa"<enter>

Finally, she closed the here string.

"@<enter>

<enter>

“Now you need to write your CSV data to a file,” I said. “When you are done, use the Import-CSV cmdlet to read it back.”

“Oh, I can use redirection to create the file,” she said.

The Scripting Wife quickly typed the following.

$csv >>c:\fso\mycsv.csv<enter>

Import-Csv C:\fso\mycsv.csv<enter>

“Very good. Now store the CSV information back into a new variable, and access the first element in the file,” I said.

“Huh? Do you mean for me to use square brackets and see the first row of information?”

“Yeah.”

“Then why don’t you just say that?” she chided.

The Scripting Wife typed the following.

$mycsv = Import-Csv C:\fso\mycsv.csv

$mycsv[0]

“Do you see that your first row of data contains two items—the index and the name?” I asked.

“Yes.”

“You can use dotted notation to access the specific column of information. These act just like properties. Why don’t you get the name from the second record?” I suggested.

The Scripting Wife typed the following.

$mycsv[1].name

“So how does all this look?” the Scripting Wife asked as she turned the monitor over so I could see.

As I looked at the screen, I beamed. “It is perfect.” The screen is shown in the image that follows.

Image of command output

“Cool,” she said as she jumped up and prepared to leave.

“By the way, how did you do on the new 2012 Scripting Games PowerShell Quiz?” I asked.

But by this time she was long gone. Perhaps she did not hear. Or maybe she did…

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 

The Scripting Wife Learns to Use PowerShell to Work with XML

$
0
0

Summary: In this blog, the Scripting Wife learns how to use Windows PowerShell to work with an XML file.

Microsoft Scripting Guy, Ed Wilson, is here. It is only eight days until the kickoff of the 2012 Scripting Games. Tomorrow the signup for the 2012 Scripting Games goes live. I have finished all the meetings, and everything is now in readiness state for the big event. I am sitting in the kitchen sipping a cup of English Breakfast tea, and looking over the chapter that I completed last night in my Windows PowerShell 3.0 Step by Step book. I close my eyes to think about one particular sentence when all of a sudden I feel a presence come into the room.

“If you are going to sleep, then you should get up from the table,” the Scripting Wife chided.

“I am not sleeping, I am deep in thought,” I replied.

“Then I am in deep trouble,” the Scripting Wife rejoined.

“What are you doing in here? The sun is still up,” I joked.

“Very funny. In fact, it is so funny I forgot to laugh,” she said. “Actually, since you are not doing anything, I need to you tell me about XML.”

“Say what?”

“XML. I need to know how to read an XML file,” she repeated.

“You are kidding.”

“Nope. I exported my book database, and it saved as an XML file. I need to know how to read it,” the Scripting Wife explained.

“OK. That makes sense. In Windows PowerShell, it is really easy. How do you read a plain text file?” I asked.

“I use the Get-Content cmdlet,” she said.

“It is the same thing, except that you use the letters XML inside square brackets. Open up Windows PowerShell on your computer, and then use Get-Content to read the XML file.”

The Scripting Wife stores her books.xml file in the FSO directory on her C:\ drive. Therefore, her command looks like this:

[xml]$books = Get-Content C:\fso\books.xml

“Now look at what is contained in the $books variable,” I suggested.

The Scripting Wife typed the $books variable on its own line in the Windows PowerShell console. The command and its associated output are shown in the image that follows.

Image of command output

“Now look at the XML property,” I suggested.

The Scripting Wife typed the following command.

$books.xml

“OK. Now look at the BookInfo property.”

She typed the command that appears here.

$books.bookinfo.

The command to examine the XML property and the command to look at the BookInfo property are shown in the image that follows, along with the associated output.

Image of command output

“What is that booklist?” the Scripting Wife asked.

“I don’t know. Why don’t you access it and see.”

The Scripting Wife used the Up arrow to retrieve the previous command, and added BookList to the end of the command and pressed ENTER. Here is her command:

$books.bookinfo.booklist

“Well, it looks like a bunch of books,” she replied as she turned her monitor to me so I could see. The image that follows shows her Windows PowerShell console.

Image of command output

“Why don’t you keep going…But this time, pipe the output to More just in case you get all of your books rolling by,” I suggested.

The Scripting Wife once again used the Up arrow to retrieve her previous command, added Book to the end of the command, and piped the output to More. The command is shown here.

$books.bookinfo.booklist.book | more

Sure enough, after a few seconds, the book information began to scroll. The first little bit is shown here.

Image of command output

“Well that looks interesting, but how can I find more information about a book?” she asked.

“Why don’t you index into the collection? Choose the first book,” I suggested.

The Scripting Wife thought for a few seconds, and then she used the Up arrow to retrieve her previous command and then added the index operator. Her command is shown here.

$books.bookinfo.booklist.book[0]

The output from the previous command is shown here.

Image of command output

“You can use the same techniques to find information about the subjects of the book, and to find information about the title, plot, and other information.”

The Scripting Wife typed the commands that follow. As she examined the output from each command she continued to burrow deeper and deeper into the data structure of the first book.

$books.bookinfo.booklist.book[0].subjects

$books.bookinfo.booklist.book[0].subjects.subject

$books.bookinfo.booklist.book[0].mainsection

$books.bookinfo.booklist.book[0].mainsection.authors

$books.bookinfo.booklist.book[0].mainsection.authors.author

$books.bookinfo.booklist.book[0].mainsection.authors.author.person

Finally, she sat back and examined her handiwork. The output from these commands are shown in the image that follows.

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

 

Use PowerShell to Parse an XML File and Sort the Data

$
0
0

Summary: In this blog, the Scripting Wife learns how to use Windows PowerShell to parse her books XML files and to find authors and sort titles.

Microsoft Scripting Guy, Ed Wilson, is here. Today the registration opens for the 2012 Scripting Games. You can go to the 2012 Scripting Games site on PoshCode, click Log On, choose your authentication mechanism, and fill out your user name and email address. Make sure your user name is the name you want to appear on the leaderboard, and on your 2012 Scripting Games certificate. Also, make sure your email address is correct because it is used to notify you about prizes.

Yesterday, the Scripting Wife asked me to help her with exploring an XML file. Last night, she told me that she wants me to help her look at the XML file she got by exporting her book database so that she can find titles of books and things like that. I think I will call her, and see if she is ready…

“Scripting Wife?” I call in my nicest voice.

All of a sudden I look up, and she is here.

“You don’t have to yell. You could simply have called me on my Windows 7 phone,” she replied.

“I didn’t yell—and besides, I was not sure you had your Windows 7 phone with you,” I apologized.

“I always have it with me,” she said rather curtly. “So are you going to show me how to find titles in my XML file?”

“Yep. Why don’t you sit over here next to the computer, and first read your XML file into a variable. Remember to use the [XML] symbol to make sure that you get an XML document,” I said.

The Scripting Wife thought for a minute, and then typed the following command.

[xml]$books = Get-Content C:\fso\books.xml

“Now, remember that all your book data was in the book node. So why don’t you retrieve that, pipe it to the Foreach-Object cmdlet, and then retrieve the Title property,” I said.

The Scripting Wife thought for a few seconds and began to type. Within a minute or so, she had composed the command that is shown here. (The percentage sign (%) is an alias for the Foreach-Object cmdlet.)

$books.bookinfo.booklist.book | % {$_.mainsection.title}

The two commands and the output associated with the commands are shown in the image that follows.

Image of command output

“That is pretty cool, but I want to be able to find out how many books I have based on subject,” she asked.

“Well, that is pretty easy. Take your book element, pipe it to the Foreach-Object cmdlet, then pipe that to the Sort-Object cmdlet, and choose the DisplayName property. Then group it by DisplayName. Use the NoElement switched parameter to keep from displaying a bunch of extra information,” I said.

She thought for a second, and then used the Up arrow to retrieve her previous command. She then modified it until the following command appeared.

$books.bookinfo.booklist.book | % {$_.subjects.subject} | sort displayname | group displayname -NoElement

She turned the monitor to me, and the output that is shown in the image that follows was the result.

Image of command output

“That was pretty complicated. Can’t we do something easier? For instance, I want to find all the Perry Mason novels,” she requested.

“That one really is easy. Retrieve your command that lists all the titles. Because the titles are all strings, pipe that to the Where-Object and use the Match operator to look for Mason,” I said.

This time the Scripting Wife did not hesitate. She retrieved her next to last command by pressing the Up arrow twice. Then she added a pipe character, used the question mark (?) as an alias for the Where-Object. She added the Match operator and looked for the word Mason. Her completed command is shown here.

$books.bookinfo.booklist.book | % {$_.mainsection.title} | ? { $_ -match 'mason'}

“This is more like it. Here take a look,” she said as she turned the monitor towards me.

Image of command output

“That is all I really wanted to see right now. I think I am going to head to the mall with a couple of my friends. You have been keeping me too busy around here, and I need a break,” she said as she jumped up and headed towards the door.

“Don’t forget…registration for the 2012 Scripting Games is open,” I said.

“I will register tomorrow,” she said.

And she was gone.

Join us tomorrow when I imagine the Scripting Wife will register for the 2012 Scripting Games.

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 

Support Our 2012 Sponsor: Devfarm Software

$
0
0

Devfarm Software’s mission is to build world-class products to simplify and automate the daily activities of IT administrators.  Devfarm Software’s flagship product, PowerWF Studio delivers on this dream by leveraging Windows Workflow Foundation and Windows PowerShell to innovate in the areas of administration, virtualization, service desk, and monitoring. 

PowerWF is a unique authoring tool that turns Windows PowerShell commands into toolbox items that can easily be used to create powerful workflows. PowerWF can convert existing Windows PowerShell scripts into workflows which can then be extended by using Windows PowerShell and non-Windows PowerShell activities. PowerWF includes a workflow debugger, which enables easier creation and testing of workflows that leverage Windows PowerShell. By using a workflow and Windows PowerShell together, administrators can accomplish simple tasks (such as creating standalone executable programs) to more advanced tasks (such as creating and deploying rich management packs for System Center Service Manager and System Center Operations Manager. These tasks are possible by using Windows PowerShell or by leveraging the drag-and-drop workflow design surface. 

For more information about PowerWF and to download a trial version, visit the PowerWF - Visual PowerShell website. 

PowerSE is a best-in-class, free Windows PowerShell script editor that can be downloaded by itself or as part of the PowerWF package where it is included automatically. PowerSE has all the features expected in high-end script editors like color syntax highlighting, tab completion, and deep Intellisense of Windows PowerShell, WMI, and .NET. But what truly makes PowerSE special, is how it helps you learn and use Windows PowerShell faster. Smart command-line Help is there when you need it. A detailed command history shows execution time and success or failure, and there is a detailed variable inspection window. A seamless blending of these features with a syntax editor and a Windows PowerShell command console allow you to make the most of your time with Windows PowerShell.

To download the standalone, free version of PowerSE, see the Download PowerSE Today website.

PowerVI is a VMware automation tool that extends the vSphere Client, providing access to dozens of prebuilt automation scripts that simplify everyday VMware administration tasks. The PowerVI menu is dynamically generated, based on the scripts that you have installed or created. This enables Windows PowerShell scripts to be easily executed directly from the vSphere Client through context sensitive actions. This provides a customizable UI extension for the vSphere Client.

For additional information about PowerVI, please visit the PowerVI – PowerScripter, vSphere Automation Fueled by PowerShell website.

 2012 Scripting Games badge

Back to All Sponsors page

How to Register for the 2012 PowerShell Scripting Games

$
0
0

Summary: Learn how (and why) to register for the 2012 Windows PowerShell Scripting Games.

Microsoft Scripting Guy, Ed Wilson, is here. Well, the 2012 Scripting Games start in six days. I found this out by using the following code:

New-TimeSpan -Start "March 27,2012" -End "April 2, 2012"

The output from the previous command returns a System.TimeSpan object, as shown in the image that follows.

Image of command output

Why you should sign up for the 2012 Scripting Games

At the Charlotte IT Pro Appreciation Day, I was asked again and again why someone should sign up for the 2012 Scripting Games. There are actually several reasons—all predicated on learning Windows PowerShell. (You should begin by reading Why It Is Important for IT Pros to Learn PowerShell). After you agree that you should learn Windows PowerShell, the next question is, “What is the best way to learn Windows PowerShell?” This is where the 2012 Scripting Games comes into play.

Back when I was at the University, I had a good friend who was from Cuba. Every morning, we would get up early and run before our morning classes. All semester, I kept intending to learn Spanish. We would talk about various vocabulary words as we ran, but I really did not learn much Spanish that semester. It was not until the following semester when I signed up for Spanish 101, that I really began to learn Spanish. This is because I had a vocabulary quiz each day, and therefore, I put more effort into learning.

In addition to the motivation to learn, the 2012 Scripting Games also provide recognition and feedback on your progress learning Windows PowerShell. There is also the chance to win great prizes, which include a free pass to 2012 TechEd and hundreds of other prizes.

Take a quiz every day for two weeks

With the 2012 Scripting Games, you will in effect, have a quiz every day for two weeks. The quiz takes the form of each Scripting Games event. This is your time to commit to learning Windows PowerShell. The ten events will give you added motivation to learn. After you have spent time creating solutions to the ten events, you will naturally want to see the ten expert solutions to the events so that you can compare your work with that of the experts. You might also want to see what your peers come up with when their solutions are revealed seven days after the event first appears.

Take a quiz even if you don’t sign up for the games

Even if you do not sign up for the 2012 Scripting Games, you might want to take a Windows PowerShell quiz. I have two series of training videos and two Windows PowerShell quizzes. You can access the quizzes and the two video series from the Scripting with Windows PowerShell page.  In addition, you should work your way through the 2012 Scripting Games Study Guide, and the study guides for the previous year’s Scripting Games. You can find the links to the study guides from 2012 Windows PowerShell Scripting Games: All Links on One page.

Here is how you sign up for the 2012 Scripting Games

Now that you know why you need to sign up for the 2012 Scripting Games, I am going to ask the Scripting Wife to come help us get signed up for the games. (I would do it, but I am a judge, so it would not be fair.)

I pick up my Windows 7 phone and call the Scripting Wife. The nice thing about our phone provider is that phone-to-phone calls are free on the same service plan. So we use our Windows 7 phones sort of like an intercom or like a walkie-talkie at home. It prevents yelling—which just seems a bit rude. We also use our phones to send SMS messages to each other when we are dining out, but that is another story.

The Scripting Wife appears at the door to my office, and I greet her with an affectionate and heart felt greeting.

“I need you to come over here, so we can get you registered for the 2012 Scripting Games,” I exclaim.

“What, no ‘Hi, how are you doing?’ No ‘I have a special surprise for you today’? No nothing…just come over and get signed in,” she complained. ”How wude!”

“Sorry. Hey, why don’t you come over, I have a special surprise for you,” I said smiling.

“Too late, I already know what it is. The sign-up page for the 2012 Scripting Games is live,” she said.

“OK. You need to go to http://2012sg.poshcode.org/. When you get there, you need to click on the Log On button in the upper-right corner,” I said.

The Scripting wife typed http://2012sg.poshcode.org/ into Internet Explorer 9, and watched as the page navigated to the new PoshCode site for the 2012 Scripting Games. The 2012 Scripting Games PoshCode page appeared on her screen as follows, and she turned the monitor so I could see it.

Image of website

The Scripting Wife pressed Log On and was presented with the PoshCode Multi-Protocol Authentication page that is shown here.

Image of webpage

She then clicked the Profile button in the upper-right portion of the screen, just above the Search PoshCode box. This button is shown here.

Image of webpage

When the Scripting Wife pressed the Profile button, the Edit Account Information page appeared. She changed her display name to ScriptingWife, and she added her Hotmail email address and the web address of her blog. She then clicked save. The Edit Account Information page is shown here.

Image of webpage

That’s it. She then hit the Log Off button and closed Internet Explorer. The Scripting Wife is now registered for the 2012 Scripting Games. Scripting Games prep week will continue tomorrow.

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

Use PowerShell to See Time Zone Information on Remote Computers

$
0
0

Summary: Learn how to use a Windows PowerShell cmdlet to determine if the time zone on remote servers has been changed from the default.

Microsoft Scripting Guy, Ed Wilson, is here. One of the cool things about the Scripting Wife is that from time to time I can ask her if she would like to help with some of the system admin duties around the house. Of course, on these occasions she is more than delighted to show off her scripting skills. Take for example, a situation I ran across today. I was working with one of my servers, comparing different event log entries among machines, when I noticed what appeared to be a time skew. I checked, and noticed that I had forgotten to set the time zone when I built the computer. This made me curious…did I forget to do this on other servers on the network?

Detecting time zone settings on servers

There are several ways to approach this problem, including using Windows Management Instrumentation. But I decided to use the Get-WinEvent cmdlet and check the DateTimeControlPanel operational trace log. This is because an event gets written to this trace log when the time zone is set. If the time zone is never set, there is no entry in this trace log.

Note   This log is automatically enabled on server operating systems beginning with Windows Server 2008 R2. The trace log exists, but it is not enabled on Windows Server 2008. It is also available, but not enabled on client operating systems beginning with Windows Vista.

The DateTimeControlPanel trace log on one of my servers running Windows Server 2008 R2 is shown in the image that follows.

Image of menu

Use PowerShell to query the DateTimeControlPanel log

I decide to ask the Scripting Wife to join me, so she can help check all the servers on the network to determine the time zone settings. I grab my Windows 7 phone, and send the following SMS message.

“Would you like to come to my office and help me check the time zone settings on a bunch of servers?”

It seems like I just completed hitting send, and she was standing in the doorway to my office.

“You rang?” she asked, sounding a bit like Lurch.

“I just found out that I omitted setting the time zone on some of the new servers I built last weekend,” I started to explain.

“And that affects me how?” she asked.

“Well, it really does not. But I thought it would be a great time to give you some real-world practice reading trace logs,” I explained. “I can tell you for a fact, it will be a useful skill to have for the 2012 Scripting Games.”

“Well then, why didn’t you just say so?” she exclaimed.

“I just did.”

She just waved an impatient hand towards me that I think indicated I was to clear my chair to provide her with premium seating in front of the array of monitors that occupy my desk.

“So get on with it. I don’t have all day,” she said, “I have important things to do this afternoon.”

“OK. We need to run a command on a bunch of remote servers. To do this, what cmdlet will we use?”

“The Invoke-Command cmdlet will do that. Is that what you wanted to know?”

“Exactly. Now, to read from a trace log, what cmdlet do you use?”

“You know. You sound a lot like your new Windows PowerShell quiz.”

“Of course I do. I wrote it. Just answer the question and quit stalling.”

“Well, I guess I could use the Get-WinEvent cmdlet. By the way, why is it called Get-WinEvent instead of Get-EventLog?”

“Because we already had a cmdlet named Get-EventLog. That’s what happens when all the good names are taken.”

“Oh,” she said looking like she was not certain that I was being serious, “Then why don’t we just use the Get-EventLog cmdlet to query all of the trace logs?”

“Because Get-EventLog only works on classic event logs, not the ETW trace logs.”

“Oh. OK. Then why don’t we just use the Get-WinEvent cmdlet to do everything? I know it has a Credential parameter, and it also has a ComputerName parameter.”

“Because the Get-WinEvent requires that a port be open in the firewall for the event log service. In addition, I cannot supply an array to the ComputerName parameter of that cmdlet.”

“Well, then let’s get this show on the road. Show me what I need to know,” she said.

“First of all, you need to use the Invoke-Command cmdlet to run the command on the remote computers. Use the cn.txt file that lists all of the servers. Next, you will need to use the Get-WinEvent cmdlet inside the script block to do the actual query. I have the credentials stored in the $cred variable. While you are at it, create an easy-to-read table that lists the computer name, the time of the message, and the actual message,” I said.

The Scripting Wife thought for a few seconds, and then typed the following command. (The command is a single-line command that wraps, but it does not include any line continuation characters.)

invoke-command -cn (gc c:\fso\cn.txt) -cred $cred {Get-WinEvent -LogName

 Microsoft-Windows-DateTimeControlPanel/Operational -Force} | select pscomputername, timecreated, message | ft pscomputername, timecreated, message -AutoSize -Wrap

The command runs for nearly a minute. When it completes, the output appears as in the image that follows.

Image of command output

“Connect to the remote computer by using RDP and make the change,” I said.

The time settings dialog box is shown in the following image.

Image of dialog box

“But why do I have to use RDP to connect to the server just to set the time zone? I don’t want to be a button monkey, I am a Scripting Wife,” she said emphatically.

“OK, Dudette. Chill please,” I said. “You are right. It is entirely possible to get and set the time zone information by using a simple command-line utility tool. Keep in mind that this utility tool works on Windows7 and Windows Server 2008 R2; therefore, it will work on the machine running Windows Server “8” Beta that you discovered.”

“So don’t keep me in suspense…Give,” she said.

“The command is tzutil. To get a time zone, use the /g parameter. To set the time zone use the /s parameter and specify the time zone. I like to use the /g parameter after I have used /s to set a new time zone.”

“So does the tzutil command have a /c parameter for ComputerName?” she asked.

“Nope. But this is where the Invoke-Command cmdlet comes in handy,” I said, “Go ahead and set the new time zone on the server running Windows Server “8” Beta to Eastern Standard Time.”

The Scripting Wife thought for about a minute, and then she typed the following command.

invoke-command -cn w8server6 -cred $cred {tzutil /s "Eastern Standard Time"}

“Very good,” I said, “Now use the tzutil command to verify that the change took place.”

The Scripting Wife used the Up arrow to retrieve her previous command, and she edited the line until it looked like the following.

invoke-command -cn w8server6 -cred $cred {tzutil /g}

“Perfect.”

“I have just one question for you,” she said.

“If I could have used the tzutil command, why did you have me parsing the DateTimeControlPanel log?” she asked.

“Because I wanted to show you that you could. Also it actually made it easier because the only time an entry existed was if the time zone actually had been changed. Remember, there were no entries in the log for Windows Server “8” Beta because it was still at the default Pacific Standard Time setting,” I explained.

“Yes, I guess that makes sense,” she said somewhat hesitantly.

And with that, she got up and departed.

That is about all there is to using the Get-WinEvent cmdlet to connect to a group of remote computers and determine if the time zone is configured on the machines. Scripting Games 2012 Prep Week will continue tomorrow.

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


Use PowerShell to Troubleshoot and Repair WMI Errors

$
0
0

Summary: Learn how to use Windows PowerShell to troubleshoot and repair WMI errors.

Microsoft Scripting Guy, Ed Wilson, is here. Tomorrow is the New York City TechStravaganza. The Scripting Wife and I will be there, and we are looking forward to hanging out with Microsoft PowerShell MVPs such as Tome, Brandon, and Aleksandar. Anyway, it was late when we got to the hotel, and I was looking forward to reading a story collection by Raymond Chandler and calling it a day. I had just started on the third story in the collection, when above the constant hum of Times Square, I heard the Scripting Wife.

“Why do I always get these errors,” she exclaimed with obvious annoyance.

“Probably because you are doing something wrong,” I said not really helping the situation.

“No. In the event log. Here take a look,” she said turning her laptop to me.

The error to which she referred is shown here.

Image of error message

“How do you know you are always getting this error,” I asked.

“Because I always see it every time I open the Application log on my computer,” she replied.

“Well, let’s see how many times you really are getting this error,” I suggested, “Open the Windows PowerShell console, and let’s use the Get-WinEvent cmdlet to retrieve every Event 10 from Windows Management Instrumentation.”

“OK. But you are going to have to help me a bit,” she said.

“But of course. We will use a filter hash table so that we only retrieve the events from Windows Management Instrumentation that are Event 10 in the Application log. The first thing is to type the Get-WinEvent cmdlet, and call the FilterHashTable parameter. But do not press ENTER because we will build the command.”

The Scripting Wife thought for a bit, and then typed the following (she used tab expansion to complete the FilterHashTable parameter name).

Get-WinEvent -FilterHashtable

“Now we need to create the hash table for the filter. Remember that a hash table begins with the ‘at’ sign (@). Then it is the key equals the value. Each pair gets a semicolon separator,” I said.

“OK,” she said as she typed the “at” sign, and opened a pair of curly braces, “Now what?”

“The first pair is LogName equals Application. Put the word ‘application’ in quotation marks,” I said.

The following is what the Scripting wife typed.

@{logname='application'

“Now the next pair is ID equals 10. There is no need for quotation marks around the number ten. Remember, that each key value pair receives the semicolon separator.”

The Scripting Wife was all business. The she typed the following.

;id=10;

“The good thing is that the ProviderName will accept a wild card. So all you need to do is use the asterisk with the letters wmi. Make sure you also put them in quotation marks and close the curly bracket,” I said.
Here is what she typed.

providername='*wmi*'}

“Great. You are almost done. Pipe the whole thing to the Measure-Object cmdlet. You can use the alias measure for that cmdlet,” I instructed.

The following is the Scripting Wife’s completed command.

Get-WinEvent -FilterHashtable @{logname='application';id=10;providername='*wmi*'}  | measure

“Cool, it works,” the Scripting Wife exclaimed, “Here take a look.”

As she turned her laptop monitor so I could see the following output in her Windows PowerShell console.

Image of command output

“How would I know how to do this if you were not around?” she asked.

“You could use the Get-EventLog cmdlet to do this, but you would need to pipe the results to the Where-Object cmdlet to help with the filtering. This command is more efficient. Besides, I wrote a great Hey, Scripting Guy! blog last year about using the FilterHashTable parameter. It is titled How to Improve the Performance of a PowerShell Event Log Query,” I said.

“So what does all this mean anyway?” she asked.

“What does what mean?” I asked.

“What is Event 10 from Windows Management Instrumentation, and why is it littering my Application log with meaningless events?” she asked.

“Actually it is not meaningless. It means that some permanent event does not have permission to run. That is what the error code 0x80041003 means. Why it does not have permission is another issue. Let me check with Bing to find out,” I said.

Within less than a minute, I had retrieved a support article describing the situation. Interestingly enough, this issue also has a Microsoft Fix It solution attached to it. “Cool.” I thought. Then I thought this would be a great opportunity to talk to the Scripting Wife about permanent event consumers.

“Do you remember when Trevor wrote Use a PowerShell Module to Work with WMI Permanent Events?” I asked.

“Sure. I thought it was great,” she replied.

“Well, before that blog, I talked about working with permanent events and I discussed the technology that was behind them in Use PowerShell to Monitor and Respond to Events on Your Server,” I said.

“Uh. Sure, if you say so. I don’t remember that far back,” I said.

I started to say something like she remembered Trevor’s module, but then I decided to keep my mouth shut for a change. Then I changed my mind.

“Well, this is your lucky day. Because we are going to do a refresher course,” I said.

“Oh, come on. It is late, and tomorrow is the TechStravaganza,” she whined.

The first thing I did was create a simple script that I called Get-BVTFilterandConsumer.ps1. This script is shown here. (Note: The second line uses the back tick character for line continuation. GWMI is an alias for the Get-WmiObject cmdlet. Remember, this is a quick script, and it is late at night.)

Get-BVTFilterandConsumer.ps1

gwmi __EventFilter -Namespace root\subscription -Filter "name = 'bvtfilter'"

gwmi __FilterToConsumerBinding -Namespace root\subscription `

-filter "filter = '__EventFilter.Name=""bvtFilter""'"

“Now I want you to run the script. It will retrieve instances of the __EventFilter Windows Management Instrumentation class that are named bvtFilter. It will also retrieve instances of the __FilterToConsumerBinding Windows Management Instrumentation class—but only instances that are associated with the filter named bvtFilter. It sounds complicated, but really it is not,” I said.

“If you say so. But sometimes I wonder if your idea of complicated and my idea of complicated are the same thing,” she said as she ran the script. The output from the script is shown in the image that follows.

Image of command output

“Now what we need to do is to delete both the bvtFilter and the filter to consumer binding. This part is really easy because all we need to do is to pipe the objects from the previous script to Remove-WmiObject,” I said.

“That is the first thing you have said that makes sense,” she said, “Shouldn’t we back up the computer first?”

“We do not need to back up the entire computer, but it does not hurt to back up system state. To do this, use the CheckPoint-Computer cmdlet,” I said.

The Scripting Wife copied the code from the Get-BVTFilterandConsumer.ps1 script, and at the end of each line she added a pipe character, and sent the objects to the Remove-WMIObject cmdlet. Then she backed up and went to the top of the script and added the Checkpoint-Computer command. The resulting script, which she named BackupComputerAndRemoveBVTFilter.ps1, is shown here.

BackupComputerAndRemoveBVTFilter.ps1

Checkpoint-Computer -Description "prior to fixing event 10 from wmi" `

 -RestorePointType MODIFY_SETTINGS

gwmi __EventFilter -Namespace root\subscription -Filter "name = 'bvtfilter'" |

Remove-WmiObject

gwmi __FilterToConsumerBinding -Namespace root\subscription `

-filter "filter = '__EventFilter.Name=""bvtFilter""'" |

Remove-WmiObject

 When the Scripting Wife pressed the green triangle to run the script, the dialog box shown here appeared.

Image of dialog box

Other than the dialog box, there was no output from the script.

“So how do I know that it worked?” she asked.

“For one thing, you can run my Get-BVTFilterandConsumer.ps1 script. But with no instances, it will not display any output either. Another thing you can do is to open WbemTest, change your namespace to root\subscription and open the __FilterToConsumerBinding Windows Management Instrumentation class,” I said.

The Scripting Wife typed wbemtest into the Windows PowerShell console, and when the Windows Management Instrumentation Tester opened, she set the namespace to root\subscription and opened the __FilterToConsumerBinding Windows Management Instrumentation class. She then pressed the Instances button and the following dialog box appeared.

Image of dialog box

“You might also want to look for instances of the __EventFilter Windows Management Instrumentation class,” I suggested.

The Scripting Wife closed the previous dialog box, and opened the __EventFilter class. Next she looked for instances. The results are shown here.

Image of dialog box

“OK. That’s enough. You are making my head hurt, and I need to catch up with people on Facebook,” the Scripting Wife said.

And with that, I was effectively dismissed. 2012 Scripting Games Prep Week will continue tomorrow when we will have a guest blog post from Boe Prox.

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 

Support Our 2012 Sponsor: BeyondTrust

$
0
0

BeyondTrust is excited to be a sponsor for this year’s Windows PowerShell Scripting Games. BeyondTrust is the global leader in securing the perimeter to mitigate internal threat and the misuse of privileges. BeyondTrust offers consistent policy-driven, role-based access control, monitoring, logging, and reporting to protect internal assets from the inside out. The company’s products empower IT governance to strengthen security, improve productivity, drive compliance, and reduce expense across physical, virtual, public, private, and hybrid cloud environments.

Recently, BeyondTrust introduced PowerBroker Servers Windows Edition, the industry’s first privileged identity management solution for Windows-based servers. The product aligns nicely with the Windows PowerShell Scripting Games because the solution is built on top of, and can actively monitor, audit, and control remote Windows PowerShell activity. BeyondTrust is actively looking for folks to beta test an upcoming version of our software that will enable improved visibility and control over rapidly emerging server-based technologies that leverage Windows PowerShell. Interested candidates should fill out our quick qualification survey.

 2012 Scripting Games badge

Back to All Sponsors page

Tips for Preparing for the 2012 PowerShell Scripting Games

$
0
0

Summary: Guest commentator, Boe Prox, talks about practical tips for preparing for the 2012 Windows PowerShell Scripting Games.

Microsoft Scripting Guy, Ed Wilson, is here. Guest blogger, Boe Prox, is with us today. He is going to talk to us about preparing for the 2012 Scripting Games. First, a little bit about Boe…

Photo of Boe Prox

Boe Prox is currently a senior systems administrator with BAE Systems. He has been in the IT industry since 2003, and he has been working with Windows PowerShell since 2009. Boe looks to script whatever he can, whenever he can. He is also a moderator on the Hey, Scripting Guy! Forum. Check out his current projects published on CodePlex: PoshWSUS and PoshPAIG.
Boe’s blog: Learn PowerShell | Achieve More

Take it away Boe…

With the Scripting Games coming up on April 2, you might be asking yourself, “What do I need to do to be prepared for these games?” You are in luck because I am going to show some things that will help you in your quest for scripting glory!

These tips are in no particular order of importance, and they cover a wide variety of items that should be used to increase the readability of your code and to ease any issues that the people who are using your scripts may run into. So without further ado, let’s get started!

Variables that make sense

When you are deciding what you want to call the variables that are used in your code, keep in mind that others will be reading your code, whether it is in the Scripting Games or at your place of work. Or you might have to debug or add something to your code several months later, so using something like this for your code will only make the effort to read the code more difficult.

$strServers = 'server1','server2'

$d = Get-Date

ForEach ($C in $strServers) {

  $objp = Get-WmiObject -computer $c Win32_Process

}

There are a couple of things here that can stand to be changed. First off, the $strservers that is using Hungarian notation is not needed. Although it is often used in VBScript script, it isn’t needed in Windows PowerShell script. Using something that lets you know what the variable is holding—in this case, servers—is suitable, rather than knowing the type of the variable.

Although, I would rather use ComputerName because that is a common parameter in Windows PowerShell cmdlets. $d, $objp, and $c are the remaining the variables that fail to make it easy to know what is being used for each variable. Given, this is a small snippet of code, but imagine if you are working with 100+ lines of code. It would be more difficult to back track and find out what each variable is. Something like this would be much easier to read and understand.

$Computername = 'server1','server2'

$date = Get-Date

ForEach ($computer in $Computername) {

  $processes = Get-WmiObject -computer $computer Win32_Process

}

Error handling

If you are writing functions or scripts (or whatever), you need to be using some sort of error handling in your code. This will prevent unwanted errors from popping up and preventing your code from working. Now, I don’t mean to add $ErrorActionPreference = ‘SilentlyContinue’ at the top of your code and let it fly. If you are using that to solve your error handling, you are only fooling yourself. In other words, remove it immediately! It’s OK, I’ll wait.

What you should be doing is investing in using Try/Catch in your code to handle any potential errors that might pop up. All cmdlets have the ErrorAction parameter, and you can choose to use Stop. Or if you really don’t want to catch any errors (or even know about errors), you can use SilentlyContinue. The benefit of using this parameter is that it will only affect that command, not the all of the commands in the code. The following example of using this method will catch an error if something goes wrong.

ForEach ($Computer in $Computername) {

  If (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {

    Try {

      Get-WmiObject -Computer $Computer -Class Win32_Process -ErrorAction Stop

    } Catch {

      Write-Warning ("{0}: {1}" -f $Computer,$_.Exception.Message)

    }

  } Else {

    Write-Warning ("{0}: Unavailable" -f $Computer)

  }

}

A couple of other types of error handling use specific cmdlets to test for. Test-Connection checks if a system is online before making a connection for a query or some other operation. Test-Path checks to see if a folder or file exists.

Also, checking for Administrator rights is a useful thing to do within your code, especially when working with remote systems or accessing parts of a system that are otherwise off limits to a regular user account. It also helps if you have UAC enabled and are not running the script “as an Administrator.” I wrote a guest blog last year that talked about this: Check for Admin Credentials in a PowerShell Script.

Code formatting

Making your code readable can be just as important as making your code work properly to perform the action that you want it to do. Having code that is not readable makes it difficult to debug when something goes wrong. In addition, others trying to read the code may end up spending more time putting it into a proper format than actually debugging it or modifying it for their own environment. Things to consider when writing your code are:

  • Use spacing between areas of code to separate blocks of code.
  • Use natural line breaks: “|”,”{“.
  • Indent your code in areas where groups of code are being used logically, such as after an opening bracket “{“ or after a pipeline character is used. This ensures that all the lines of code within the construct are easy to identify and work with.
  • Use splatting for parameters where it threatens to force the use of a back tick (“`”) to enable a line break to continue the code.

Following is an example of poorly formatted code:

Image of code

There is a lot wrong with this code, ranging from no spacing, to indenting blocks of code where it is incased in a {} construct, to cmdlets using enough parameters to warrant a line break to keep everything from going off of the screen. Also, there are areas in the code that really aren’t needed, such as saving the result of the Test-Connection cmdlet and then comparing the return when it is a Boolean value in the If statement.

This is what it should look like:

Image of code

What you have now is something that is not only easier to read, but also takes advantage of other techniques, such as splatting the parameters for Get-WmiObject and taking advantage of the Boolean return value for using the Quiet parameter in Test-Connection for the If statement. Instead of using something like @{L='Computer';E={$_.__Server}},@{L='TimeGenerated';E={Get-Date}}} to add a couple extra properties to the output that is difficult to read, I used a ForEach loop and created my own object to make it easier to read. This really starts to show its usefulness when you are trying to add multiple properties to the output that are not available any other way.

There are more lines of code being used here. But trust me, it is worth it to have more readable code than taking shortcuts by cramming it all together.

Comment-based Help

Something that I saw last year (especially in the first few events), and I sometimes still see, are people writing their own Help in their code. Although it is great to see that some sort of Help is being added into their code so other people know what is going on with it, there is no reason to be doing this. The Windows PowerShell team has put together an amazing thing called comment-based Help that does practically all of the work for you. It has some great features such as displaying examples, viewing the full Help of the command, and looking at the details of a particular parameter. It is so simple that you can practically do it in your sleep! See this example:

Image of code

Everything within “<#” and “ #>” that uses the appropriate keywords will be read by Windows PowerShell and used to format the Help correctly so it shows something similar to the following:

Get-Help Get-StoppedService

 Image of command output

Everything that can help a person figure out what to do with this code is here. Want to know the specifics about the ComputerName property? Simple! Just do this:

Get-Help Get-StoppedService –Parameter Computername

Image of command output

How cool is that? This is much better than only getting one option when writing your own Help—which is typically to display everything at once. Need an example? Just do this:

Get-Help Get-StoppedService -Example

Image of command output

Remember, comment-based Help is your friend, and it should be used instead of writing your own Help. For more information about comment-based Help, run the following command:

Get-Help about_Comment_Based_Help

Other things to consider

I don’t have the time to dive into detail about these other items, but they are by no means any less important to think about and use while writing your code. It is just that I only have a limited amount of time and space to pick and choose which items to talk about.

  • Use output objects instead of text, and make it pipeline friendly.
  • Do not use aliases for anything (this includes cmdlets and parameters).
  • Use properly named functions (Verb-Singular noun).
  • Use Get-Verb to see approved verbs.
  • Keep inline comments to a minimum (consider using Write-Verbose instead).
  • Use [cmdletbinding()] and Param() in advanced functions; This allows the use of common parameters such as Verbose, Debug, WhatIf, and ErrorAction.
  • Consider using Write-Progress for long running tasks where you are looping through a collection; this allows the user to know where the script is and does not assume it has locked up.

Final thoughts

Keep in mind that during the Scripting Games you may not always get the score that you were hoping for. But don’t let that get you down! Keep writing code and submitting your scripts, learn from what the judges say, and look at the scripts your fellow scripters have submitted. You will improve on your current skills and continue to put together great scripts!

To quote myself from last year on twitter during the 2011 Scripting Games: “Remember that as long as you did your best on your script and are happy with what you did, then grading should be secondary.”

Good luck to all of the scripters this year!

~Boe

Thank you Boe. This is a great summary of things to keep in mind for the 2012 Scripting Games. Join us tomorrow for more Scripting Games prep week.

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 

Official Rules for the 2012 Scripting Games Challenge

$
0
0

Summary: The official rules for the 2012 Scripting Games challenge announce the rules and the prizes to be awarded.

Microsoft 2012 Scripting Games Official Rules—No purchase necessary.

Note: It is your sole responsibility to review and understand your employer’s policies regarding your eligibility to participate in trade promotions. If you are participating in violation of your employer’s policies, you may be disqualified from entering or receiving prizes. Microsoft disclaims any and all liability or responsibility for disputes arising between an employee and their employer related to this matter, and prizes will only be awarded in compliance with the employer’s policies.

This Challenge is hosted in the United States, and entry information is collected on computers in the United States. This Challenge will be governed by the laws of the State of Washington, and you consent to the exclusive jurisdiction and venue of the courts of the State of Washington for any disputes arising out of this Challenge. If you do not agree with this provision and these Official Rules, please do not enter this Challenge.

COMMON TERMS USED IN THESE RULES:

These are the official rules that govern how the Microsoft 2012 Scripting Games Challenge promotion will operate. This promotion will be simply referred to as the “Challenge” throughout the rest of these rules. The Challenge consists of a skill based contest (“Contest”) and daily and Grand Prize random drawing sweepstakes (“Sweepstakes”). In these rules, “we,” “our,” and “us” refer to Microsoft Corporation, the sponsor of the Challenge. “You” refers to an eligible Challenge entrant.

WHAT ARE THE START AND END DATES?

This Challenge starts at 12:01 a.m. Pacific Time (PT) on April 2, 2012, and ends at 11:59 PM PT on April 13, 2012 (“Entry Period”). The Entry Period contains 10 separate Daily Prize Periods. Each Daily Prize Period will begin at 12:01 AM PT and end at 11:59 PM PT on each weekday (Monday – Friday) during the Entry Period.

Entries must be received within the Entry Period to be eligible.

CAN I ENTER?

You are eligible to enter this Challenge if you meet the following requirements at time of entry:

You are a professional in the field of IT / software research, sales or development and;

You are NOT a resident of any of the following countries: Cuba, Iran, North Korea, Sudan, and Syria.

  • You are NOT an employee of Microsoft Corporation or an employee of a Microsoft subsidiary; and
  • You are NOT involved in any part of the administration and execution of this Contest; and
  • You are NOT an immediate family (parent, sibling, spouse, child) or household member of a Microsoft employee, an employee of a Microsoft subsidiary, or a person involved in any part of the administration and execution of this Contest; and

If you are 18 of age or older, but are considered a minor in your place of residence, you should ask your parent’s or legal guardian’s permission prior to submitting an entry into this Contest.

This Challenge is void outside of the geographic area described above and wherever else prohibited by law.

HOW DO I ENTER?

The Challenge consists of a skill contest (“Scripting Contest”) and ten (10) daily Sweepstakes drawings.

To enter the Scripting Contest, you must visit http://2012sg.poshcode.org/Auth/LogOn website and following instructions for new members to register for the Scripting Contest or for existing members to login to the website. When you are successfully logged in, follow instructions to successfully complete the 10 daily task-based scenarios that make up the “2012 Scripting Games.”

You will receive one Sweepstakes entry into each Daily Prize Period during which you submit a 2012 Scripting Games entry.

Limit one (1) Daily Prize Period entry per day, regardless of the number of 2012 Scripting Games entries that you submit each day.

We are not responsible for entries that we do not receive for any reason, or for entries that we receive but are not decipherable for any reason.

We will automatically disqualify:

  • Any incomplete or illegible entry; and
  • Any entries that we receive from you that are in excess of the entry limit described above.

WINNER SELECTION

At the close of the Entry Period, the entrant who achieved the highest scoring entry in each 2012 Scripting Games category (Beginner and Advanced) based on the judging criteria set forth here, will win the Contest prize described below.

At the close of each Daily Prize Period, will randomly select ten (10) winners from among all eligible entries received that day, to receive a daily prize described below. Non-winning entries will not be carried forward into subsequent daily prize drawings.

PRIZES

2 Contest Prizes:

  • A Tech·Ed 2012 North America full conference pass (Approximate Retail Value , ARV, $2,195). Prize consists of the pass only; all other associated travel or other expenses are the sole responsibility of the winner.
  • A phone discussion with Distinguished Microsoft Engineer Jeffrey Snover.

129 Daily Prizes:

Two of the following items (1 Beginner, 1 Advanced) will be awarded each day.  The assignment of prizes will be determined by Microsoft and announced each day.  

  • (1) Voucher toward in-class training of 3 or more days with up to 12 students, or toward a 1-day online class with up to 8 students from Don Jones and Concentrated Technology (ARV $750 )
  • (1) PrimalScript 2011 Universal from SAPIEN Technologies (ARV $999)
  • (2) PrimalScript 2011 Studio from SAPIEN Technologies (ARV $599)
  • (2) PrimalForms 2011 from SAPIEN Technologies (ARV $299)
  • (2) PowerShell Video Training Set from SAPIEN Technologies (ARV $99)
  • (3) Windows PowerShell 2.0:TFM ebook from SAPIEN Technologies (ARV $34.99)
  • (5) PowerShell Plus Professional Edition version 4.0 from Idera (ARV $199)
  • (2) PowerWF from Devfarm Software (ARV $499)
  • (1) PowerShell Video Library from Interface Technical Training (ARV $500)
  • (50) ebooks from O’Reilly Media (ARV $20.00)
  • (50) ebooks from Manning (ARV $40.00)
  • (10) Amazon Gift ecard from BeyondTrust (ARV $50.00)

We will only award one Contest Prize, and one Daily Prize per person during the Entry Period.

If you are a potential winner, we will notify you by sending a message to the e-mail address, the phone number, or mailing address (if any) provided at time of entry within fourteen (14) days following the random drawing. If the notification that we send is returned as undeliverable, or you are otherwise unreachable for any reason, we may award the prize to an alternate, randomly selected winner.

If there is a dispute as to who is the potential winner, we will consider the potential winner to be the authorized account holder of the e-mail address used to enter the Challenge. If you are a potential winner, we may require you to sign an Affidavit of Eligibility, Liability/Publicity Release and a W-9 tax form or W-8 BEN tax form within 10 days of notification. If you are a potential winner and you are 18 or older, but are considered a minor in your place of legal residence, we may require your parent or legal guardian to sign all required forms on your behalf. If you do not complete the required forms as instructed and/or return the required forms within the time period listed on the winner notification message, we may disqualify you and select an alternate, randomly selected winner.

If you are confirmed as a winner of this Challenge:

You may not exchange your prize for cash or any other merchandise or services. However, if for any reason an advertised prize is unavailable, we reserve the right to substitute a prize of equal or greater value; and

You may not designate someone else as the winner. If you are unable or unwilling to accept your prize, we will award it to an alternate potential winner; and

If you accept a prize, you will be solely responsible for all applicable taxes related to accepting the prize; and

If you are otherwise eligible for this Challenge, but are considered a minor in your place of residence, we may award the prize to your parent/legal guardian on your behalf; and

Unless otherwise noted, all prizes are subject to their manufacturer’s warranty and / or terms and conditions.

WHAT ARE YOUR ODDS OF WINNING?

Your odds of winning this Challenge depend on the number of eligible entries we receive.

WHAT OTHER CONDITIONS ARE YOU AGREEING TO BY ENTERING THIS CHALLENGE?

By entering this Challenge you agree:

  • To abide by these Official Rules; and
  • To release and hold harmless Microsoft, and its respective parents, subsidiaries, affiliates, employees and agents from any and all liability or any injury, loss or damage of any kind arising from or in connection with this Challenge or any prize won; and
  • That Microsoft’s decisions will be final and binding on all matters related to this Challenge; and
  • That by accepting a prize, Microsoft may use of your proper name and state of residence online and in print, or in any other media, in connection with this Challenge, without payment or compensation to you, except where prohibited by law.

WHAT LAWS GOVERN THE WAY THIS CHALLENGE IS EXECUTED AND ADMINISTRATED?

This Challenge will be governed by the laws of the State of Washington, and you consent to the exclusive jurisdiction and venue of the courts of the State of Washington for any disputes arising out of this Challenge.

WHAT IF SOMETHING UNEXPECTED HAPPENS AND THE CHALLENGE CAN’T RUN AS PLANNED?

If cheating, a virus, bug, catastrophic event, or any other unforeseen or unexpected event that cannot be reasonably anticipated or controlled, (also referred to as force majeure) affects the fairness and/or integrity of this Challenge, we reserve the right to cancel, change or suspend this Challenge. This right is reserved whether the event is due to human or technical error. If a solution cannot be found to restore the integrity of the Challenge, we reserve the right to select winners from among all eligible entries received before we had to cancel, change or suspend the Challenge.

If you attempt to compromise the integrity or the legitimate operation of this Challenge by hacking or by cheating or committing fraud in ANY way, we may seek damages from you to the fullest extent permitted by law. Further, we may ban you from participating in any of our future Challenge, so please play fairly.

HOW CAN YOU FIND OUT WHO WON?

We will post the names of winners who received a prize worth $25.00 or more at http://blogs.technet.com/heyscriptingguy. This list will remain posted one month after April 13, 2012.

WHO IS SPONSORING THIS CHALLENGE?

Microsoft Corporation
One Microsoft Way
Redmond, WA 98052

2012 Scripting Games Guest Commentators Announced

$
0
0

Summary: The guest commentators for the 2012 Scripting Games are announced today.

 2012 Scripting Games badge

Microsoft Scripting Guy, Ed Wilson, is here. Today I am proud to announce the guest commentators for this year’s Scripting Games. This group volunteered to write answers and commentaries to go along with their answers for the 20 events that make up the 2012 Scripting Games. So now, without further ado…here are the 2012 Scripting Games guest commentators.

Trevor Sullivan

Photo of Trevor Sullivan

Trevor is a pursuer of all types of knowledge, and is particularly passionate about technology and technical communities. He has been working primarily with Microsoft solutions since 2004. Trevor has received public recognition from Microsoft for his contributions to the Windows PowerShell community, and he has also written several guest blogs for the Hey, Scripting Guy! Blog. One of his more notable achievements is the release of the PowerEvents module for PowerShell, which is available on CodePlex.

Arnaud Petitjean

Photo of Arnaud Petitjean

Arnaud is an author, speaker, system engineer, and trainer. Arnaud is the founder of the French-speaking Windows PowerShell Community. He specializes in managing VMware (by using Windows PowerShell and PowerCLI) and in desktop virtualization.

Website: www.PowerShell-Scripting.com

Rich Prescott

Photo of Rich Prescott

Rich is currently working as a Windows Engineer for a market-leading global financial services firm in New York City. He started learning Windows PowerShell in 2009 while he was working as a desktop engineer. He is an author for the Microsoft TechNet Wiki. He is also a moderator on the Official Scripting Guys Forum, and he recently received the Microsoft Community Contributor award.

Personal blog: Engineering Efficiency
Microsoft blog: WikiNinjas - Official Blog of TechNet Wiki
Microsoft profile: Rich Prescott on TechNet
Twitter: @Rich_Prescott

Jeremy Engel

Image of Jeremy Engel

Jeremy works in the health care industry as a lead systems engineer and architect, promoting new technologies and helping drive their acceptance and implementation. Being a fanatic of efficiency and automation, he also focuses on developing programs and scripts to ease the burden of administration for himself, his colleagues, and the community. His most notable contribution thus far is the PowerShell Module for DHCP. He is currently working on releasing a multitude of other modules and scripts.

He is a great admirer of the Windows PowerShell community and is honored to be a judge for this year’s Scripting Games. He wishes all the contestant’s happy scripting and good luck! Jeremy’s proudest contributions to this world are his three wonderful children, who together with his beautiful wife live in the bustling metropolis of Oak Ridge, North Carolina.

Michael Frommhold

Photo of Michael Frommhold

Michael is a senior premier field engineer for Microsoft Germany. His technology foci are Active Directory, development (.NET, PoSh, VBS) and platforms. Apart from supporting customer Active Directory infrastructures, he provides workshops and customized knowledge transfers to teach customers how to implement coding and scripting against Active Directory and platform technologies.

Tome Tanasovski

Photo of Tome Tanasovski

Tome is a Windows engineer for a market-leading global financial services firm in New York City. He is the founder and leader of the New York City PowerShell User group, a blogger, and a regular contributor to the Official Scripting Guys Forum. In 2011, he became a cofounder of the NYC Techstravaganza, coauthored the Windows PowerShell Bible, and received the title of Honorary Scripting Guy from the Hey, Scripting Guy! Blog. Tome has also received the MVP award in Windows PowerShell from Microsoft for the last two years. 

Jeffery Hicks

Photo of Jeffrey Hicks

Jeffery is a Microsoft MVP in Windows PowerShell, Microsoft Certified Trainer, and an IT veteran with 20 years of experience—much of it spent as an IT consultant specializing in Microsoft server technologies. He works today as an independent author, trainer, and consultant. Jeff writes the popular Prof. PowerShell column for MPCMag.com, and he is a regular contributor to SMB IT Simplified and the Petri IT Knowledgebase. Jeff is a regular speaker at conferences, such as TechEd, and he often speaks about Windows PowerShell, Active Directory, Group Policy, and anything else than can make IT Pros more efficient and productive.

Richard Siddaway

Photo of Richard Siddaway

Richard has been working with Microsoft technologies for over 22 years, and he spent time in most IT roles including analyst-programmer, server administration, support, DBA and architect. He has been interested in automation techniques (including automating job creation and submission on mainframes many years ago!). He has used VBScript and WMI since it became available on NT 4. Windows PowerShell caught his interest when he first heard about it  and he has been using it since the early beta versions.

He founded and runs the UK PowerShell User Group, and he is a Windows PowerShell MVP. He has given numerous talks about Windows PowerShell at various events in the UK, Europe, and the USA. He is a frequent speaker for Windows PowerShell user groups worldwide. He has a number of articles published about Windows PowerShell, including expert commentary’s on the Microsoft Scripting Games for which he has been a judge for the last two years. Windows PowerShell in Practice (Manning) was published in June 2010 and he is currently finishing PowerShell and WMI (Manning) to be published in 2012. Another book                               about Windows PowerShell 3.0 will be published towards the end of 2012. 

Blogs:
Richard Siddaway's Blog: Of PowerShell and Other Things 
PowerShell for Windows Admins
IT Knowledge Exchange: Get Answers from Your Peers

Sean Kearney

Photo of Sean Kearney

Sean “The Kraken” Kearney is an infrastructure support analyst, Microsoft MVP in Windows PowerShell, and member of the Springboard Technical Experts Program. He is also one of this year’s first ever Honorary Scripting Guys and the mystery persona behind The BATCHman and Cmdlet. He is presently writing a book about Windows PowerShell.

He is so passionate about Windows PowerShell that he tried naming a pet gerbil “Cmdlet,” and then he attempted to use a Get-Wheel | Invoke-Run on it. We have been advised that he is also barred from any caffeinated beverages when he is presenting due to “The Edmonton Affair” at TechDays Canada.

Boe Prox

Photo of Boe Prox

Boe is currently a senior systems administrator with BAE Systems. He has been in the IT industry since 2003, and he has been working with Windows PowerShell since 2009. Boe looks to script whatever he can, whenever he can. He is also a moderator on the Official Scripting Guys Forum. Check out his current projects published on CodePlex: PoshWSUS and PoshPAIG.

Blog: Learn PowerShell | Achieve More
Guest posts on Hey, Scripting Guy! Blog
Twitter: @proxb

Jonathan Medd

Photo of Jonathan Medd

Jonathan has been working with IT infrastructure products since 1997. A few years ago, he discovered Windows PowerShell, and he now cohosts the Get-Scripting PowerShell podcast. Since April 2010, he has been a Microsoft MVP for Windows PowerShell, and in 2011 was honored as a VMware vExpert. He is co-author of VMware vSphere PowerCLI Reference.

Chad Miller

Chad is a senior manager of database administration at Raymond James Financial. Chad has worked with Microsoft SQL Server since 1999, and he has been automating administration tasks by using Windows PowerShell since 2007. Chad is a Windows PowerShell MVP and the project coordinator and developer of the Windows PowerShell-based CodePlex project, SQL Server PowerShell Extensions (SQLPSX). Chad leads the Tampa PowerShell User Group, and he is a frequent speaker at users groups, SQL Saturdays, and Code Camps.

Blog: Sev17—SQL Server, PowerShell, and so on
Twitter: @cmille19

Lee Holmes

Photo of Lee Holmes

Lee is a senior software engineer on the Microsoft Windows PowerShell team, and he has been an authoritative source of information about Windows PowerShell since its earliest betas. He is the author of the Windows PowerShell Cookbook, Windows PowerShell Pocket Reference, and the Windows PowerShell Quick Reference.
 
Blog: Precision Computing
Twitter: http://www.twitter.com/Lee_Holmes
LinkedIn: http://www.linkedin.com/pub/lee-holmes/1/709/383

Thomas Lee

Photo of Thomas Lee

Thomas is an IT Pro with over 40 years experience. He’s a WindowsPowerShell MVP, and he is very busy writing, consulting, and training for some of the key Microsoft technologies, including Windows PowerShell, Lync, and Windows Server and client. In his spare time, he lives in a small cottage in the UK with his wife, daughter, and a nice wine cellar. He has a large collection of Grateful Dead live recordings (which are managed, of course, by using Windows PowerShell).

Blogs:
Under The Stairs
PowerShell Scripts Blog
Twitter: @doctordns

Gary Siepser

Photo of Gary Siepser

Gary is a premier field engineer (PFE) in Customer Services and Support (CSS) at Microsoft. He works with customers that have a limited technology focus, and he helps premier support customers get the most from their Microsoft infrastructure. He used to be a messaging PFE, supporting Exchange Server, and he is a Microsoft Certified Master in Exchange 2007. But he has morphed to 100% Windows PowerShell support engagements.

He delivers premier workshops and provides services such as custom-scoped onsite Windows PowerShell knowledge transfer and sample solutions to help customers solve their needs. He is the Windows PowerShell tech lead within his PFE organization, and he focuses on IP development, internal readiness, and Train-the-Trainer (TTT); recruits instructors; and promotes Windows PowerShell throughout PFE and by proxy to customers. 

Blog: Gary's $this and that about PowerShell and Exchange
Microsoft Services Premier Support site

Shane Hoey

Photo of Shane Hoey

Shane’s scripting experience started when Windows XP was the new kid on the block, and he soon found himself scripting on a daily basis with VBScript, WMI, and ADSI. Fast forward to the Scripting Games 2009—he finally discovered Windows PowerShell, and he has been hooked ever since. One of the things he likes most about Windows PowerShell is its ability to easily automate tasks.

Twitter: @shanehoey
Aussie PowerShell Usergroup

Kirk Munro

Photo of Kirk Munro

Kirk is a five-time recipient of the Microsoft Most Valuable Professional (MVP) award for his deep involvement with the Windows PowerShell community. He has worked in the IT industry for more than 15 years, with the last five years focused 100% on Windows PowerShell and software solutions that use Windows PowerShell. He currently works at Devfarm Software as Product Manager for the PowerWF and PowerSE products.

When he's not working on PowerWF and PowerSE, Kirk spends his time working with Windows PowerShell in the community. He is the president of the PowerShellCommunity.org site, a central hub for all things PowerShell. He is also a frequent blogger, and he presents at conferences, launch events, and user group events whenever he gets the opportunity.

Blog: Poshoholic: Totally addicted to PowerShell 
Twitter: http://twitter.com/Poshoholic 
Linked-in profile: http://www.linkedin.com/in/kirkmunro 
Facebook profile: http://www.facebook.com/kirk.munro
Personal profile: http://poshoholic.com/about

Chris Bellee

Chris is a premier field engineer for Microsoft. He is based in Sydney, Australia. He teaches a very popular Windows PowerShell class to Microsoft premier customers.

Tobias Weltner

Photo of Tobias Weltner

Dr. Tobias Weltner is Germany’s first Windows PowerShell MVP. Tobias trains and coaches enterprises throughout Europe and helps IT Pros and administrators understand, leverage, and love the Power of PowerShell. He also shares his knowledge on PowerShell.com, and he regularly airs webcasts about exciting Windows PowerShell topics such as multithreading and performance.

As a software developer, he created scripting IDEs to make scripting easier, such as Systemscripter (VBScript), the first graphical IDE for PowerShell (PowerShellIDE), and the award-winning PowerShellPlus, which is now part of Idera, Inc. He provides consultant services to enterprises (Windows PowerShell-enabled applications and solutions). As a Rotarian, Tobias is the youth exchange officer, and he enjoys organizing the world-wide youth exchange. He also likes diving and climbing and is curious to discover new things.

Email: tobias.weltner@email.de
PowerShell.com

Marco Shaw

Photo of Marco Shaw

Marco has been in the IT industry for almost 15 years, and he is currently working for the IT consulting company CGI. He supports Windows servers and Linux, and he enjoys the various daily challenges he faces. He is a five-time recipient of the Microsoft MVP award for his support of Windows PowerShell online and offline communities.

Thanks to all of our guest commentators. 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

2012 Windows PowerShell Scripting Games: All Links on One Page

2012 Scripting Games Beginner Event 1: Use Windows PowerShell to Identify a Working Set of Processes

$
0
0

 2012 Scripting Games badge

Summary: Beginner Event 1 of the 2012 Scripting Games uses Windows PowerShell to identify a working set of processes.

About this event

Division

Beginner

Date of Event

4/2/2012 12:01 AM

Due Date

4/9/2012 12:01 AM

Event scenario

You are the network administrator for a small, single-location company. Your desktops are all running Windows 7, and your servers are all running Windows Server 2008 R2. Your company has a single domain, and Windows PowerShell remoting is enabled on all computers—both servers and desktops. Your boss is concerned because a number of users have complained that their computers are slow. This is surprising and alarming because each user received a new desktop when they were migrated to Windows 7. To better get a handle on what is going on with the desktop computers, your boss has directed you to ascertain the top ten processes that are consuming memory resources on each computer.

You decide, after doing a bit of research, that the working set of each process would be the best property to track. You also decide to use Windows PowerShell to gather the information. An acceptable output is shown in the following image.

Image of command output

Design points

  • There is no need to write a script for this event.
  • The command you use should be CAPABLE of running remotely against other computers in the domain, but you are not required to have multiple computers available for this scenario.
  • Because this command can be a one-liner, aliases are acceptable in your submission.
  • Your command should return an object that could be piped to additional commands.
  • You should be able to write the results of your command to a file if required (but writing to a file is not a requirement for this scenario).

2012 Scripting Games links

2012 Scripting Games: All Links on One Page

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. Good luck as you compete in this year’s Scripting Games. We wish you well.

Ed Wilson, Microsoft Scripting Guy 

2012 Scripting Games Advanced Event 1: Review a Coworker’s Script

$
0
0

 2012 Scripting Games badge

Summary: Advanced Event 1 of the 2012 Scripting Games asks you to review a coworker’s script.

About this event

Division

Advanced

Date of Event

4/2/2012 12:01 AM

Due Date

4/9/2012 12:01 AM

 

Event scenario

You work as a network administrator for a large company. You are part of a team of other network administrators that monitor several mission critical applications. Your coworker has convinced your boss that he knows everything about Windows PowerShell. As a result, whenever any scripting needs to be done, he always gets the nod. Recently, however, your boss has begun to have some doubts, and the boss has asked you to do a code review of the script that is shown here:

MonitorNotepadFor10Seconds.ps1

$notepad = Get-Process notepad

for ($i = 1 ; $i -le 10 ; $i++)

{

 start-sleep 1

 $notepad

}

When you run the script, you receive the output that is shown here:

Image of command output

Design points

  • If no changes are required to the script, put “No changes” in your entry for this event.
  • If changes are required:
    • Make the minimum number of changes to the script. Points will be deducted if you make too many changes.
    • Consider the performance of the script when you make changes.

2012 Scripting Games links

2012 Scripting Games: All Links on One Page

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. Good luck as you compete in this year’s Scripting Games. We wish you well.

Ed Wilson, Microsoft Scripting Guy 


2012 Scripting Games Beginner Event 2: Find Stoppable Running Services

$
0
0

 2012 Scripting Games badge

Summary: In Beginner Event 2, you have to find stoppable running services.

About this event

Division

Beginner

Date of Event

4/3/2012 12:01 AM

Due Date

4/10/2012 12:01 AM

 

Event scenario

You are a server administrator for a medium-sized enterprise company. Your boss wants you to write a Windows PowerShell script to shut down servers across the network. Instead of simply shutting down the servers, he wants you to investigate a more controlled shut down of services prior to actually shutting down the server.

As a first step in this process, you need to find all services that are running that will actually accept a Stop command. You need to run this command remotely against trusted computers that have the appropriate ports open through their firewalls, so your command must work against remote computers.

An appropriate output is shown in the following image.

Image of command output

Design points

  • For the purposes of this exercise, you do not need to have a second computer against which to run.
  • For the purposes of this exercise, you do not need to test firewall connections, nor do you need to configure the firewall. Assume that the appropriate ports are opened.
  • Use the simplest command that will work. You do not need to write an entire script.
  • Display the output to the screen; you do not need to write to a text file.
  • It is permissible to use standard aliases (if any exist). It is NOT permissible to use non-standard aliases that do not exist without special configuration.

2012 Scripting Games links

2012 Scripting Games: All Links on One Page

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. Good luck as you compete in this year’s Scripting Games. We wish you well.

Ed Wilson, Microsoft Scripting Guy 

2012 Scripting Games Advanced Event 2: Find Information about Remote and Local Services

$
0
0

 2012 Scripting Games badge

Summary: In Advanced Event 2, you must find information about remote and local services.

About this event

Division

Advanced

Date of Event

4/3/2012 12:01 AM

Due Date

4/10/2012 12:01 AM

Event scenario

You are a server administrator for a medium-sized enterprise company. Your boss has tasked you with finding the way that all services on all servers start. You need to present your findings in a spreadsheet that includes the following information:

  • The server name
  • The service name
  • The start mode of the service
  • The user account used to start the service
  • The current status of the service

An acceptable output for this task is shown in the following image.

Image of command output

Design points

  • You should use the easiest method possible to display the information in a spreadsheet.
  • You must include the ability to run the script both on a local computer and on a remote computer.
  • You must include the ability to run the script with alternate credentials when operating against a remote computer—you should impersonate the logged on user when running locally.
  • You do not need to add comment-based Help for this scenario, but additional points are awarded if you do include appropriate comment-based Help, such as a description, examples, and parameters.
  • If the script requires administrative rights to run, you should check to ensure that the script is running with admin rights. If those rights are not present, you should display an appropriate message and exit.
  • For the purpose of THIS exercise, do not write a module. You should make your script stand completely alone, with NO external dependencies. Therefore, EVERYTHING this script needs should be put in this script. Failure to do so will cost you points.

2012 Scripting Games links

2012 Scripting Games: All Links on One Page

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. Good luck as you compete in this year’s Scripting Games. We wish you well.

Ed Wilson, Microsoft Scripting Guy 

Scripting Wife Discusses 2012 Scripting Games Beginner Event 1

$
0
0
Hi everyone. Well, Ed (the Microsoft Scripting Guy) is totally swamped with the 2012 Scripting Games, and so I thought I would jump onto Live Writer and write a quick post about Beginner Event 1. I noticed that Ed has been keeping up pretty well with...(read more)

What to expect during the Scripting Games

$
0
0
Summary: the Scripting Wife discusses what she has learned in the last several Scripting Games. Well, it is hard to believe that I could be considered a veteran of the Scripting Games. But I guess I am because this is my third Scripting Games. So for...(read more)

2012 Scripting Games Advanced Event 3: Create a Log that Updates

$
0
0

 2012 Scripting Games badge

Summary: Advanced Event 3 of the 2012 Scripting Games challenges you to create a log file that appends each time a person logs on to the network.

 

About this event

Division

Advanced

Date of Event

4/4/2012 12:01 AM

Due Date

4/11/2012 12:01 AM

 

Event scenario

You are “the scripting guy” at your small single location business. As a matter of fact, you are also “the Exchange Server guy,” “The AD guy,” and “The WSUS guy.” In short, you seem to do it all. The IT department consists of the CIO, you, and a Help Desk person. All servers are running Windows Server 2008 R2, and all workstations (except the IT department) are running Windows 7 Enterprise edition. About half of the workstations are running a 32-bit operating system, and the other half are running a 64-bit operating system. All of the workstations are running the 32-bit version of Microsoft Office 2010. The IT department staff (you, the Help Desk person, and the CIO) are running a beta version of Windows 8 on your client computers with a beta version of Office 2012.

Your boss, (aka, the CIO) has decided that she would like the Help Desk person to have a log that updates each time a person logs on to the network. The log, named logonstatus.txt should be stored in a folder off the root named logonlog. This file should append (the latest entries will be at the bottom of the log file) each time the user logs on. Therefore, if a user logs on to the computer 12 times in one day, there will be 12 entries in the log. Here is a list of things the CIO has mandated MUST be in the log file:

  1. The user name in domainname/username format, for example: Microsoft/EdWilson
  2. The computer name in hostname.domainname format, for example: Mred.Microsoft.Com
  3. Operating system version
  4. Service Pack level
  5. All mapped drives and path to mapped resources
  6. The default printer
  7. The last reboot of the computer
  8. The type of boot up (for example, safemode or normal)

The image shown here illustrates an acceptable output for the file.

Image of command output

Design points

  • For the purpose of this exercise, we are looking for a specific file name in a specific location.
  • The file must append. Do not overwrite the file on each log on or you will lose a point. The history aspect of the file is important to the scenario.
  • You must include all eight pieces of information in the file. If you miss information, you will lose points.
  • Neatness counts. The information presented must be accurate and easy to read by humans. Therefore, outputting as a .csv, .tsv, or .xml file will not gain extra points. In fact, because they are not very humanly readable, you will lose points for such output. The idea here is that a Help Desk person will open the file and read it.

2012 Scripting Games links

2012 Scripting Games: All Links on One Page

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. Good luck as you compete in this year’s Scripting Games. We wish you well.

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>