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

Support Our 2012 Sponsor: TechEd North America 2012

$
0
0

Big news! Our friends from TechEd North America 2012 have donated two full conference passes to give away as part of the 2012 Scripting Games. (This does not include travel costs or other expenses.) Woohoo! Keep in mind that each pass is worth more than $2,000. But you have to register and participate in the 2012 Scripting Games to qualify to win one of two full conference passes to their four day event in Orlando, FL, June 11-14. Pretty darn good deal for participating in a free event, wouldn't you say?

Because only two people can win one of the full conference passes, you should register for TechEd North America 2012 today (they’ll reimburse you, if you win). If you need more details:

Good luck in the 2012 Scripting Games, and we hope to see you at TechEd 2012 in Orlando, June 11-14.


 2012 Scripting Games badge

Back to All Sponsors page


Support Our 2012 Sponsor: O'Reilly Media

$
0
0

O'Reilly Media logo

O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, research, and conferences. Since 1978, O'Reilly has been a chronicler and catalyst of leading-edge development, homing in on the technology trends that really matter and galvanizing their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An active participant in the technology community, the company has a long history of advocacy, meme-making, and evangelism.

 2012 Scripting Games badge

Back to All Sponsors page

Support Our 2012 Sponsor: PoshCode

$
0
0

 

PoshCode.org image

PoshCode is a repository of Windows PowerShell scripts that are free for public use. As you find things useful, we only ask that you give back to our community. Contribution feed.

The original reason for the existence of this site was our set of functions for Windows PowerShell that allowed you to interact with PoshCode.org from the console.

We have both a PoshCode Module and a v1-compatible script, which expose functions for searching, downloading, and uploading code functions from Windows PowerShell. 

 2012 Scripting Games badge

Back to All Sponsors page

2012 Scripting Games Judging Criteria Revealed

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, discusses the judging criteria for the 2012 Windows PowerShell Scripting Games.

 2012 Scripting Games badge

Microsoft Scripting Guy, Ed Wilson, is here. Today is the day that I reveal the judging criteria for the 2012 Windows PowerShell Scripting Games. In many respects, good Windows PowerShell code is good Windows PowerShell code. So the judging criteria this year reflects this fact.

General criteria for good Windows PowerShell scripts

  1. You should be able to read and understand your script. If you cannot read and understand your script, you will never be able to effectively modify it or troubleshoot it.
  2. Use native Windows PowerShell cmdlets and capabilities unless a clear cut reason dictates otherwise.
  3. Use comment-based Help.
  4. Format your script to facilitate reading and understanding of the script.
    • Line up related items, and indent subordinate or dependent items.
    • Use comments, but avoid in-line comments. Instead, place comments on their own line ahead of the code to which the comment refers.
    • Avoid aliases in scripts.
    • Write your code so that it can be read without requiring horizontal scrolling. To do this, consider using variables and natural line breaks (such as the pipe (|) character). Avoid line continuation marks if at all possible, but not at the expense of creating really long lines of code.
    • Leave the pipeline character on the right side of the code.
    • Put at least one space between commands.
    • Place individual commands on individual lines unless the command is exceedingly short and separating the commands would hinder readability.
  5. Keep the integrity of an object as long as possible. Avoid using Write-Host.
  6. Write reusable, self-contained functions.
  • Functions should return objects.
  • Use Verb-Noun naming for functions.
  • Prefer the singular for nouns in function names.
  • Functions should accept piped input if it makes sense to the application.
  • Do not call a function like a method.

Specific grading criteria

All scripts are graded on a five-point scale.

  • One point is awarded for a submission. All scripts will receive at least one point.
  • One point is awarded if the script runs and meets the minimum requirements of the scenario.
    Therefore, a submitted script that runs and meets the requirements of the scenario will receive two points. If a script runs, but DOES NOT meet the requirements it will only receive 1 point, which is the same score as a script that attempts to meet the requirements of the scenario but does not work.
  • The other three points depend on the scenario.
    In most cases, there will be four or five specific criteria that a script must meet. To receive all five points, a script must meet all of these criteria. If a script omits one criterion, one point is taken from the total of five. Therefore, a script would receive four points if it met all but one of the criteria and it worked properly.
    If a scenario only lists two criteria, and the script worked properly and met both of the criteria, the script would receive five points. A script that only met one of the criteria, would receive only four points.
    However, there is an evaluation process on the part of the judge—a judge may decide that a script is only worth 2 or 3 points instead of four or five.

Script judging

It is the intention that every script will be graded by at least two judges, and that a script will receive at least one comment from a judge. This is not a contract, however, and some scripts may only receive one grade and no comments. It all depends on how busy the judges are, and on the number of scripts submitted for a particular event.

If the last two years are any indication, the first scripts submitted for the first event will in all likelihood be graded 10 or 12 times because the judges are anxious to get on with the 2012 Scripting Games. As the events progress, it is also possible that some scripts will continue to be graded many times, and others will receive only a few. This is because all judges will not be able to grade all scripts all the time (although it is possible that some judges may be able to do so).

Please keep in mind that we will run reports that will point out which scripts need grading and need comments. All the judges have full time jobs, and all are uncompensated volunteers. The real point of the Scripting Games is to learn scripting. For more background about the Scripting Games, see the following posts:

The 2012 Scripting Games are going to be great. They will be fun, exciting, and a tremendous learning opportunity. Maybe you will win and get a free pass to TechEd, a conversation with Jeffrey Snover, and a chance to write a guest blog post for the Hey, Scripting Guy! Blog. If so WOO HOO! But if not, keep plugging away. Microsoft MVP, Bartek Bielawski, did not win the Scripting Games the first time out either.

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

Announcing the PowerShell Judges for the 2012 Scripting Games

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, announces the judges for the 2012 Windows PowerShell Scripting Games.

 2012 Scripting Games badge

Microsoft Scripting Guy, Ed Wilson, is here. We are rapidly drawing to the kick-off day of April 2, 2012 when the 2012 Scripting Games begin. One of the key milestones is the introduction of the judges. This year (as in years past), we have an esteemed panel of judges—a veritable who’s who in the world of Windows PowerShell scripting. I hope you will spend some time reading these mini-biographies, and hopefully get inspired to learn all you can about Windows PowerShell. Maybe one day, your picture and biography will appear in this same virtual location.

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

Niklas Goude

Photo of Niklas Goude

Niklas is an author, trainer and technical consultant for TrueSec in Sweden. Niklas specializes in the Microsoft environment, focusing on Active Directory, SQL Server, and SharePoint products and technologies. Most of his daily work is performed using Windows PowerShell. He is also active as a trainer, teaching courses that are focused on Windows PowerShell, and he has been a speaker at various conferences, such as Microsoft Tech Days, SharePoint & Exchange Forum, and SharePoint conferences in Australia and New Zealand.

Niklas contributes to the Windows PowerShell community by sharing scripts, guides, and ideas. Niklas is active within the PowerShell community, acting as a moderator for the Official Scripting Guys Forum and as an expert at SecretsOfSharePoint.com.

He wrote PowerShell for SharePoint 2010 Administrators with Mattias Karlsson, a former colleague. He wrote e-book about Windows PowerShell (in Swedish), which covers the fundamentals of Windows PowerShell. It can be downloaded for free at www.powershell.se.

Niklas lives in Stockholm, Sweden with his wife Anna, his collection of guitars, and a lot of computers.

Blog: PowerShell.nu

Scott Smith

Photo of Scott Smith

Prior to joining Microsoft, Scott served 20 years in the U.S. Air Force with split careers in the Precision Measurement Equipment Laboratory and Computer Programming fields. His career ended in San Antonio at the Air Intelligence Agency, where he never wrote one line of code—just designed and architected solutions for three classifications of networks. He joined Microsoft in Jan 2001, and over the past 11 years he filled many roles in what is now premier field engineering: a rapid response engineer, a ROSS manager/engineering service manager, and a PFE manager during the evolution of PFE.

After seven years in mainstream PFE, he moved to Incubation Services and Support to be the team lead in driving the support model for Amalga, Microsoft’s first major investment in the health care world. For the next three years, he worked directly with the Health Solutions Group and Mergers and Acquisition to assist in growing adoption of Amalga across major health care systems. The key customers were the Mayo Clinic, John Hopkins, and New York Presbyterian. In the July 2010, he moved back into management in Amalga and saw it through three releases. Then he was tasked with leading a small team of engineers to learn Office 365 and train mainstream PFEs about IP that is focused on cloud services, which lead to the need to learn Windows PowerShell.

Outside of work, he and his wife love to cruise and travel. In the past year, he began a new passion of scuba diving and he has over 20 logged dives in six months with many scheduled this year. The picture was taken at the Devil’s Den in Williston, FL.

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.

Jim Christopher

Photo of Jim Christopher

Jim runs Code Owls LLC, a software development company focusing on process automation and system integration. He delivered his first piece of software at the ripe age of 9, and he since has had the pleasure of coding in the education, defense, gaming, and IT fields. He is a Windows PowerShell MVP, and he manages numerous open-source projects that integrate Windows PowerShell with SQLite, OData, MongoDB, Redis, RabbitMQ, ASP.NET Membership, and Visual Studio. He likes to talk to developers about how they can use Windows PowerShell every day to make their lives easier.

Blog: beefycode: serving all of your beefy code needs

Twitter: @beefarino

Brandon Shell

Photo of Brandon Shell

Brandon Shell is a Microsoft MVP, and a moderator for the Official Scripting Guys Forum.

Blog: BSonPoSH: The Power of Shell

Bartek Bielawski

Photo of Bartek Bielawksi

Bartek is Windows PowerShell enthusiast, and he is still a fairly new Windows PowerShell MVP. He loves automation and he tries to automate systems whenever he can. Bartek describes his work life as, “Just a regular IT pro with a constant urge to learn more and share what he learned with others.” He uses IRC, his blogs, and forums to give back to community what he got from it—free of charge both ways.

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.

Steven Murawski

Photo of Steven Murawski

Steven is a senior Windows system engineer for edgenet and a Microsoft MVP in PowerShell. In this role, he supports a dynamic infrastructure that pushes the boundaries of the Windows platform. Windows PowerShell allows him to support this infrastructure in a more consistent and efficient manner. Steven also runs the Greater Milwaukee Script Club, and he is a board member for the Greater Milwaukee IT Pro User Community.

Blog: Use PowerShell | The Shell is Calling

Claus Nielsen

Photo of Claus Nielsen

Claus has been working as an IT professional for 13+ years, and he has been spending a lot of his time in the last eight years working with scripting and automation. He uses several languages, including batch, VBScript, AutoIT, and Windows PowerShell. The latter has been his primary scripting platform since 2007. 

Aleksandar Nikolic

Photo of Aleksandar Nikolic

Aleksandar is a system administrator, Windows PowerShell MVP, and the cofounder and editor of PowerShellMagazine. He enjoys giving Windows PowerShell presentations and reviewing Window PowerShell-related (e)books. He is a proud recipient of two Dr. Scripto bobblehead dolls. Why does he like the Scripting Games? There is no better way to learn and improve your Windows PowerShell skills and have fun all the way through. 

Blog: PowerShellers: He who controls the shell, controls the universe

Twitter: @alexandair

Bhargav Shukla

Photo of Bhargav Shukla

Bhargav is a senior premier field engineer in unified communications, with his primary focus on the Exchange Server and Lync 2010 platforms. Bhargav has been in IT since the beginning of his career 15 years ago. Before joining Microsoft, he managed to work on almost any technology an IT consultant would be required to know, including Active Directory, Exchange, RSA Security, VMware, Citrix, and Cisco. He also holds industry certifications such as Microsoft Certified Master: Exchange 2010, VMware Certified Professional, Citrix CCEA, RSA: CSE, and Cisco CCNA/CCDA.

He started working on scripting with small DOS batch scripts in his early career, and he learned to be a better scripter with new scripting languages. From batch files to VBScript and on to Windows PowerShell, he has written many scripts to address specific needs and reusable functions for repetitive code. When he is not working with customers, Bhargav teaches at MCM Exchange rotations, leads the Philadelphia Area Exchange Server User Group, shares his knowledge on his blog and twitter, plays chess, and has recently fallen in love with photography.

Mark Schill

Photo of Mark Schill

Mark is a senior architect for a leading federal government service provider in the Atlanta area. He coauthored the Windows PowerShell 2.0 Bible. He is the founder and operator of the Atlanta PowerShell User Group, and he is the current manager for the PowerShellGroup.org user group support site.

Blog: String Theory

Twitter: @meson3902

Ravikanth Chaganti

Photo of Ravikanth Chaganti

Ravikanth has 11+ years of experience in the IT industry. At the beginning of his career, he worked at Wipro Infotech managing Windows, Solaris servers, and Cisco network equipment. He currently works at Dell, Inc. as a lead engineer in the SharePoint solutions group. As a part of his work, he authored several whitepapers about MOSS 2007 and SharePoint 2010 that provide guidance about infrastructure elements of a SharePoint deployment. His work also involves performance testing and sizing of SharePoint workloads on Dell servers and storage. 

Ravikanth is passionate about automation, and he won a Microsoft Most Valuable Professional (MVP) award in Windows PowerShell. You can hear him speak regularly at Bangalore ITPro User Group meetings and other in-person events in Bangalore, India. 

Blog: Ravikanth Chaganti: SharePoint, Virtualization, Automation and much more…

Doug Finke

Photo of Doug Finke

Doug is a Microsoft Most Valuable Professional (MVP) for PowerShell. He is a software developer at Lab49, a company that builds advanced applications for the financial service industry. Doug is a consultant, author and speaker.

Blog: Development in a Blink

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

Jan Egil Ring

Photo of Jan Egil Ring

Jan works as a lead architect at Crayon, Norway. He mainly works with Microsoft server-products, and he has a strong passion for Windows PowerShell. In addition to being a consultant, he is a Microsoft Certified Trainer. He has obtained several certifications, including MCITP: Enterprise Administrator and MCITP: Enterprise Messaging Administrator.

In January 2011 and 2012 he was awarded the Microsoft Most Valuable Professional Award for his contributions in the Windows PowerShell technical community.

Blog: blog.powershell.no: On Windows PowerShell and other Admin-Related Topics           

Twitter: @janegilring

LinkedIn: Jan Egil Ring, Lead Architect, Infrastructure

Matt Johnson

Photo of Matt Johnson

Matt is a system administrator, developer, and all around hacker. He runs the Michigan PowerShell Users Group, helps run the Virtual PowerShell User Group Brown Bag Lunch Series, and is a moderator on the Official Scripting Guys Forum. In is free time, he is a member of the #MiSec information security group and spends most of his days lurking around the Internet and trying to solve problems by using Windows PowerShell.

Blog: MWJ Computing

Michigan PowerShell Users Group

Glenn Sizemore

Photo of Glenn Sizemore

Glenn is a technical marketing engineer at NetApp, where he combines Microsoft with NetApp, using Windows PowerShell as the glue. Glenn started scripting early in his IT career, and he has made a living off it ever since. Along the way he started a blog, wrote a book, and he is the proud father of two beautiful children.

Blog: get-admin: Lessons of a Datacenter Administrator

Book: VMware vSphere PowerCLI Reference: Automating vSphere Administration

Oliver Lipkau

Photo of Oliver Lipkau

Oliver is a Windows PowerShell enthusiast, sporadic Hey, Scripting Guy! Blog guest poster, MCC, and Official Scripting Guys Forum moderator.

Blog: Oliver's Blog: My germs!

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

Georges Maheu

Photo of Georges Maheu

Georges is the PFE security technology lead for Microsoft Canada. As a senior premier field engineer, he focuses on delegation of authority (how many domain admins do you really have?), on server hardening, and on doing security assessments by using his own scripts.

Georges has a passion for VBScript, Windows PowerShell, and WMI, and he uses them on a regular basis to gather information from Active Directory and computers. Also, Georges delivers popular scripting workshops to Microsoft Premier Customers worldwide.

Guest posts on Hey, Scripting Guy! Blog

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.

Don Jones

Photo of Don Jones

With more than fifteen years of IT experience, Don is one of the world’s leading experts on the Microsoft business technology platform. He’s the author of more than 35 books, including Windows PowerShell: TFM; Windows Administrator’s Scripting Toolkit; VBScript, WMI, and ADSI Unleashed; PHP-Nuke Garage; Special Edition Using Commerce Server 2002, and Definitive Guide to SQL Server Performance Optimization. Don is a top-rated and in-demand speaker at conferences such as Microsoft TechEd, Windows Connections, and TechMentor, and he is an accomplished IT journalist with features and monthly columns in Microsoft TechNet Magazine, Redmond Magazine, and on websites such as TechTarget and MCPMag.com. Don is also a multiple-year recipient of Microsoft’s prestigious Most Valuable Professional (MVP) Award, and he is the editor-in-chief for Realtime Publishers.

Ed Wilson

Photo of Ed Wilson

Ed is the Microsoft Scripting Guy and a well-known scripting expert. He writes the daily Hey Scripting Guy! Blog. He has spoken at TechEd and at the Microsoft internal TechReady conferences. He is a Microsoft-certified trainer who has delivered a popular Windows PowerShell workshop to Microsoft Premier Customers worldwide. He has written nine books, including six about Windows scripting that were published by Microsoft Press. He also contributed to nearly a dozen other books. His Windows PowerShell 2.0 Best Practices book for Microsoft Press was recently published.

Ed holds more than 20 industry certifications, including Microsoft Certified Systems Engineer (MCSE) and Certified Information Systems Security Professional (CISSP). Prior to coming to work for Microsoft, he was a senior consultant for a Microsoft Gold Certified Partner, where he specialized in Active Directory design and Exchange Server implementation. In his spare time, he enjoys woodworking, underwater photography, and scuba diving. 

2012 Windows PowerShell Scripting Games: All Links on One Page

Easily Use PowerShell to Discover the Holders of Active Directory FSMO Roles

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell to discover the Active Directory FSMO role holders

Microsoft Scripting Guy, Ed Wilson, is here. The day has arrived—it is PowerShell Saturday in Columbus, Ohio! Wes Stahler, the Scripting Wife, Ashley McGlone, Brian Jackett, and I have looked forward to this day for over four months. I am really looking forward to meeting everyone who signed up for this historic event. The way cool thing is that by the time the Scripting Wife and I are back in Charlotte, North Carolina, it will be time for my five-day series of live meetings: Windows PowerShell Essentials for the Busy Admin. If you have not signed up for those, you should, because they will cool, fun, and educational.

You know, I continue to be amazed at how powerful Windows PowerShell really is. I know I should not be amazed—after all I have been using Windows PowerShell since way before Windows PowerShell 1.0 was even in beta. You would think that after all these years I would begin to get callous, but that is not the case.

The VBScript way of doing things

One reason, I believe, is that I spent years working with VBScript prior to coming to Windows PowerShell. (In fact, I wrote three books about VBScript.) I spent nearly five years teaching VBScript to Microsoft Premier Customers. As a result, I am very familiar with the amount of effort that is required to accomplish certain tasks.

This morning, the Scripting Wife and I were sitting in the Microsoft Office in Columbus Ohio, early—real early—way before anyone would even dream of showing up. I was showing her how to use the Active Directory module to document FSO roles. She looked up at me, and said, “Didn’t you write a script to do that a long time ago?”

“As a matter of a fact I did,” I replied, “It was in VBScript.”

“Do you still have it?” she asked, “You might want to show it today while you are talking about learning Windows PowerShell.”

I was so proud. I am convinced, at times, that she is a genius. But of course, I would never actually tell her that because I would never hear the end of it. Anyway, here is a script that is very similar to the one I wrote, (I copied this one from the Scripting Guys Script Repository.)

List_FSMO_Role_Holders.vbs

Set objRootDSE = GetObject("LDAP://rootDSE")

 

Set objSchema = GetObject _

    ("LDAP://" & objRootDSE.Get("schemaNamingContext"))

strSchemaMaster = objSchema.Get("fSMORoleOwner")

Set objNtds = GetObject("LDAP://" & strSchemaMaster)

Set objComputer = GetObject(objNtds.Parent)

WScript.Echo "Forest-wide Schema Master FSMO: " & objComputer.Name

 

Set objNtds = Nothing

Set objComputer = Nothing

 

Set objPartitions = GetObject("LDAP://CN=Partitions," & _

    objRootDSE.Get("configurationNamingContext"))

strDomainNamingMaster = objPartitions.Get("fSMORoleOwner")

Set objNtds = GetObject("LDAP://" & strDomainNamingMaster)

Set objComputer = GetObject(objNtds.Parent)

WScript.Echo "Forest-wide Domain Naming Master FSMO: " & objComputer.Name

 

Set objDomain = GetObject _

    ("LDAP://" & objRootDSE.Get("defaultNamingContext"))

strPdcEmulator = objDomain.Get("fSMORoleOwner")

Set objNtds = GetObject("LDAP://" & strPdcEmulator)

Set objComputer = GetObject(objNtds.Parent)

WScript.Echo "Domain's PDC Emulator FSMO: " & objComputer.Name

 

Set objRidManager = GetObject("LDAP://CN=RID Manager$,CN=System," & _

    objRootDSE.Get("defaultNamingContext"))

strRidMaster = objRidManager.Get("fSMORoleOwner")

Set objNtds = GetObject("LDAP://" & strRidMaster)

Set objComputer = GetObject(objNtds.Parent)

WScript.Echo "Domain's RID Master FSMO: " & objComputer.Name

 

Set objInfrastructure = GetObject("LDAP://CN=Infrastructure," & _

    objRootDSE.Get("defaultNamingContext"))

strInfrastructureMaster = objInfrastructure.Get("fSMORoleOwner")

Set objNtds = GetObject("LDAP://" & strInfrastructureMaster)

Set objComputer = GetObject(objNtds.Parent)

WScript.Echo "Domain's Infrastructure Master FSMO: " & objComputer.Name

Does the script work? Well, let’s try it out and see. I save the file as ListFSMORoleHolders.vbs. I then decide to run the script by using CSCRIPT, which I call from within Windows PowerShell. It is a strange sort of irony to run a VBScript script from within Windows PowerShell. The results are shown here.

Image of command output

The Windows PowerShell way of doing things

How hard it to find the FSMO role holders by using Windows PowerShell? It comes down to only two commands. Three commands if you want include importing the Active Directory module. Four commands if you want to include making a remote connection to a domain controller to run the commands.

One cool thing about using Windows PowerShell remoting is that I specify the credentials I need to run the command. My normal account is a standard user, and I only use an elevated account when I am required to perform tasks with elevated rights. The first two commands create a remote session on a remote domain controller and load the Active Directory module.

Enter-PSSession dc3 -Credential iammred\administrator

Import-Module activedirectory

When it is loaded, I type a one-line command to get the forest FSMO roles and another one-line command to get the domain FSMO roles. These two commands are shown here.

Get-ADForest iammred.net | Format-Table SchemaMaster,DomainNamingMaster

Get-ADDomain iammred.net | format-table PDCEmulator,RIDMaster,InfrastructureMaster

That is it, two or three or four one-line commands, depending on how you want to count. Even at a worst case, four one-line commands are much easier to type than 33 lines of code. In addition, the Windows PowerShell code is much easier to read and to understand. The commands and the associated output from the Windows PowerShell commands are shown in the image that follows.

Image of command output

Well, that is it. People are starting to arrive for the first ever PowerShell Saturday. I will write more 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 Active Directory Integrated DNS

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about troubleshooting the status of Active Directory integrated DNS servers.

Microsoft Scripting Guy, Ed Wilson, is here. The first ever PowerShell Saturday that was held in Columbus, Ohio was a tremendous success. It was really great to see people who I had literally not seen for five or six years, and to meet new people for the first time ever. People came from nearly a dozen states to attend this event. It was awesome, and I look forward to helping out with the next PowerShell Saturday event.

One of the cool things about Windows PowerShell is that if a particular cmdlet does not exist, there are multiple choices for a solution. Depending on what I am seeking, I might write a quick script, dash off a fast little function, write a more reusable function, or even write a module to provide the functionality I seek. Many times, however, I do none of the above. In fact, I find myself spending a lot of time at the Windows PowerShell console plunking around. Interactive use of the Windows PowerShell console is a great way to discover information, to manage a system, or to troubleshoot a problem.

Today, I ran into a problem. It always happens when we come back home—or at least it seems to be a problem when we come back home after having been gone for a while. The network is down—or at least that was the report from the Scripting Wife. What the Scripting Wife actually meant to say was that from her computer in the kitchen, she was unable to connect to Facebook. That, in my mind, hardly qualifies as the network is down…but I digress.

The first thing I needed to do, after ensuring that her computer could actually communicate with other machines on the network, was to look at DNS. Indeed, it seemed to be a name resolution issue, because it turned out I could ping by IP address, by not by name. I have a rather complicated network at home, and I could not remember which of my domain controllers are actually running DNS (because I am using Active Directory integrated DNS).

The first thing I do is create a remote session to one of my domain controllers. (I do this because my computer does not have the RSAT tools installed.) The command is shown here, and it enables me to use alternate credentials, if needed. (My normal user account is as a regular user, and so I need to specify an account with admin rights.)

Enter-PSSession -ComputerName dc3 -Credential iammred\administrator

When I have done that, I import the ActiveDirectory module. This command is shown here.

Import-Module activedirectory

Now I need to retrieve a list of all of my domain controllers. To do this, I use the Get-ADDomainController cmdlet, and I use a wild card for the Filter parameter. For each of the domain controller objects that return from the previous command, I need to find out the status of the DNS Server service on the machine. To do this, I use the Get-Service cmdlet. Luckily the Get-Service cmdlet accepts a value for the ComputerName parameter, so I can use this one command to get the status of the DNS Server service on all of the returned domain controllers. After this is complete, I want to know the computer name, the name of the service, and the status of the service. The complete one-line command is shown here.

Get-ADDomainController -Filter * | foreach { Get-Service DNS -ComputerName $_.hostname} | Select machinename, name, status

The command tells me that the DNS Server service is stopped on one of the domain controllers. Unfortunately, the Start-Service cmdlet does not have a ComputerName parameter, so I cannot use it directly. But the Invoke-Command cmdlet does have a ComputerName parameter, so I can start the DNS Server service on the remote server in this way. The command is shown here.

Invoke-Command -cn dc1 {start-service dns}

Now I use the Up arrow to retrieve the prior command and to check the status of the DNS servers on the domain controllers. The command tells me that the service is now running. These commands, and the associated output are shown in the image that follows.

Image of command output

I check downstairs with the Scripting Wife and she is now happy—she can talk on Facebook with the friends she just saw. Cool. Now maybe I can find some time to relax and read a book. I just got a copy of Herman Wouk’s The Caine Mutiny, and I am excited to compare it to the Humphrey Bogart movie with the same title.

I will talk to you tomorrow, until then cheers.

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 Explore Active Directory Security

$
0
0

Summary: Learn how to use Windows PowerShell to explore Active Directory Security settings on objects.

Hey, Scripting Guy! Question Hey, Scripting Guy! I have a problem. My boss told me I need to document the access rights for objects that are in Active Directory. I have absolutely no idea how to do this. I open up Active Directory Users and Computers and I do not see anything about security settings. To be honest, I have never modified security on any object in Active Directory in my life—and I have been doing this sort of stuff for nearly a decade. I am too embarrassed to ask my boss (also just a bit scared if the truth be told), so I thought I would give you a shout out. Your blogs have saved my bacon more than once, although this is the first time I have ever written. I know you must get thousands of emails every week, I just hope you will see fit to answer mine. Sitting with my fingers crossed…

—HJ

Hey, Scripting Guy! Answer Hello HJ,

Microsoft Scripting Guy, Ed Wilson, is here. I am sitting here sipping a cup of green tea with a cinnamon stick in it. Nothing fancy—no gunpowder, no dragons or other exotic creatures in my tea cup, just a simple cup of green tea. Sometimes the simple things in life are worth contemplating. I thought I would jump over and check the scripter@microsoft.com email, and HJ, I ran across your email. First of all, I feel that I should say one should never be embarrassed because one does not know something. I often admit that I do not know something, and I am not embarrassed because the world of computers has exploded in the last decade. No one can be expected to know everything about everything. In fact, I am highly suspicious when I run into someone and they claim to be “an expert on Active Directory” or some other topic. Areas like Active Directory are huge, and are highly complex, and I know people who specialize in very minute areas of Active Directory. I know of only a few people who would qualify as a total expert on all facets of Active Directory.

But I digress…I am going to talk about three ways to find security information on an object in Active Directory. I am going to use an organizational unit named posh.

First, the GUI way

The first way I need to show you is by using the Active Directory Users and Computers MMC. The reason you did not see anything related to security is that by default the security information is hidden. You need to use the View menu and select Advanced from the Action menu. When Advanced is selected, the security tab becomes visible. In addition to revealing additional tabs about objects in Active Directory, it also shows hidden containers and other items that are normally not messed with during day-to-day administration. It is probably a good idea to clear the Advanced option when it is not in use—that is what I do on a normal basis. The image that follows shows the View menu from Active Directory Users and Computers with the Advanced option selected.

Image of folder

Once the Advanced option is selected, the Security tab (and other tabs) appear. One tab that I especially like is the Attribute editor tab because it is like ADSI Edit, and it is convenient having it built into the tool. The Security tab showing security settings for the posh organizational unit is shown in the image that follows.

Image of folder

Using DSACLS

Anyone who needs to do much work with Active Directory, especially in the security arena, should become familiar with DSACLS. DSACLS is a tool that permits viewing and assigning security rights to objects in Active Directory. The syntax is a bit convoluted, but once mastered, it is a very easy tool to use, and it can integrate easily within Windows PowerShell.

Note   For more information about using legacy commands from within Windows PowerShell, see this series of Hey, Scripting Guy! Blogs.

When used with no parameters, DSACLS enters query mode and returns security information. Therefore, to view the security settings on the posh organizational unit, I need to use only the DSACLS command and provide it with the distinguished name of the object. An example of this is shown here.

dsacls "ou=posh,dc=iammred,dc=net"

The command and the associated output are shown in the image that follows.

Image of command output

Using the Active Directory Provider

I have read a lot of blogs bemoaning the fact that there is no cmdlet to get the security settings of an object in Active Directory. By corollary, there would not be a cmdlet to set security either. But there really is! I can use the same cmdlets that I use for the file system, for the registry, and for other items. The cmdlets are Get-ACL and Set-ACL. That’s right, you do not need to learn a new cmdlet. This is the great thing about Windows PowerShell providers—they are extensible.

So the first thing I do is enter a remote Windows PowerShell session to a computer that has the ActiveDirectory module installed. By default it is the domain controllers in my network. I have not installed the RSAT on my computer since I rebuilt it a week or so ago. Upon establishing the remote Windows PowerShell session, I import the Active Directory module, and I set my working location to the Active Directory drive. These commands are shown here.

Enter-PSSession dc3 -Credential iammred\administrator

Import-Module activedirectory

set-location ad:

Now, it is really simple, I use the Get-ACL cmdlet to retrieve the security access settings for my organizational unit. I then pipe the results to the Format-Table cmdlet, and I choose the IdentityReference and the AccessControlType attributes. This is shown here.

(Get-Acl 'ou=posh,dc=iammred,dc=net').access | ft identityreference, accesscontroltype -AutoSize

The commands and the associated output are shown here.

Image of command output

If I do not happen to know the value of the DistinguishedName attribute of the object that I am interested in examining, I can use the Get-ADOrganizationalUnit cmdlet to retrieve the DistinguishedName value for me. An example of this is shown here.

(get-acl (Get-ADOrganizationalUnit -Filter 'name -eq "posh"').distinguishedname).access | ft identityreference, accessControlType –AutoSize

As seen in the image that follows, the results are the same as in the previous command.

Image of command output

Now, this command is getting really hairy, and you may be asking, “Why don’t I just stick to DSACLS?” And of course, you can. But the great thing about using Windows PowerShell is that the commands build, and they also mix and match. Instead of needing to parse text, I can work with objects. One really cool thing to do is to send the output to Out-GridView. But this command does not work in a remote Windows PowerShell session. So to do something like that would require installing the RSAT tools on my local computer or using RDP to connect to the server that has the Active Directory module.

HJ, that is all there is to working with Active Directory security. Join me tomorrow as we once again return to Windows PowerShell Coolsville.

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 Set Exchange Server Aliases for an Entire Organizational Unit

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shows that with a little knowledge of Windows PowerShell, it is easy to administrator products like Exchange Server.

Microsoft Scripting Guy, Ed Wilson, is here. Yesterday’s live meeting, Windows PowerShell Essentials for the Busy Admin went extremely well. I am looking forward to today’s live meeting because I will be talking about using the Windows PowerShell pipeline. I made an impromptu posting last week that has the abstracts for all five sessions, in addition to the registration links. All the sessions will be recorded, and made available via the Learn PowerShell page. But if at all possible, you should attend the live meeting—it is more fun, and you get to ask questions. The questions, for me anyway, are the highlight of the event.

The other day I was hanging out on Twitter, and I noticed a tweet about a particular blog post. I read the post, and I decided that I needed to meet the person who wrote it. As it turns out, the author, Derek Schauland, is a Microsoft MVP and a real fun person to talk with. During our conversation, he mentioned wanting to script mass changes to user’s aliases on an Exchange Server. He said that he needed aliases that would be formatted as First name <period> Last name, and not as First initial, Middle initial, Last name that he currently has. I thought it would be a cool script—but more than a script, I figured I could do it as a one-liner in Windows PowerShell.

PowerShell is PowerShell is PowerShell

I have said this before, but it bears repeating: PowerShell is PowerShell is PowerShell! This means that if you know Windows PowerShell, you can easily use it to perform other tasks. For example, because I know Windows PowerShell pretty well, I am familiar with the Windows PowerShell pipeline. I know that I can take the output from one cmdlet, and in general, pipe the input to another cmdlet (assuming the cmdlet accepts piped input). This means that all I need to do is find certain cmdlets, and then find other cmdlets, and then I can accomplish what I need.

Enable mailboxes for test users

For example, I have a group of test users in an organizational unit, and I need to enable their mailboxes. I happen to know that Microsoft Exchange Server ships with a cmdlet called Get-User. It stands to reason that Get-User will be able to get all the users in my test OU. I try it out, and it works. I next decide that a cmdlet to enable a mailbox on a user should be called something like Enable-Mailbox, and that it should accept pipelined input. Here is the command that I decided to try.

Get-User -OrganizationalUnit mytestou | Enable-Mailbox

I give it a whirl, and before I know it, I have enabled mailboxes for all five of my test users. The image that is shown here contains the command that I typed and the output from the command.

Image of command output

Verify the current email aliases

That went well. Now I want to take a look at the aliases for these users. I think the Get-Mailbox cmdlet will provide that information. I use the Up arrow to retrieve the previous command, and I change the Enable-Mailbox cmdlet to the Get-Mailbox cmdlet. The revised command is shown here.

Get-User -OrganizationalUnit mytestou | get-mailbox

The command and the associated output shown in the image that follows confirm my suspicion that the Get-Mailbox cmdlet does indeed provide the alias information.

Get-User -OrganizationalUnit mytestou | get-mailbox

Image of command output

Use PowerShell objects

One of the most powerful features of Windows PowerShell is that everything is an object. This means that instead of having to parse a bunch of text, all I need to do is find the property and access it. I just saw that the property I need exists on a mailbox object—it is the Alias property. At least I am assuming that I need the Alias property because most of the time, the property that appears at the head of a table is the actual property name that might be needed in other places.

Note   Occasionally, developers decide to change the column heading to make things more friendly, but this really annoys most advanced Windows PowerShell users. This goes back to the old problem that the fields that appear in Active Directory Users and Computers are not the names needed when writing an LDAP query. Luckily in Windows PowerShell, all I need to do is pipe the output to Get-Member if a command fails due to renamed table headers.

I also reason that if Get-Mailbox displays the information, then Set-Mailbox should set the information—it makes sense, right? I will give it a shot. But before I do, because I have not used Set-Mailbox very often, I decided to take a look at Get-Help on the Set-Mailbox cmdlet. The results are shown here.

Image of command output

OK, now I need to change the email aliases from First name Last name to First name <period> Last name. To do this, I use the Foreach-Object cmdlet to walk through the piped input. Inside the Foreach-Object cmdlet, I call the Set-Mailbox cmdlet. I use a format operator to create the pattern for the new email alias. The command is shown here. (This command is a one-line command, but I broke it for readability at the pipeline character. The % sign is an alias for the Foreach-Object cmdlet).

Get-User -OrganizationalUnit mytestou |

% {Set-Mailbox -Identity $_.identity -Alias ("{0}.{1}" -f $_.firstname, $_.lastname)}

No output displays from the command, so I decide to rerun my command to get the mailboxes. This command, the previous command, and the output from the commands are shown in the image that follows.

Image of command output

 

Cool, it worked! That is all there is to using Windows PowerShell to modify user aliases in Microsoft Exchange Server. I invite you to 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 

PowerShell Pie for Pi Day

$
0
0

Summary: Use the built in pi value in an impromptu function to get the circumference of a circle by using Windows PowerShell.

Microsoft Scripting Guy, Ed Wilson, is here. The Scripting Wife and I are still pretty geeked out from the first ever Windows PowerShell Saturday that was held in Columbus Ohio. Add that today will be the third live meeting in the PowerShell Essentials for the Busy Admin series, and the week is pretty complete. But, as they say on late night television (at least in the United States), “Wait! There is more!” I completed writing all the events for the 2012 Scripting Games, and I emailed them off to the 20 guest commentators. I completed the 2012 Scripting Games quiz and got it sent off to the people who will turn it into an online quiz. And in just a few days, it will be International PowerShell User Group day! Now that ought to be enough to make any geek or geekette jump up and down with excitement.

How to get pi in PowerShell

I know I wrote a blog about not using the .NET Framework classes—but I was talking about unless you need to do so. Well, the easy way to get access to pi is to use the .NET Framework Math class. Pi is available as a static property, which means it is always available. I know that pi is equal to 3.14, or 22/7, but that is about it. Beyond the first few digits, it starts to get fuzzy for me. But I do not need to remember it because I can use the static pi property from the Math class. The following example illustrates using the pi property from the Math class to obtain a more precise value than simply 3.14.

PS C:\> [math]::pi

3.14159265358979

The key to using a static property from a .NET Framework class is remembering to use the double colon symbol (::). If you are wondering how I found this property, it is easy—I used the Get-Member cmdlet. This technique is shown here.

[math] | Get-Member –Static

The command and the associated output are shown here.

Image of command output

Suppose I need to calculate the circumference of a circle. In fact, I do this quite often in my woodworking shop. I cut out a circle for a tabletop, and I want to add an edge band to the circle so that it does not display open-pored end grain. Well, I need to know the circumference of the circle so I know how long of a piece of wood to cut. I could use paper and pencil, and perform this calculation:

Circumference = 2πr

Creating an impromptu function that uses pi

One of the cool things I can do in Windows PowerShell is creating an impromptu function. I do not need to open the Windows PowerShell ISE, type out a long convoluted script containing a function, then save it and dot source it into my Windows PowerShell console. Instead, I can create the function on the fly and use it throughout my session.

function get-circumference { Param($r)2*[math]::pi*$r }

Image of command output

Instead of using the Function keyword, I can also create the function directly on the function drive. To do this, I use the New-Item cmdlet. The code to do this is shown here.

New-Item -path function:get-circumference -Value {Param($r)2*[math]::pi*$r}

The code to create the Get-Circumference function directly on the function drive and the associated output are shown in the image that follows.

Image of command output

Well, that is about all there is to using pi to get the circumference of a circle. I need to get to work on prepping for today’s live meeting. See you then. Join me tomorrow when I will talk about more cool Windows PowerShell stuff.

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

Ed Wilson, Microsoft Scripting Guy 

Microsoft Script Explorer for Windows PowerShell Beta 1 Now Available

$
0
0

We are very excited to announce the availability of Microsoft Script Explorer for Windows PowerShell Beta 1 (Script Explorer). Script Explorer is an extension of the Windows PowerShell content and guidance experience, and it combines the vast amount of knowledge held in the community with the resources that are available from Microsoft. With Script Explorer, you can:

  • Discover information that is related to Windows PowerShell from across the community and Microsoft.
  • Search seamlessly across repositories such as PoshCode.org and the Microsoft Script Center to locate samples that are relevant to you.
  • Establish, grow, and search corporate repositories.

Community and Microsoft guidance in one place

Script Explorer combines the rich information from the community and the guidance that is available from Microsoft, which helps you realize more of the benefits of Windows PowerShell. Script Explorer brings together resources such as the Windows PowerShell Survival Guide, how-to guidance, and videos. You can filter the results to the products that are relevant to you.

Search across multiple repositories

Script Explorer enables a single search experience across multiple repositories, including PoshCode.org and the Microsoft Script Center, which allows you to locate script samples, snippets, and modules. You can filter search results, read reviews and comments, and seamlessly integrate into Windows PowerShell ISE to further customize your environment.

Build a trusted library of scripts for your company

Script Explorer makes it easy to build a library of scripts for personal use or to establish and grow a corporate library of trusted scripts, modules, and snippets. You can also extend Script Explorer to include your own providers by using the Script Explorer Provider Reference.

Free download now!

Get started today with this free download of Microsoft Script Explorer for Windows PowerShell Beta 1.

Support

For support, visit Script Explorer for Windows PowerShell at the Microsoft Script Center online forums.

Also visit the forum for the latest status on Script Explorer services, to ask questions, and to provide feedback about Script Explorer. If you currently host a public repository, and you would like to make it available through Script Explorer, please contact Microsoft Script Explorer Customer Support <secustsupp@microsoft.com>.

Additional information

Beware the Ides of March—But by Who's PowerShell Calendar?

$
0
0

Summary: Learn about using Windows PowerShell and specifying different calendar types to use with dates.

Microsoft Scripting Guy, Ed Wilson, is here. Today is day four of my PowerShell Essentials for the Busy Admin series of webcasts. The series has been a lot of fun, and the feedback so far has been great. It is encouraging to see the level of interest in this series. In addition, there have been a decent amount of questions via the scripter@microsoft.com email alias about the series of live meetings in addition to the 2012 Scripting Games.

Today is the Ides of March. For the Scripting Wife, it means March Madness is underway. For me, I think back to the play by William Shakespeare, Julius Caesar. Beware the Ides of March…

If you want to work with calendars in Windows PowerShell, perhaps you should also beware of the Ides of March—or at least be aware of how to work with different calendar types.

Anyway, the .NET Framework classes are fun to play with. If I want to create a specific date, I can use the constructor for the System.DateTime .NET Framework class and create a date. To do this, I use the New-Object cmdlet to specify the name of the .NET Framework class I want to use, and I pass the arguments for the constructor to the ArgumenLlist parameter.

With the System.DateTime .NET Framework class, there are several different constructors. As a matter of a fact, MSDN lists 11 different constructors on the System.DateTime details page. To create a new DateTime object and specify the year, month, and day, requires me to use a particular constructor. Using Windows PowerShell to create a new instance of the System.DateTime class by passing the year, month, and day is shown here.

PS C:\> New-Object system.datetime -ArgumentList 2012,3,15

Thursday, March 15, 2012 12:00:00 AM

Of course, I can do the same thing by using the Get-Date cmdlet. I am not certain it is any easier, but it is a bit less typing. It is definitely easier to read the Get-Date command. This command and the output associated with the command are shown here.

PS C:\> Get-Date -Month 3 -Day 15 -Year 2012

Thursday, March 15, 2012 5:29:42 PM

The easiest way to create a specific date is to cast a string to the DateTime object. This technique is shown here.

PS C:\> [datetime]"3/15/12"

Thursday, March 15, 2012 12:00:00 AM

All three of the previous examples, however, use the same calendar—the Gregorian calendar. A problem arises if I need to specify a particular calendar. To do this, I need to first create an instance of the specific calendar I want to use. Next, I use the constructor for the System.DateTime class that permits supplying the specific calendar. Because today is the Ides of March, it makes sense to use the Julian calendar as an example. Julius Caesar ordered a calendar reform that resulted in the creation of the Julian calendar. The Julian calendar is the predecessor of the Gregorian calendar.

Luckily, the .NET Framework makes these types of conversions from calendar to calendar really easy. I only need to create a new instance of the JulianCalendar class to be able to use it in the constructor to create a Julian calendar type of date. Once again, I use the New-Object cmdlet to create an instance of the class. But I do not need to pass any arguments to the JulianCalendar class. Therefore, no ArgumentList parameter is needed.

In the code that follows, I use the New-Object cmdlet to create a new instance of the JulianCalendar class, and I store the resulting calendar in the $j variable. I then use this calendar in the New-Object command that creates a specific date. The result is a specific date, reflected in a specific calendar. These two lines of code are shown here.

$j = new-object system.globalization.julianCalendar

New-Object system.datetime -ArgumentList 2012,3,15,$j

There are lots of different types of calendars defined in the .NET Framework. All of the calendars reside in the System.Globalization .NET framework namespace. To get a feel for the different calendars, spend a bit of time on MSDN and review the various calendar classes.

In the image that follows, I first create a DateTime object that represents March 15, 2012, and I display that DateTime object to the Windows PowerShell console. I then create an instance of the JulianCalendar class, and store that calendar in the $j variable. I next use the New-Object cmdlet and create the date March 15, 2012 by using the Julian calendar. These commands and the associated output are shown in the image that follows.

Image of command output

If you want to know what a specific calendar does, you can create the calendar object, store it in a variable, and then display the contents of that variable. Information returned by doing this includes the minimum supported date and the maximum supported date. In the image that follows, I list information for both the Julian calendar and the Gregorian calendar.

Image of command output

Anyway, beware the Ides of March—especially if you are not sure what calendar is being used.

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 Edit the Registry on Remote Computers

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to edit the registry on remote computers.

Microsoft Scripting Guy, Ed Wilson, is here. In Wednesday’s PowerShell Essentials live meeting presentation, one of the questions revolved around working with the registry on a remote computer. While there are lots of ways to work with the registry on a remote computer, including using Windows Management Instrumentation, or .NET Framework classes, I like to use a combination of Windows PowerShell remoting and the Windows PowerShell registry provider because it is easier. In fact, by using Windows PowerShell remoting, it is just as easy to work with the remote registry as it is to work with a local registry.

Note   
For a good introduction to using Windows PowerShell to work with the registry, see The Scripting Wife, Windows PowerShell, and the Registry.
For more advanced topics, check out some of the other blog posts about the registry in the Hey, Scripting Guy! Blog archives. There you will find blogs such as:

Suppose I want to create a new registry key under HKEY_CURRENT_USER under the Software key, and I want to call it HSG. The registry location (for the target HSG) is shown in the following image.

Image of menu

To create the new registry key, I use the four steps:

  1. I use the Push-Location cmdlet (pushd is an alias) to store my current location.
  2. I use the Set-Location cmdlet to change my working location to the HKCU:\Software location.
  3. I use the New-Item cmdlet to create the new registry key.
  4. I use the Pop-Location cmdlet (popd is an alias) to return to my current location.

The commands are shown here.

PS C:\> pushd

PS C:\> Set-Location HKCU:\Software

PS HKCU:\Software> New-Item -Name HSG

    Hive: HKEY_CURRENT_USER\Software

SKC  VC Name                           Property

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

  0   0 HSG                            {}

PS HKCU:\Software> popd

PS C:\>

 

The newly created registry key is shown in the image that follows.

Image of menu

To add a registry property value, I use the New-ItemProperty cmdlet. I perform the same basic steps I used to create the registry key, but I use the New-ITemProperty cmdlet instead of the New-Item cmdlet, as follows:

  1. I use the Push-Location cmdlet to store my current location.
  2. I use the Set-Location cmdlet to change my working location to the HKCU:\Software location.
  3. I use the New-ItemProperty cmdlet to create the new registry property. I specify the Name, Path, Value, and PropertyType.
  4. I use the Pop-Location cmdlet to return to my current location.

The use of these techniques is shown here.

PS C:\> pushd

PS C:\> Set-Location HKCU:\Software

PS HKCU:\Software> New-ItemProperty -Name forscripting -PropertyType string -path hsg -Value "PowerShell Rocks"

 

PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\hsg

PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software

PSChildName  : hsg

PSDrive      : HKCU

PSProvider   : Microsoft.PowerShell.Core\Registry

forscripting : PowerShell Rocks

 

PS HKCU:\Software> popd

PS C:\>

The newly created registry property is shown in the image that follows.

Image of menu

After I have done all this locally, it is really easy to do it against a remote computer. I can do it by using Windows PowerShell remoting by using the following steps:

  1. I use the Get-Credential cmdlet to retrieve a credential object to use to make a remote connection.
  2. I use the Enter-PSSession cmdlet to enter a remote PS Session.
  3. I use the Push-Location cmdlet to store my current location.
  4. I use the Set-Location cmdlet to change my working location to the HKCU:\Software location.
  5. I use the New-Item cmdlet to create the new registry key.
  6. I use the New-ItemProperty cmdlet to create the new registry property. I specify the Name, Path, Value, and PropertyType.
  7. I use the Pop-Location cmdlet to return to my previous location.
  8. I use the EXIT command to leave the remote PS Session.

The following image illustrates this technique.

Image of command output

I then use Remote Desktop to connect to the remote server to verify that the registry key and property are updated. This is shown in the following image.

Image of menu

Well, that is about it for creating a remote registry key. Join me tomorrow, when I will talk about doing this in a single command—a scenario that is useful when you need to make changes on multiple computers.

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 

Edit the Registry on Multiple Remote Computers with PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to edit the registry on multiple remote computers with one command.

Microsoft Scripting Guy, Ed Wilson, is here. The PowerShell Essentials for the Busy Admin series was a huge success. Not only were there a lot of people who attended the live meetings, but there will be way people who will download and use the recordings in the future. If you were able to attend, I hope you enjoyed the series as much as I enjoyed making the presentations. Doing the presentations does take a lot of work, and requires a lot of time, but it is worthwhile.

On Monday, I am speaking for International PowerShell User Group Day. I will be doing one of the presentations from the Charlotte Windows PowerShell user group meeting—this will be a blast. On Friday, I am speaking at the Charlotte IT Pro Appreciation Day conference in Charlotte. Nearly a thousand people will be attending this all day event. The Scripting Wife is helping out with registration, so if you are in the area, you will probably get a chance to see her. The following week I am speaking at the TechStravaganza in New York. It seems that there is something nearly every week from now until TechEd. Speaking of Microsoft TechEd 2010, the Scripting Wife and I will be there manning the Scripting Guys booth. If you have not registered, you should. It will be a great event. Besides the event, I grew up in Florida, and I relish any occasion to head back down south. If you are having a hard time keeping up with the schedule—so am I. This is why I add all the events to the community page on the Script Center.

Anyway…

Yesterday, I talked about Use PowerShell to Edit the Registry on Remote Computers. I used the same technique that I used to create a registry key on a local computer by using the Registry provider.

The technique I illustrated worked just fine for setting a registry key and value on a single remote computer. But if more than one computer needs the change, the method of entering a remote Windows PowerShell session is a bit cumbersome. Clearly, it is better than a lot of mousing around; but still, it is cumbersome.

One way to avoid this and to enable the ability to make changes on multiple machines is to turn the commands into a single line. It is then really easy to run the command by using the Invoke-Command cmdlet. To do this, I use the following steps:

  1. Use the Get-Credential cmdlet to retrieve cmdlets. Store the returned credential in a variable.
  2. Use the Invoke-Command cmdlet to run the command on remote computers.

The two commands are shown here. Keep in mind that the second command is one long command that has wrapped over several different lines. I have not included line continuation for this command.

$cred = Get-Credential iammred\administrator

Invoke-Command -cn dc3 -cred $cred {pushd;sl HKCU:\software; ni HSG; New

-ItemProperty -name forscripting -PropertyType string -path hsg -value "powershell rocks" ; popd}

The registry key is the same registry key and registry property that I created in yesterday’s blog. I test the command, and the commands and the output associated with the commands are shown in the image that follows.

Image of command output

Now, I decide to test the command against two computers. The only change required is to add an additional computer name to the -cn property (I deleted the registry key on DC3 prior to running the code the second time). This is shown here.

Image of command output

I decide to make one more test. I have a text file that contains the names of some of the servers on my network. The file is Servers.txt. Each line of the file contains a different computer name, as shown here.

Image of file

I can use the Get-Content (gc is an alias) cmdlet to read the contents of the text file. Instead of specifying a particular computer name, I can use Get-Content to retrieve the computer names for me. The revised command is shown here.

$cred = Get-Credential iammred\administrator

Invoke-Command -cn (gc c:\fso\servers.txt) -cred $cred {pushd;sl HKCU:\software; ni HSG; New-ItemProperty -name forscripting -PropertyType string –path hsg -value "powershell rocks" ; popd}

The image that follows illustrates these commands, and the output associated with the commands.

Image of command output

Well, that is about it for today. Join me tomorrow when I will talk about testing for registry keys and deleting them.

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 Find and Remove Remote Registry Entries

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell to find and remove registry entries from remote systems.

Microsoft Scripting Guy, Ed Wilson, is here. It seems that weekends go faster and faster these days. For one thing, spring has definitely sprung down here in Charlotte, North Carolina in the southern portion of the United States. In fact, this past week we had to mow the grass in our yard. But we have not yet turned on our solar collector (that will happen in about another week or so).

Anyway, I am mellowing out around the house this morning—the Scripting Wife plans to meet up with a few friends later in the day. Tomorrow is International PowerShell User Group Day, and I am reviewing the presentation I will make for that important event. On Friday, I make two presentations at the Charlotte IT Pro Appreciation Day conference in Charlotte, North Carolina. That conference is expected to attract nearly a thousand people from all over the area, and it should be an excellent educational opportunity. I am looking forward to attending some great sessions, in addition to the two sessions that I present.

One question I received during the past week of Live Meetings was about finding and removing registry entries—not only from a local session, but also from remote computers. To do this, I like to use the Windows PowerShell registry provider, and incorporate it with Windows PowerShell remoting.

In Use PowerShell to Edit the Registry on Remote Computers, I talked about one way to use Windows PowerShell remoting to create new entries on a remote computer. In Edit the Registry on Multiple Computers with PowerShell, I talked about running one command and editing the registry on multiple computers.

Note    Today I will continue that discussion as I discuss finding and removing registry entries from multiple computers. For a good introduction to using Windows PowerShell to work with the registry, see The Scripting Wife, Windows PowerShell, and the Registry.
For more advanced topics, check out some of the other blog posts about the registry in the Hey, Scripting Guy! Blog archives. There you will find blogs such as:

In the image that follows, there is an HSG registry key that contains a ForScripting property. Both of these need to be detected, and if they exist, they need to be deleted.

Image of file

The steps involved in detecting and removing the HSG registry key are as follows:

  1. Use Push-Location to store the current location (pushd is an alias).
  2. Use Set-Location to change the working location to the registry drive (sl is an alias).
  3. Use Test-Path to determine if the HSG registry key exists.
  4. Use Remove-Item to remove the registry key.
  5. Return to the original location by using Pop-Location (popd is an alias).

The actual commands are shown here.

Pushd

sl HKCU:\Software

Test-Path hsg

Remove-Item hsg

popd

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

Image of command output

When I know I can successfully test for the presence of a specific registry key, and I know I can remove that registry key, I can put the commands together in a single command. This will facilitate using them with the Invoke-Command cmdlet to run against multiple remote computers.

I recreate the registry key on my local computer by using the commands that are shown here.

pushd

sl HKCU:\Software

New-Item -Name hsg

New-ItemProperty -Name forscripting -PropertyType string -Path hsg –Value “PowerShell Rocks”

popd

Now, I create a single command to test for the registry key and to remove it if it exists. To do this, I use a semicolon to separate the logical commands. In addition, I added the if statement to determine if the registry key exists before I attempt to delete it. In the else condition, I display a message that the registry key does not exist. The command is shown here.

pushd;sl HKCU:\Software; if(test-path hsg){remove-item hsg}ELSE{"hsg does not exist"};popd

After I know the single line command works properly, I can easily add it to the Invoke-Command cmdlet to find and delete the registry key on all remote servers that are listed in the servers.txt file. The content of the servers.txt file is shown in the image that follows.

The revised command is a single-line logical command that spans multiple lines in the console. This command is shown here.

invoke-command -cn (cat c:\fso\servers.txt) -credential iammred\administrator {pushd;sl HKCU:\Software; if(test-path hsg){remove-item hsg}ELSE{"hsg does not exist"};popd}

Well, that is about all there is to testing remote machines to see if they contain a specific registry key. 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 


Celebrate International PowerShell User Group Day

$
0
0

Summary: Today is International Windows PowerShell User Group Day. Find a user group near you and join in the festivities.

Microsoft Scripting Guy, Ed Wilson, is here. The day has finally arrived—at least one of the days. Today is International PowerShell User Group Day. Today every Windows PowerShell user group in the world will attempt to host meetings at similar times. We will be conducting three remote sessions at three different times. Because of bandwidth constraints, you will need to attend a Windows PowerShell user group meeting near you to see the show. Don Jones and I will be speaking, and it will be great. I will be making one of my broadcasts from the Charlotte Windows PowerShell User Group meeting. We anticipate that it will be a great event.

So how do you find a user group in your area? Well, you can use the map of the United States on the Community page of the TechNet Script Center and simply click a location. That will take you to a page that details the meeting times and contact information for the user group. An image of the map is shown here.

Image of map

If you are not in the United States, you can use the PowerShell User Groups Worldwide map on the PowerShell Community Groups site to find a Windows PowerShell user group near you.

What if you find that there are no Windows PowerShell user groups in your area? You can start one, of course. In fact, someone started all of the Windows PowerShell user groups—it might as well be you. Over the past year, the Scripting Wife and I have worked with several people to launch new Windows PowerShell user groups in their area. In fact, the Scripting Wife worked really closely with Microsoft PowerShell MVP, Jim Christopher, to start the Windows PowerShell user group in Charlotte, North Carolina.

I describe the visit to the Corpus Christi Windows PowerShell user group meeting in A Visit to a PowerShell User Group by the Scripting Guys blog post. I was really fortunate because I happened to be in Corpus Christi, Texas at the time Mark Adam Carter was planning his first Windows PowerShell user group meeting; therefore, I got to speak at their first meeting.

So what is a Windows PowerShell user group? Well for one thing, it is a great way to meet people who share an interest in Windows PowerShell. You will quickly find that people in the Windows PowerShell community are very giving, receptive, and willing to help other people learn this engaging and useful technology.

Each Windows PowerShell user group is as different as the individuals who make up the group, but at the Charlotte Windows PowerShell user group, we have two formats. On one month, we have a set agenda with a formal presentation on a specific topic. During the first meeting, I spoke about creating and using Windows PowerShell modules. On alternate months, we have a “script club” type of meeting where we divide the group into clusters of people who have a common interest in a specific script. For example, at one table, there were people who had a specific problem and everyone at the table pitched in to help fix the script. At another table, one person showed cool scripts that he had written. He also entertained suggestions for improvement to the script. At the end of the day, everyone walked away with a feeling of accomplishment.

There are other reasons for joining a Windows PowerShell user group besides the direct learning activities. For example, it is a great way to increase your professional network. I have numerous stories of IT Pros who have obtained jobs due to someone they met at a user group meeting. In addition, these meetings are a great way to find professional mentors, or to find someone with whom you can assist in their professional career. So basically, there is a lot of give and take that goes on with these meetings.

If you decide that you would like to start a Windows PowerShell user group, you should read Practical Tips for Starting a PowerShell User Group and Mark Schill Discusses PowerShell User Groups. Mark is the founder and president of the Atlanta PowerShell User Group. When you get your group established, send me email at scripter@microsoft.com so that we can arrange a time for me to talk to your group in person or via Live Meeting. Oh yeah, you will also want to make sure you contact Mark Shill so he can update the PowerShell Community Groups site. A listing on that site is a great way to ensure that people can find you.

Join me tomorrow for more Windows PowerShell coolness.

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

Ed Wilson, Microsoft Scripting Guy

Support Our 2012 Sponsor: Idera

$
0
0

Idera image

PowerShell Plus is the most advanced Interactive Development Environment for Windows PowerShell available today. PowerShell Plus features a powerful interactive console, an advanced script editor and debugger, and a comprehensive interactive learning center all integrated into a single product.

Try PowerShell Plus today and see how much more productive you can be!

 2012 Scripting Games badge

Back to All Sponsors page

Use Strict Mode for PowerShell to Help You Write Good Code

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about calling a method like a function and using Windows PowerShell strict mode to aid script development.

Microsoft Scripting Guy, Ed Wilson, is here. Believe it or not, the 2012 Scripting Games begin in less than two weeks! That is right, less than two weeks; it hardly seems possible. But April 2, 2012 is rapidly approaching. In one respect, preparing for the 2012 Scripting Games is much like preparing for a marathon—you begin with small distances and gradually increase intensity and distance until you approach race day. However, with the 2012 Scripting Games, it is not race day, but race two weeks. Yes, for two weeks, the 2012 Scripting Games will be front and center in the minds and hearts of thousands of scripters from around the world. Who will emerge victorious? Who will win the free pass to TechEd 2012 in Orlando, Florida? Who will appear on the PowerScripting PodCast and talk to Jeffrey Snover? Who will get to hang out with the Scripting Guy and the Scripting Wife at the Scripting Guys booth at TechEd? Who will get to write a guest blog post that chronicles a meteoric rise to fame? Well…it could be you!

The Scripting Games point out documentation white space

The Scripting Games are as much of a challenge for me as they are for you—but in a different sort of way. The product of literally thousands of hours of work by hundreds of different people, the Scripting Games is first and foremost, a logistical exercise. But right up next to that, the Scripting Games provides me with a chance to evaluate the things I have written about and to assess gapes in the content (the infamous white space). It never fails that in the ramp up to the Scripting Games, I discover some topic—either small or quite large—that I have neglected to cover. It might be during the preparation of the Study Guide, or during the selection of the emphasis topics, or even during the creation of the Scripting Games Quiz.

Today, it was none of the above—it was a comment on the 2012 Scripting Games Judging Criteria.

How do I call a method?

In one of my judging guidelines, I mentioned that it is not a good idea to call a function like a method. This is, by the way, true—you should not call a function like a method. But what does this really mean? As you probably know, a method does something. In Windows PowerShell, we always use parentheses when calling a method. This is one way that you can tell when you read the code whether the code is retrieving a property or calling a method. In VBScript script, the parentheses were optional, and at times it was literally impossible to tell whether the code called a method or retrieved a property.

At times, the name would indicate if the item was a method or a property, but not always. For example, size is a property of an object, as is color. The member setDate is likely a method that sets the date of an object, and the member formatDisk is a method that will format a disk. But what about count? Well, it is possible that count is a property that tells you how many items are in something, but at the same time count could be a method that forces an enumeration of the number of items in a collection. Therefore the name of the member does not tell me if it is a method or a property. What about the code? In VBScript script, the following code works:

colItems.count

coItems.count

In the first instance, I retrieve the count property, and in the second instance I call the count method. Don’t go cross-eyed trying to perceive the difference, they are the same. On the other hand, in Windows PowerShell, I would have the following:

$colItems.count

$colItems.count()

You can see, I add the parenthesis when I want to call a method in Windows PowerShell; therefore, the parenthesis delineate the difference between a property and a method. Let me further illustrate this technique by creating an old-fashioned COM object, and then calling a method from that COM object.

$wshShell = New-Object -ComObject wscript.shell

$wshShell.Popup("Hi")

To retrieve a property from the same object, I use the dotted notation and access it directly. This is shown here.

$wshShell.CurrentDirectory

How do I call a function like a method?

The following code creates a simple function called test. It will write whatever I pass to it by using the Write-Host cmdlet.

function test {Param($a,$b) write-host $a $b}

When I call this function like a method, I use the parentheses next to the function call itself. This is shown here.

test("hi", "there")

If I want to enable strict mode, the previous command would fail. To enable strict mode, I use the Set-StrictMode cmdlet. This is shown here.

Set-StrictMode -Version 2.0

When I repeat the previous command, an error appears that states I attempted to call the function or command as if it were a method. This error message is shown in the image that follows.

Image of command output

There are two ways that I can type the command and avoid being “trapped” by strict mode. The first technique simply uses a space between each of the two parameters. The second technique uses named parameters. These two techniques are shown here.

PS C:\> test "hi" "there"

hi there

PS C:\> test -a "hi" -b "there"

hi there

PS C:\>

When I specify Set-StrictMode -Version 2.0, it checks the following items:

  • Uninitialized variables
  • References to non-existent properties of an object
  • Calling a function like a method
  • Variables without a name

You may say, “But wait! Windows PowerShell 3.0 is coming around the corner. Do I need to go back and modify all my Windows PowerShell scripts?”

The answer is, “No.” I can set strict mode for version 1.0 right now on my computer running Windows 7 (with Windows PowerShell 2.0 installed). If I use strict mode for version 1.0, it only checks for references to uninitialized variables.

If you always want to use the most stringent rules, set strict mode to Latest. In this way, Windows PowerShell uses the latest rules that apply to whichever Windows PowerShell version you are running. This could, however, cause scripts to break when unforeseen new rules suddenly apply.

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 

Avoid PowerShell Errors by Initializing Variables

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using the Set-StrictMode Windows PowerShell cmdlet to aid in detecting uninitialized variables.

Microsoft Scripting Guy, Ed Wilson, is here. Charlotte, North Carolina is alive with color this morning. There is a blue jay sitting on the light post at the end of the driveway, and a cardinal munching on our newly sewn grass seed in the front yard. The various bushes, trees, and shrubs are blooming in the neighborhood. But the chief color right now is the yellowish-green color of the pollen from all the tall willowy southern pines. These evergreens guarantee color all year long; although right now, their chief contribution is the color of pollen. It will be this way for the next few weeks. The rain yesterday knocked it from the air, and left it on the grass, the drive, and the sidewalks of our neighborhood. The Scripting Wife promptly closed the windows and turned on the air conditioner. Me? The pollen does not bother me too badly, so I prefer to sit on the lanai with my laptop, the ceiling fan, a cup of English Breakfast tea, and a freshly baked blueberry scone.

That’s the nice thing about wireless—I can now work the way I prefer to work instead of being tied to a within 10 feet of a LAN drop. Beyond peaceful coexistence with my feathered friends, there is another reason I am sitting on the lanai…I am looking for the cable truck because my Internet connection suddenly dropped off this morning while I was checking my email. This is a real shame because I am missing a meeting I really wanted to attend. Oh well. At least I have my Windows7 phone. (Disclaimer: my employer, the Microsoft Corporation, bought me a Windows7 phone. They did not buy the Windows7 phone that the Scripting Wife uses, but she had to have one after she saw how cool my phone was.) So I can keep in touch with all the members of my team—in fact, I used it to look up the support phone number of my ISP.

The problem of uninitialized variables

One of the cool things about writing Windows PowerShell scripts (indeed, writing most scripting languages) is that you can quickly whip up a bit of code to solve problems. Some languages make this easier than others, some are quite verbose, and others are rather terse, but one advantage of scripting is that it permits rapid development.

This advantage is also a disadvantage. It permits bad habits. As long as you are aware of the bad habits and their attendant consequences, you can use this to your advantage. After all, the goal is to quickly solve a problem. But every so often, these bad habits can cause horrible consequences. This situation usually occurs when an impending deadline is rapidly barreling down the track, and the svelte one-liner has morphed into a 550-line FrankenScript. Having stood at the end of a darkened tunnel with a single light looming large upon my countenance whilst frantically attempting to unravel a mess of spaghetti code, I decided to embark upon a quest for Windows PowerShell best practices (indeed, that was one reason for my book). 

In the script that follows, the value of the $a variable increments five times each time the script runs. This is because the value of $a is never initialized.

UnitializedVariable.ps1

1..5 | foreach{

 $a++}

$a

The result of running this script three times is shown in the image that follows.

Image of script

The problem with such a script, especially when it is run from within the Windows PowerShell ISE, is that the initial value of $a changes each time the script runs. Therefore, you never know the final value of the $a variable. If you are counting something like running processes, stopped services, or errors in a particular event log, it is difficult to know what the expected value might be; and therefore, it is easy to let the error slip by undetected.

Detecting and solving the problem of uninitialized variables

The easiest way to detect the problem of uninitialized variables is to use the Set-Strictmode cmdlet. To do this, add the command at the top of the script. One of the great things about the Set-Strictmode cmdlet is that it only affects the current scope and all child scopes (as opposed to using the older Set-PSDebug –strict command, which affects the global scope).

When it is added, the Set-Strictmode cmdlet detects uninitialized variables and generates an error. The Set-Strictmode cmdlet does this whether the value of the Version parameter is 1, 2, or Latest. The following code shows adding the Set-StrictMode cmdlet to the top of the previous script.

Set-StrictMode -Version 1

1..5 | foreach{

 $a++}

$a

 Image of script

Use the version to apply the right amount of protection

It is important to keep in mind what -Version 1 and -Version 2 check for in strict mode. -Version 1 checks for uninitialized variables. See yesterday’s blog, Use Strict Mode for PowerShell to Help You Write Good Code, for a discussion of the -Version 2 checks.

Correcting the problem of the uninitialized variable requires declaring the variable and assigning a value to it. This technique is shown here.

InitializedVariable.ps1

Set-StrictMode -Version 1

$a = 0

1..5 | foreach{

 $a++}

$a

Now when the script runs, the correct value returns. This is shown in the following image.

Image of script

One thing to keep in mind about uninitialized variables and using Set-StrictMode and –Version 1, is that while it will detect an uninitialized variable that is directly accessed, it permits access to an uninitialized variable within a string. For example, when I use the Set-StrictMode cmdlet to set strict mode -Version 1, an error occurs when directly accessing an uninitialized variable. This technique is shown here.

Set-StrictMode -Version 1

$a

However, if I attempt to access the value of the variable from within an expanding string, no error generates. This technique is shown here.

"the value of `$a is $a"

The previous commands and their associated output are shown in the image that follows.

Image of command output

If accessing an uninitialized variable from within a string is a problem, the answer is to use Set-StrictMode –Version 2. When I set strict mode -Version 2, uninitialized variables within strings also generate an error. The command is shown here.

Set-StrictMode -Version 2

When set, both of the two commands that follow generate errors.

$a

"the value of `$a is $a"

The previous commands and their associated output are shown in the image that follows.

Image of command output

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 

Scripting Manager Agrees to Judge the 2012 Scripting Games

$
0
0
Summary : Caught up in the excitement of all the 2012 Scripting Games prep work, the Scripting Manager agrees to be a judge this year. Microsoft Scripting Guy, Ed Wilson, is here. I have a bit of exciting news! Dave Bishop, "the Scripting Manager,...(read more)
Viewing all 3333 articles
Browse latest View live


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