January 2011 Archives

powershell

Ok yes.

I’m being dramatic.  But I got your attention!

If you’ve worked on ANY level with Microsoft SQL Server 2008 and SQL Server 2008R2 you’ll know there are Windows Powershell Cmdlets.   The problem is it’s via “MiniShell” which is a sort of bastardized version of Powershell customized for SQL.

Well not REALLY but there is no shortcut for it.

No wait, I lied.  There is.  But it’s shortcut to an evil compiled “Quasi” Powershell session.   But it DOES use snapins.  But when you’re IN the “Mini-Shell” (Strikes me as “Mini-Me” accomplice to Dr. Evil) it won’t LET you run the “useful stuff” like “GET-PSSNAPIN”

But AHA! It *IS* using Snapins and those Snapins ARE Registered.

So by opening Windows Powershell and keying in

GET-PSSNAPIN –Registered

We get a handy output like this

image

So we could just add this our Profile but today I would like to just make a CUSTOM Powershell session with a Shortcut.

“Just cuz!”

So if you keyed in Powershell.exe /? within Cmd.exe or Powershell.exe you’ll see a pile of useful parameters you can use.  These are especially useful if you intend to schedule Powershell scripts as a task.  Today we’re just going to leverage the “-command” and “-noexit” parameters as we create a new Shortcut in Windows to launch our new Custom shell.

So within Windows on the Desktop, we’re just going to Right Click and choose “New Shortcut” which will launch that old familiar Wizard.  We’re going to Browse to “C:\Windows\System32\WindowsPowershell\v1.0\powershell.exe”

 

image

 

Once we have the shortcut selected, let’s “NEXT” and name that “SQL Powershell Console” (You could name it Ernie or Joey, but that might be more confusing later on when you need to use it)

After you complete, pull up the Properties on your new shortcut and you’ll to add the following info after “Powershell.exe”

-noexit -command "& {ADD-PSSNAPIN SQLServerCmdletSnapin100; ADD-PSSNAPIN SQLServerProviderSnapin100}"

Now believe it or not, this ACTUALLY makes sense.  No really, I’m not pulling your leg.

“-noexit” Means after you Launch the Powershell session and run the Cmdlets or commands provided in the Command parameter, keep Powershell open.  Yes “DON’T EXIT”

“-command” Means to run the following commands in Powershell.  In our case we’re going to execute the two ADD-PSSNAPIN Cmdlets to add the SQL Server Management Snapins.  The Semicolon separating them is exactly what you think it means.  “End of this line”.  It’s the demark between one Powershell CmdLet and another.   Handy if we can’t put an invisible carriage return in there.

When you see the “& “ that means to send everything to Powershell EXACTLY as you see it.  Also note, when doing this technique, the –command parameter and all it’s goodies must be the LAST thing in the line.

Click on “Apply” and try your new Shortcut.  Doesn’t seem to do anything magic?  Of course not.   That’s because this is a normal Windows Powershell console with the SQL Snapins added in and AVAILABLE to you.

How do you tell they are there?

GET-COMMAND –module SQL*

image

There you go.  

So is there a point to ANY of this?  Sure there is.  Ever have to create a new User?  Is there any chance you might have a Vendor or inhouse application storing it’s OWN variant on user information in an SQL database?

Maybe not?

Take this to note.   It’s not difficult to add additional Snap-ins or modules this way.   It’s just another way of shaping Powershell to your own needs.

Remember, the Power of Shell is in YOU

Sean
The Energized Tech

powershell

Here’s your challenge.  Sometimes, no matter what you do, mistakes get made.   People create virtual Machines with the wrong Network Adapter time; Machines don’t migrate because of Server type mismatches.   Computers may not Autostart, simply because somebody forgot to enable the option.

That’s right.  Problems will Happen.   But with the Powershell Cmdlets in Systems Center Virtual Machine Manager 2008R2, this is less of a issue.   Because often if we have a list of things we can easily identify the problem and determine how to best resolve it.

Need to identify which machines ARE NOT starting up Automatically ?  Within SCVMM just execute this line to get a list of Machines to work with.

$VMLIST=GET-VM –VMMSERVER NAMEOFSCVMMSERVER

Now you have a complete list of your Hyper-V Machines managed by SCVMM.   Once you have the list, there is a series of properties available with GET-MEMBER.

$VMLIST | GET-MEMBER

You can now pull up the “Start Action” on all your Virtual Machines (and the stop) with this simple line

$VMLIST | Format-Table Name,Startaction,Stopaction –autosize

You can even filter this list down to show only the machines that aren’t starting automatically.

$VMLIST | Where { $_.StartAction –eq ‘Never AutoTurnOnVM’ } | Format-Table Name,StartAction,StopAction –autosize

Now do you have some Hyper-V servers with newer processors and some with older?   When migrating you can go forward in technology.  Going back is tricky unless you TELL the Virtual machine it can.

To identify those machines that can’t step back you need to check for the LimitCPUForMigration

$VMLIST | Where { $_.LimitCPUForMigration –eq $FALSE } | Format-table Name

Now if for any reason you’re unsure if your Virtual Machines have their Virtual Machine Additions, you can run a simply one liner again.

$VMLIST | format-table Name,HasVMAdditions

Now here’s a useful function to show you all the Computers in the Hyper-V environment that are still running with Legacy Network Adapters.

$VMLIST=GET-VM -VMMSERVER NAMEOFSCVMMSERVER
Foreach ($Machine in $AllVM )
    {
    $Adapterlist=$Machine.VirtualNetworkAdapters
    Foreach ($Adapter in $Adapterlist)
        {
        IF ($Adapter.VirtualNetworkAdapterType -ne 'Synthetic')
            {
            WRITE-HOST $Machine.Name,$Adapter.VirtualNetworkAdapterType,$Adapter.VMNetworkOptimizationsEnabled
            }
        }
    }

Why bother with this?  The more native your Hyper-V environment is, the fewer problems you can encounter.   Also when working with Systems Center Data Protection Manager and Hyper-V, you’ll want to make sure everything is as correct as possible to avoid that irritating “Backup Using Saved System State”,  a fallback backup method in DPM for Hyper-V Child Partitions.

All done with Powershell and a few minutes of typing.

Remember, the Power of Shell is in YOU
Sean
The Energized Tech

Yes you TOO could win a copy of Windows 7 Ultimate!  Just tell us your story! check out this amazing contest at Microsoft!   Hurry up and submit entries before January 31st!

 

Win a copy of Windows 7 Ultimate in our “Best Windows Story” Contest

We’re giving away a copy of Windows 7 Ultimate to the ten (10) best Windows stories from IT Professionals. Stories can be related to how Windows 7 saved your company money, solving your application compatibility issues, deployment, management of your installations, and virtually anything else. The more compelling your story, the better chance you have to win.

OFFICIAL RULES

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

GOVERNMENT EMPLOYEES: Microsoft is committed to complying with government gift and ethics rules and therefore government employees are not eligible.

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

COMMON TERMS USED IN THESE RULES:

These are the official rules that govern how the Microsoft Best Windows Story contest promotion will operate (“Contest”). In these rules, “we,” “our,” and “us” refer to Microsoft Corporation, the sponsor of this Contest.  “You” refers to an eligible Contest entrant.

CONTEST DESCRIPTION:

This is a skill-based Contest.

The object of this Contest is to recognize your story about how implementing Windows 7 has helped your business. Stories can describe how Windows 7 saved your company money, solved for application compatibility issues, helped with deployment or management of your installations, or virtually anything else. For purposes of this Contest, each “story” you submit will be called an entry. All eligible entries received will be judged using the criteria described below to determine the winners of the prizes described below.

WHAT ARE THE START AND END DATES?

This Contest starts at 12:01 a.m. Pacific Time (PT) on December 15, 2010 and ends at 11:59 p.m. PT on January 31, 2011 (“Entry Period”).

CAN I ENTER?

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

  • You are an IT Professional 18 years of age or older whose business has previously deployed Windows 7;  and
    • If you are 18 of age or older, but are considered a minor in your place of residence, you should ask your parent’s or legal guardian’s permission prior to submitting an entry into this Contest; and
  • You are NOT a resident of any of the following countries: Cuba, Iran, North Korea, Sudan, and Syria.
    • PLEASE NOTE: U.S. export regulations prohibit the export of goods and services to Cuba, Iran, North Korea, Sudan and Syria. Therefore residents of these countries / regions are not eligible to participate.
  • You are NOT an employee of Microsoft Corporation or an employee of a Microsoft subsidiary; and
  • You are NOT involved in any part of the administration and execution of this Contest; and
  • You are NOT an immediate family (parent, sibling, spouse, child) or household member of a Microsoft employee, an employee of a Microsoft subsidiary, or a person involved in any part of the administration and execution of this Contest.

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

WHAT CONSTITUTES AN ELIGIBLE ENTRY?

To be eligible for judging an entry must meet the following content / technical requirements:

  • Story must be no more than 2 double spaced pages with normal margins.
  • Story must be about how your business was helped by implementing Windows 7 or migrating to Windows 7 from Windows XP or Windows Vista.
  • Story must be written and submitted in English
  • Story must be submitted in .doc or .docx format to WinStory@microsoft.com no later than January 31, 2011 at midnight Pacific time.

In addition:

  • your entry must be your own original work; and
  • your entry cannot have been selected as a winner in any other contest; and
  • you must have obtained any and all consents, approvals or licenses required for you to submit your entry; and
  • your entry must not otherwise violate the rights of any other person or company by using their trademarks, music, logos, names or images without their express written consent.

Entries may NOT contain, as determined by us, in our sole and absolute discretion, any content that:

  • is sexually explicit, unnecessarily violent or derogatory of any ethnic, racial, gender, religious, professional or age group; profane or pornographic;
  • promotes alcohol, illegal drugs, tobacco, firearms/weapons (or the use of any of the foregoing) or a particular political agenda;
  • is obscene or offensive;
  • defames, misrepresents or contains disparaging remarks about other people or companies;
  • communicates messages or images inconsistent with the positive images and/or good will to which we wish to associate; and/or violates any law;

We reserve the right to reject any entry, in our sole and absolute discretion, that we determine does not meet the above criteria.

HOW WILL MY ENTRY BE POTENTIALLY USED?

Other than what is set forth below, we are not claiming any ownership rights to your entry.  However, by submitting your entry, you:

  • are granting us an irrevocable, royalty-free, worldwide right and license to: (i) use, review, assess, test and otherwise analyze your entry and all its content in connection with this Contest; and (ii) feature your entry and all content in connection with the marketing, sale, or promotion of this Contest (including but not limited to internal and external sales meetings, conference presentations, tradeshows, and screen shots of the Contest entry in press releases) in all media (now known or later developed)
  • agree to sign any necessary documentation that may be required for us and our designees to make use of the rights you granted above;
  • understand and acknowledge that the Promotion Parties may have developed or commissioned materials similar or identical to your submission and you waive any claims you may have resulting from any similarities to your entry; 
  • understand that we cannot control the incoming information you will disclose to our representatives in the course of entering, or what our representatives will remember about your entry. You also understand that we will not restrict work assignments of representatives who have had access to your entry.  By entering this Contest, you agree that use of information in our representatives’ unaided memories in the development or deployment of our products or services does not create liability for us under this agreement or copyright or trade secret law; 
  • understand that you will not receive any compensation or credit for use of your entry, other than what is described in these Official Rules

Please note that following the end of this Contest your entry may be posted on a website selected by us for viewing by visitors to that website.  We are not responsible for any unauthorized use of your entry by visitors to this website.  While we reserve these rights, we are not obligated to use your entry for any purpose, even if it has been selected as a winning entry.

If you do not want to grant us these rights to your entry, please do not enter this Contest.

HOW DO I ENTER?

To enter, send an email to WinStory@microsoft.com. Emails must include your story as an attachment and your contact information including first/last name, business, and email address.

By submitting your story, you will receive one (1) entry into the Contest.

We will only accept one (1) entry per person.

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

We will automatically disqualify:

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

WINNER DETERMINATION AND PRIZES

On or around February 28, 2011, a panel of judges will review all eligible entries received and select ten (10) winners of the Contest Prizes described below based upon judging criteria described below.

Judging Criteria

  • 25% - Compelling story about the value Windows 7 provides to your organization
  • 25% - Ability to overcome migration or deployment challenges
  • 25% - Solutions used to overcome challenges
  • 25% - Ability to clearly document your story

The decisions of the judges are final and binding.  If we do not receive a sufficient number of entries meeting the entry requirements, we may, at our discretion, select fewer winners than described above.

In the event of a tie between any eligible entries, an additional judge will break the tie based on the judging criteria described above.  The decisions of the judges are final and binding.  If we do not receive a sufficient number of entries meeting the entry requirements, we may, at our discretion, select fewer winners than the number of Contest Prizes described below.

Contest Prizes

Ten (10) Grand Prize. A Not for Resale English version of Microsoft Windows 7 Ultimate. Approximate Retail Value (ARV) $299.99.

The total Approximate Retail Value (ARV) of all prizes: $2999.90

We will only award one (1) prize per person.

If you are a potential winner, we will notify you by sending a message to the e-mail address, the phone number, or mailing address (if any) provided at time of entry within seven (7) days following completion of judging.  If the notification that we send is returned as undeliverable, or you are otherwise unreachable for any reason, we may award to a runner-up.

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

If you are confirmed as a winner of this Contest:

  • You may not exchange your prize for cash or any other merchandise or services.  However, if for any reason an advertised prize is unavailable, we reserve the right to substitute a prize of equal or greater value; and
  • You may not designate someone else as the winner.  If you are unable or unwilling to accept your prize, we may award it to a runner up; and
  • If you accept a prize, you will be solely responsible for all applicable taxes related to accepting the prize; and
  • If you are otherwise eligible for this Contest, but are considered a minor in your place of residence, we may award the prize to your parent/legal guardian on your behalf; and
  • Unless otherwise noted, all prizes are subject to their manufacturer’s warranty and / or terms and conditions. 

WHAT OTHER CONDITIONS AM I AGREEING TO BY ENTERING?

By entering this Contest you agree:

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

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

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

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

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

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

HOW CAN I FIND OUT WHO WON?

To request a winners list, please send an email to WinStory@microsoft.com and we will provide you with a list of winner who received a prize worth $25.00 or more. This list will be available until March 31, 2011.

WHO IS SPONSORING THIS CONTEST?

Microsoft Corporation
One Microsoft Way
Redmond, WA 98052

Here’s one for you.

A Server that is IN a Cluster with Some Hyper-V resources Clustered and some not.   The Clustered ones are backing up ok but the non Clustered ones?

“Meh…”

You may find a couple of things to look out for.   The Mysterious ID38 error when enumerating a NON Clustered Partition.   It could well be that the machines in question that will not backup are trying to do a “Backup Using Saved State”.

This type of backup actually does a quick save of the state of the machine and grabs that directly from physical drive.  

But in the Case of a Clustered server and DPM, if you encounter the mysterious ID 38 error (Can’t enumerate the resource) when trying to work with the drive that HAS the VHD files you will fail.

The trick is to identify the “WHY”

If you find the resources that are not backing up are using “Backup Using Saved State” you should refer to this Article on Technet to identify the “Why”

In my case, I had some test machines that had Dynamic drives which had to be switched back to “Basic”.

“But you can’t switch Dynamic back to Basic, that’s Madness!”

Well it DOES depend on the Dynamic Drive.   If your Dynamic drive is a simple partition that got accidentally created as Dynamic or part of a “Software Mirror”…. Yes you can.

Read this quick little article and download “TESTDISK” from www.cgsecurity.org

With a little time, you can undo that Dynamic Drive within the virtual machine and have a happier backup

powershell

A member of the Powershell Community passed away yesterday,  Andrew Tearle.   He was one of the original community Enthusiasts that helped drive Powershell and inspired people like me.

A great person has left us and to him and his family I write a Parody that really isn’t.   Based upon “Angie” by the Rolling Stones…

Dedicated to Andrew Tearle and family – All around Great guy and computer geek.  We’ll miss you.  To his wife and children, thank you for sharing him with us.

“Andy” (Sung to Angie by the Rolling Stones)

Andy, Andy, where'd you go, why'd you leave us here?
Andy, Andy, You've gone away, now we shed a tear.
With your passion in our souls, and your Powershelling goals
We can say you've never died
But Andy, Andy, we'll bow our heads for you we cried

Andy, you Inspired us. Now you've gone up to the Sky
Andy, We will miss you. INVOKE-PRAYER to you we sigh

All the dreams that you alight, All the eyes you made bright
Generations remember you
Andy, Andy, Someday soon we'll meet anew

Oh Andy, don't you cry, Tho it's time to say goodbye
We'll always GET-FRIEND and see you
Yeah Andy, Andy. We'll see your Cmdlets in the Sky

All that Thoughtware sent on through, and the person that was you
Lives forever in our eyes

Oh Andy, we'll still miss you
Everytime we see that screen of Blue

There won't be a day that we hear, tweets of wisdom in our ear
For you we raise a glass in cheer

Oh Andy, Andy, Forever more we bow our heads and cry
Andy, Andy, We’ll see you smiling from the sky…

powershell

Those of you who know me know from time to time I write Parody.   Unfortunately I ‘ll even try to sing it too.

Today I just wrote.  Sung to “Huey Lewis and the News” song “Workin’ for a Livin’”

“Scripting for a Living”

Users won't go away and their issues never die
The boss says get it now and I feel like I might cry
I get some vbScript and I get some Powershell
I Automate all my worries
I send em all to Hell

Scriptin' for a Livin' (Scriptin')
Scriptin' for a Livin' (Scriptin')
Scriptin' for a Livin', Livin' and Scriptin'
Automating what they're Givin' cuz I'm Scriptin' for a Livin'

They'll never seem me whine and they'll never see me moan
Cuz I sliced away the Cord from my Cisco Telephone
Wrapped inside my Functions
My Cmdlets and my Shell
I Script away it all
on my Latitude from Dell

Scriptin' for a Livin' (Scriptin')
Scriptin' for a Livin' (Scriptin')
Scriptin' for a Livin', Livin' and Scriptin'
Automating what they're Givin' cuz I'm Scriptin' for a Livin'

Ooh, Scriptin' for a Livin'
Ooh, Automatin' what they're givin'
Ooh, Scripting' for a Livin'
Ooh, Ooooooooo

Exchange, DPM, Files running free
Ten thousands users in my Active Directory
A few lines running here, A Cmdlet in the night
Ring a Bell, Powershell, it's done all before light

Scriptin' for a Livin' (Scriptin')
Scriptin' for a Livin' (Scriptin')
Scriptin' for a Livin', Livin' and Scriptin'
Automating what they're Givin' cuz I'm Scriptin' for a Livin'

Scriptin' for a Livin', Livin' and Scriptin'
Automating what they're Givin' cuz I'm Scriptin' for a Livin'
Scriptin' for a Livin', Livin' and Scriptin'

powershell

So you’ve decided you have to work your SQL Database with Powershell.   Honestly I never thought of doing this.  The SQL Management  Console seems to meet all my needs.

But perhaps you’ve got a legacy application that creates user ID’s and accounts in SQL.  Or your Development team wants to hand you off a minor database task but they only have SQL queries for the code?  Maybe you’re just bored?

We’ve all got our reasons to get things done.   With SQL Server 2008 we DO have the option to use Powershell, well sort of.

Somebody on the SQL team didn’t listen to somebody else and they made this “MiniShell” (which I’m not even going to get into).  What this GENERALLY means is unless you launch Powershell from the SQL Management Console or the direct executable, you’re not going to be using the SQL Cmdlets.

Granted, there are only three but damn they’re powerful and useful.

So how do we add SQL to a regular Powershell session?  Well provided you have the SQL Management Studio on a machine with Powershell you execute these two lines first

add-pssnapin SqlServerCmdletSnapin100
add-pssnapin SqlServerProviderSnapin100

Which will give you three new Cmdlets

DECODE-SQLNAME

ENCODE-SQLNAME

INVOKE-SQLCMD

 

INVOKE-SQLCMD is my favorite since it allows me to execute an SQL Query (Translates to the ability to manipulate, Create an SQL Database) as if I was in the Management Studio.   Where this is USEFUL to the Powershell Administrator is that is returns OBJECTS just like normal in Powershell.

More importantly, I can now interface directly with the SQL instance on terms I am comfortable with and dig for stuff like “How Fragmented is this index?”

Let’s kick this up a notch.  If the SQL server is running Powershell 2.0, you could enable remoting and tie all of this into your normal Administration in Powershell or just simply MANAGE the SQL server without any Management tools on your computer at all (Other than Powershell)

So why do this? 

If you’re doing JUST SQL I personally would stick with the SQL Management Studio.  It’s perfect for that.  Where Powershell comes into play could be some maintenance scenarios or even User creation situations.  It could be (as I was muttering before) a situation where Development has Code that runs in a Web page that performs a task.   Their only code is an SQL query.    You as the Administrator can leverage that SAME code without change on your terms.

You might even be able to help out your Developer friends.

How YOU choose to use it is up to you.

The Power of Shell is in YOU

Sean
The Energized Tech

One word

WATCH the FUTURE is about to begin TODAY!

The Challenge

A single Windows XP Computer full of data and goodies, you have no backup resources available.  Your back is against the wall and the client says “I need this machine upgraded to Windows 7 now and retain all my files and settings…”

You have 60 minutes…

(Cue Mission:Impossible music)

Gather your friends, gather your neighbours, your colleagues and anybody who thinks “This is IMPOSSIBLE!” as the myth is Busted!   Meet up at January 11th only at IT PRO TORONTO (www.itprotoronto.ca) where we will FINALLY toss that myth out the Window.

How to convert a Windows XP machine to a Windows 7 Machine in 60 Minutes or Less

In this fun and interactive session you will find out about different ways to convert a 32-bit Windows XP-based machine to Windows 7 (either 32-bit or 64-bit), keeping user data and settings in place, while installing required applications, like Office 2010 and your own line-of-business programs, in the process.

You will learn about different technologies to do this daunting task. Can it be done in 60 minutes? 

Come and find out in this session covering this important issue for many companies today.

IT Pro Toronto
155 College Street,
Toronto M5T 3M7

 

Map picture

powershell

Telling somebody to “Use Powershell” is all fine and dandy.    Telling me it’s easy is wonderful too…

But… uh… where do I start?

As a Network Administrator there are tasks we perform on a regular basis.   The fine details overall change for each one of us, but I believe personally there are just some things we’re ALL asked to do.

Now I’m going to be referring to a set of tools from Quest software called the ActiveRoles Management Shell for Active Directory when working with Pre Server 2008R2 environments and the newer built in ones from Microsoft.  Which should you use?  The choice is obvious. 

If you have at least one Server 2008R2 controller in your Active Directory, I highly recommend the newer ones if you have the option.   All of the management is done through ports 80 / 443 since they leverage WS-Man (Web Services Management).  Failing that, the free Cmdlets from Quest will allow you to manage even a Server 2000 Domain from your workstation.

GET-HELP Obiwan

The most powerful Cmdlet in Windows Powershell (In my lowly opinion) is GET-HELP

Within Windows Powershell if you need Help on a Particular Cmdlet you need only key in

GET-HELP Cmdlet; # For basic help

You’ll also have three additional options to work with.

GET-HELP Cmdlet –detailed; # Detailed instructions about the Cmdlet

GET-HELP Cmdlet –examples; # Sample code of how to use the Cmdlet

GET-HELP Cmdlet –full; # the WHOLE uninhibited manual for the Cmdlet

GET-HELP Cmdlet –online; # Brings you DIRECTLY to the Technet site with the current docs and COMMUNITY support

Example

GET-HELP NEW-ADUSER –examples –online

Trying to learn “about” something in Powershell?  Here’s a built in list of manuals that go into programming, looping and some beefier (and sometimes not so beefy) goodies.

GET-HELP about_

In order to get a complete list of topics.   I highly recommend using the Windows Powershell ISE and key in F1 for help.  For new Windows Powershell users, it may be an easier way to find what you need… and print it Smile

What’s Available here?

Knowing what is available to your in a particular Windows Powershell session is key to knowing how to play and extend it.

GET-MODULE –listavailable

Will show you what modules are presently installed on your PC.   You can easily add ANY of them in using

IMPORT-MODULE ‘ModuleName’

GET-COMMAND

Will display all the available CmdLets, Functions, Aliases you can use.   But often we really need a more “controlled” list.  With that you can filter the list to more manageable chunks.   We can break it down to a list of Cmdlet, Function or Alias with this single line

GET-COMMAND –commandtype Cmdlet

GET-COMMAND –commandtype Function

GET-COMMAND –commandtype Alias

You can even break that list down by Module or Snapin

GET-COMMAND –commandtype Cmdlet –module ActiveDirectory

Or break the list down FURTHER showing only a particular type of Cmdlet

GET-COMMAND –commandtype Cmdlet –module ActiveDirectory GET*

or just find Cmdlets that match a particular word

GET-COMMAND –commandtype Cmdlet –module ActiveDirectory *USER*

Knowing what is available to you is sometimes half the trick.  NOW for the fun stuff Smile

Disabling Users

The head of HR comes bursting in your door screaming to quickly disable the VP in Division X because an Audit has tunrned up some nasty details about their new “Fund Management Scheme”.   No panic for you when you simply execute a

# Quest
DISABLE-QADUSER ‘Mister X’

# Microsoft
DISABLE-ADACCOUNT –identity ‘Mister X’

Or perhaps it’s that entire division at Contoso that needs to be disabled?

# Quest
GET-QADUSER –Searchroot ‘Contoso.local/Divisions/X/Users’ | DISABLE-QADUSER

# Microsoft
GET-ADUSER –filter ‘*’ –SearchBase ‘OU=Users,OU=X,OU=Divisions,DC=Contoso,DC=local’ | DISABLE-ADACCOUNT

Checking Group Membership

You’ve just taken over as the Administrator for a company and need to know who has Domain Admin access?  or any other group?

# Quest
GET-QADGROUPMEMBER ‘Domain Admins’

# Microsoft
GET-ADGROUPMEMBER ‘Domain Admins’

But you say, “Hey, I have auditors that need that information in their hands now!  Well then!  Just export that into a CSV (Comma Separated Value file)

# Quest
GET-QADGROUPMEMBER ‘Domain Admins’ | Export-CSV C:\Foldername\DomainAdmins.csv

# Microsoft
GET-ADGROUPMEMBER ‘Domain Admins’ | Export-CSV C:\Foldername\DomainAdmins.csv

Unlocking Users

You say your biggest challenge is the 5% of the people who tie up support with 98% of the lockouts and need to be resolved now? Ha! Piece of cake

# Quest
UNLOCK-QADUSER ‘John Smith’

# Microsoft
UNLOCK-ADACCOUNT –identity ‘John Smith’

But wait.  Did a whole division of users from Division X have a really big party at lunch and NEED to all be unlocked NOW?  Shame on them but, hey! No challenge!

# Quest
GET-QADUSER –Searchroot ‘Contoso.local/Divisions/X/Users’ | UNLOCK-QADUSER

# Microsoft
GET-ADUSER –filter ‘*’ –SearchBase ‘OU=Users,OU=X,OU=Divisions,DC=Contoso,DC=local’ | UNLOCK-ADACCOUNT

Reset Passwords

Fred Flintstone from accounting has locked himself out! It’s the end of his world (and your day) if he can’t log into his computer.

# Quest

$NEWPassword=READ-HOST ‘New Password:’ 
GET-QADUSER ‘Fred Flintstone’ | SET-QADUSER –USERPASSWORD $NEWPassword –Usermustchangepassword $TRUE

# Microsoft
$NEWPassword=READ-HOST ‘New Password:’  -assecurestring
SET-ADAccountPassword –identity ‘Fred Flintstone’ –Reset –NewPassword $NEWPassword

Quickly Pull BIOS Information

Yes, I’m certain you have that new $50,000 inventory system that does everything…. What?  Everybody doesn’t?

Built into every Windows Powershell console is the ability to run WMI Queries EASILY.   Here’s a quick take away for you right now.  Need to know some BIOS details of a remote PC?

GET-WMIOBJECT win32_bios –computername ‘nameofcomputer’

Now how about if that computer is a DELL system?

(GET-WMIOBJECT win32_bios –computername ‘nameofcomputer’).SerialNumber

But did you need to get that information for a series of computers in your Active Directory?  Enter the Power of Shell to query All the service Tags in mysterious Division X

# Quest
GET-QADCOMPUTER –searchroot ‘Contoso.local/Division/X/Computers’ | FOREACH (GET-WMI-OBJECT win32_bios –computername $_.Name ).SerialNumber

# Microsoft
GET-ADCOMPUTER –filter ‘*’ –searchbase ‘OU=Computers,OU=X,OU=Division,DC=Contoso,DC=Local’ | FOREACH (GET-WMI-OBJECT win32_bios –computername $_.Name ).SerialNumber 

Check status of Drive Space Remotely

Here’s one I would have loved to have had in the field.   A Free utility to check the free space of a drive in Windows.  Thanks to Powershell and WMI, another free feature

GET-WMIOBJECT Win32_logicalDisk –computername ‘nameofcomputer’| Where { $_.DriveType -eq '3' -and $_.Size -ne $NULL } | Select-Object Size,Freespace,DeviceID

Easily Search File Structures

Windows Powershell is not only great for managing users, but Files as well.    Been trying to quickly find all those silly “Lock” and Temp files in a file System?  Would you like a safe way to TRY removing them without damage? Windows Powershell has the GREATEST option of all.  Any “Destructive” Cmdlet can run the parameter “-WHATIF”.  “WHATIF” I do this “WHAT” will it do?  

With that option it’s a One line in Windows Powershell!

GET-CHILDITEM H:\ –recurse –include *.tmp,~*.* | REMOVE-ITEM -whatif

and if you’d like to automatically crush the garbage?  Now that you’re certain you did it right?

GET-CHILDITEM H:\ –recurse –include *.tmp ~*.* | REMOVE-ITEM

What’s installed on my computer?

Windows Powershell can directly read the Registry as easily as a Filesystem.   There are ways to even access remote registries (Provided you have the needed permissions of course) But with ONE LINE I can have Windows Powershell show me what’s installed on a computer

get-childitem Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall | foreach {(get-itemproperty -Path $_.PsPath -Name DisplayName -erroraction SilentlyContinue).DisplayName }

But who needs to key THAT in everytime?   In Windows Powershell I can define a NEW Cmdlet all my own!

function global:GET-APPLICATION {

get-childitem Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall | foreach {(get-itemproperty -Path $_.PsPath -Name DisplayName -erroraction SilentlyContinue).DisplayName }

}

And now that’s a new Cmdlet I can run

GET-APPLICATION

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

Now here’s the fun part. 

I have only TOUCHED on the TEENIEST bit of what’s available to do in Powershell.  These are lines I PERSONALLY find useful.  The true Power of Windows Powershell is always defined by YOU.  

There are Modules and Cmdlets defined for just about every key Microsoft Windows Server product from SQL Server, Exchange to Office 365 and Azure.   Windows Powershell is as well probably THE MOST COMMUNITY DRIVEN technology from Microsoft.  

This means that the COMMUNITY is helping Microsoft to tune and improve the product to better meet it’s customers’ needs as we are the best representation of what the Customer NEEDS and WANTS.   So feel free to take a drive on the “Highway to Powershell”.  Take these lines and make them useful for yourself in however they can.   Also take note of some amazing resources for Windows Powershell especially the BEST one of all, The Technet Script Center home of “Hey Scripting Guy” , Dr. Scripto, the Technet Script Repository and the Technet Scripting Forums !

Best of all?  Just search online with “Powershell” and what you’re trying to achieve!  Check out other amazing sites like the Powerscripting Podcast and PoshCode.  Tweet your questions with #powershell as a hashtag.

Most importantly, dive in and FEEL the Power of Shell with Powershell.   It’s all defined by YOU.

Sean
The Energized Tech