May 2009 Archives

How to find what you CAN look for – a few tips

One of the stumbling blocks I personally ran into in Powershell was a actually a simple one to solve but I thought I might share it anyhow. 

How do I go about finding what I can pull and use?

You already know about the GET-MEMBER commandlet.  That will show you all the available properties of the Objects.

But sometimes “GET-MEMBER” isn’t enough.  I mean in all fairness it’s gets you what you need but I found (Very often, especially with Exchange and Active Directory) it’s a matter of seeing what particular field you can pull up and if the CONTENT of that field meets your needs.   And this trick is good with pretty much every Powershell command-let I’ve run across.

It’s the one that opened up my eyes.

With the Quest Active Roles Commandlets loaded fire up the following command (This is a free Powershell Addon from Quest Software that allows you to effectively work with Active Directory from Powershell)

GET-QADUSER

Now that’s going to dump a list of ALL Active Directory users.  But we all know, Active Directory has a LOT more than just Usernames.     And to find out WHAT was available, Just pipe that into a VERY powerful and oh so handy commandlet “EXPORT-CSV”

EXPORT-CSV is pretty much what it says it is.  It takes the Information you’re giving it (even stuff you can’t visibly see on the screen, like OTHER objects) and EXPORT’s that to a CSV (Comma Separated Value) file.   And the way to use it is easy too.  EXPORT-CSV NameOfFile.CSV (And if you’re wondering, yes there is also an IMPORT-CSV to Read back and send in.   But that’s another time.

Now I have Excel for viewing this but any spreadsheet application out there will do fine to open up a CSV file.

And of course give it a location to dump it to.  I like to have a little temporary folder off the root for Powershell.  Mostly because I hate typing and I don’t want to wreck the NTFS permissions on the Root of C just to dump a simple CSV file.    So in this case I have a folder called C:\ENERGIZED to dump my Powershell info into, or to test scripts or whatever.

GET-QADUSER | EXPORT-CSV C:\ENERGIZED\LISTOFAD.CSV

Once you open up this file you’ll see a series of columns with headers.  Those columns are ALL the available objects being piped out.    So if you remember a previous post I had about pulling a list of users from the data they were created, here’s where I got the information.  I went into Active Directory and looked to see (Under the Advanced View) if certain information was available.   Then I compared it with this output list (and checked the headers)

Now there is a LITTLE bit of guessing but not a lot.  You can usually compare the header with the output under it to see if it meets your needs.

The other thing you can do with making GET-MEMBER more useful is to change it’s output.   One of the things I found maddening was running a “GET-MEMBER” on the output only to find the lines cut off.  This mostly happens when it lists a METHOD.

But the information is always there.

So another trick that’s good and handy is running your output through a FORMAT-LIST Commandlet. 

So running

GET-QADUSER | GET-MEMBER | FORMAT-LIST

Will show me that view in a lot greater detail.   You have to scroll up and down the Powershell window but it’s all there. 

But again.  What you’ll find in Powershell is there is a lot you can work with.  Sometimes it’s just a matter finding what you can get.

Sean
The Energized Tech
”……It’s so Easy and It’s Free, Download it now it’ll take no time….” "(Highway to Powershell)

One on the really nice things, and the greatest features (and In My Humble Opinion the BEST reason to by Windows 7 and Server 2008R2) is the fact that Powershell “Newest Version as yet unnamed” is PART of the operating system.

No download needed.  No “Add a role”.

It’s there. 

And wouldn’t you know it?  A nice little editor for those of us who are not quite happy with the debugging features of “NOTEPAD”.

But here’s an indication of just HOW much Powershell is a part of the Administrator and the Users’ lives now.

I did a search for a sample PS1 file in Windows 7.  Didn’t know where to look, didn’t care, just a random search.

I do these kinds of things you know. 

I expected to find a file or two.

Well what a surprise I received!  Primarily diagnostics but there are over 400 (FOUR HUNDRED) PS1 (Powershell Script) files NATIVE to Windows 7.  I haven’t even looked at my copy of Server 2008R2 yet!

These are all functions that Windows calls up regularly

image

Take a look at the RS_Themes.PS1 file

 

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

# Copyright © 2008, Microsoft Corporation. All rights reserved.

# You may use this code and information and create derivative works of it,
# provided that the following conditions are met:
# 1. This code and information and any derivative works may only be used for
# troubleshooting a) Windows and b) products for Windows, in either case using
# the Windows Troubleshooting Platform
# 2. Any copies of this code and information
# and any derivative works must retain the above copyright notice, this list of
# conditions and the following disclaimer.
# 3. THIS CODE AND INFORMATION IS PROVIDED ``AS IS'' WITHOUT WARRANTY OF ANY KIND,
# WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. IF THIS CODE AND
# INFORMATION IS USED OR MODIFIED, THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION
# WITH THE USE OF THIS CODE AND INFORMATION REMAINS WITH THE USER.

. .\CL_Utility.ps1

Import-LocalizedData -BindingVariable localizationString -FileName CL_LocalizationData

Write-DiagProgress -activity $localizationString.themesResolve_progress

# check the Uxsms service startup tpe
$startupType = (Get-WmiObject -query "select * from win32_baseService where Name='Themes'").StartMode

#resolver
if($startupType -ne "auto" -and $startupType -ne $null)
{
    (Get-WmiObject -query "select * from win32_baseService where Name='Themes'").changeStartMode("automatic") > $null
}

Restart-Service Themes
WaitFor-ServiceStatus "Themes" ([ServiceProcess.ServiceControllerStatus]::Running)

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

 

Without knowing the full details, it appears this one script has something to do with  The Aero themes (either turning them on or off) But ignoring this one script it is ABSOLUTELY AMAZING to see what a level Powershell plays within the operating system.   It’s no longer an add-in.   It is hard coded and embedded with the system.   Which means Administration software uses it.

Which means your life as an Administrator is about to get easier.   As More and more of Windows is based upon Powershell scripts (including the Server and various applications) it will be far easier to control via Group Policy and Powershell scriptings how things need to run.


Ohhhhhhhh I can’t wait to get this in action at work! 


Sean
The Energized Tech

Ok Here's an easy one I stumbled across in Powershell that's SO incredibly useful.
 
First off, get yourself a copy of the Active Roles Management Shell from Quest Software.  It's free and makes working in Active Directory a complete breeze with Powershell.
 
Now I had what could have been a nightmare task (doesn't seem at first until you think about it)
 
Pull up a list of users that I had created in the past thirty days.
 
"Well that should be easy... " I thought to myself.   The information *IS* in ActiveDirectory.  But how?
 
Well Powershell and Active Roles Management Shell from Quest Software, it's dead simple.  
 
In the Active Roles Shell all you have to do is
 
GET-QADUSERS -searchroot "ou=xxx,dc=yyy,dc=zzz" -enabled | where { $_.whencreated -gt "mm/dd/yyyy }
 
Where the "-enabled" shows all ENABLED User accounts and "ou=xxx,dc=yyy,dc=zzz" is your Search scope to isolate it to a single OU in Active Directory
 
So if my domain was "energized.local" and I was digging through the "technicians" OU from the root of Active Directory I would use
 
"OU=TECHNICIANS,DC=ENERGIZED,DC=LOCAL"
 
Now this was a "quick and dirty" solution where I ran in my head that 30days was this date and just figured out what the month day and year to plug in was.
 
But you can get fancy.   And make it into a function or just a simple script for occasional use.
 
In Powershell there is a GET-DATE function which gets, ( well yes of course, you guessed it)  The Date.
 
So without much difficulty you can run create this little script.
 
$TODAYDATE=GET-DATE
 
GET-QADUSERS -searchroot "ou=xxx,dc=yyy,dc=zzz" -enabled | where { $.whencreated.AddDays(30) -gt $TODAYDATE }
 
Now save that as "LIST30DayUsers.PS1" and you've got a handy script for pulling up new Users that are recently created.  Now If you want, pull out the -searchroot "ou=xxx,dc=yyy,dc=zzz" from the line and it will search the Entire Active Directory you're defaulting to.  Pull out "-enabled" and it will show ALL accounts created in the structure (including disabled accounts)
 
And if you're wondering?  The Active Roles Management Shell DOES work with the newer Powershell (as of this writing) in the RC1 of Server 2008R2 and RC1 of Windows 7.   I did this on a Server 2008R2 setup.
 
Enjoy.   I am.  I'm sitting at my desk now humming "Highway to Powershell" ;)
 
Sean
The Energized Tech
 
 
 
 
 
 
 

Hey Don’t forget!  There’s still time to register!   Here at Sheridan College in Oakville Ontario!

Don’t miss this chance.

KAI AXFORD World renowned Security Expert

https://www.clicktoattend.com/invitation.aspx?code=138016

Tuesday night, May 26th 2009 at 6pm!  Don’t miss this opportunity!

If you’re going by transit, get off at the Oakville Go Station and it’s a quick cab ride up to the college!

This is a rare opportunity!  Seize it and learn from one of the best there is.

DO IT!  Expand your mind!

So last time we were introduced to piping.  A more efficient way to port results to different programs.

Now in Powershell we have to remember the information we’re dealing with is OBJECTS.  It’s important to remember that what you see on the screen, although VISUALLY text, may not be.

Think of those Objects much like a spreadsheet.   It’s a list. It’s a SPECIAL kind of list, but on a very basic level; it’s a list.

We may just want to GET the ITEMS from the list and just see them.  (GET-CHILDITEM) or we may want to examine them a little deeper.

This time, we may want to look at the Objects individually.  Perhaps examine them a bit more deeply.   The simplest way is with the “FOREACH-OBJECT” statement

With the FOREACH-OBJECT statement we have a special builtin variable.   You’ll notice variables in Powershell (Items containing information) represented by a “$”.  In the case of the Foreach-Object statement there is a variable called “$_” which represents whatever OBJECT we’re presently looking at.

So here’s a simple example with our “GET-CHILDITEM”

GET-CHILDITEM |  FOREACH-OBJECT { $_ }

image

Which really isn’t very impressive right now.  All we did was get a list of objects and say “FOREACH-OBJECT” “Echo” $_ (That Object)

But here is where the Powershell starts to open up

That SAME line with a little change can access SPECIFIC information from those objects

GET-CHILDITEM | FOREACH-OBJECT { $_.Name, $_LastAccessTime }

image

What that is doing is going sequentially though the list of objects and pulling out SPECIFICALLY the Name Property and LastAccessTime Property from the output (Remember that information provided with the GET-MEMBER ?)

You can even assign the results of that to a Variable for later use and manipulate it however you want

But here’s a better example of the FOREACH-OBJECT in Action.  To see how I can manipulate the results and maybe do something with it later afterwards.

Let’s take a look at this line

GET-CHILDITEM | FOREACH-OBJECT { $_.LastWriteTime }

image

So that just pulled up a list and showed me all the time those Objects were last written to

Then this system we’re going to apply a METHOD to those Objects (As shown from running a GET-CHILDITEM | FOREACH-OBJECT { $_.LastAccessTime } | GET-MEMBER )

image

We’re going to use the “AddHours()” Method on the “LastWriteTime” Property

and

GET-CHILDITEM | FOREACH-OBJECT { $_.LastWriteTime.AddHours(96) }

image

What did I just do? 

I pulled up a list of OBJECTS with GET-CHILDITEM.  I ran the results through a FOREACH-OBJECT and ran a Method against “EACH” object given (supplied by our friend GET-MEMBER which said which Members and Properties we could use) and said in this case “Add 96 Hours to value of that Date Object”.   This DOESN’T write back to the original item but it IS a way to manipulate information.

Still in just one line.  We’re working with the Structure of an ENTIRE file system in One line and dumping a list to the console with EVERY date Modified to work with.

And what we’ll do with that information, we’ll touch on next time.

Sean
The Energized Tech

Now we’ve had a chance to look at Powershell and get a quick glance to see some basics.   There is a lot of information provided by GET-MEMBER as to what you can do.

But let’s take a very quick look into what we can do with that information.

In the previous article you may have noticed the use of the “|” character.   That’s referred to as “piping”

When we got the output from GET-CHILDITEM, it displayed a list of information on the screen.   Mind you it didn’t display ALL the information it got, just the “Important bits” for you and me.   The key details.

When we did a

GET-CHILDITEM | GET-MEMBER

What we actually did there was take the list of objects retrieved and dump them DIRECTLY to the GET-MEMBER command.   It may not have used all the available Properties of those objects, just the ones it needed.

It would have been the same as running a

GET-CHILDITEM

and getting a small Directory list like

C:\USERS
C:\Windows
DOG.TXT
CAT.BIN
BIRD.EXE

and THEN typing in

GET-MEMBER C:\USERS
GET-MEMBER C:\Windows
GET-MEMBER C:\DOG.TXT
GET-MEMBER C:\CAT.BIN
GET-MEMBER C:\BIRD.EXE

Piping is just a more efficient way of doing things

And Piping can be done more than once on a line. I can run a GET-CHILDITEM, pipe the output to GET-MEMBER and then take the results of the GET-MEMBER and pipe that output into an EXPORT-CSV

And forever and ever until you’ve got the results you need.   A Pipe is a lot like a REAL pipe connecting different systems together ending up at a tap.  In our case the systems are Powershell Commandlets like GET-CHILDITEM, GET-MEMBER and EXPORT-CSV and the tap at the sink is the resulting output.

Next time we’ll take a look at a way to work with those objects on a more one to one level.

Sean
The Energized Tech

Sponsored by IT Pro Toronto.
 
 
**Special Event**

Seminar with World Renowned Security Expert Kai Axford

Sheridan College, Oakville, ON

Tuesday May 26th 2009
Welcome time 6:00PM Event 6:30PM-9:00PM

Click here for more details and to Register!.
Location:
Sheridan College - Trafalgar Road Campus
J Wing - Sheldon Levy Centre - RM J102
1430 Trafalgar Road (Ceremonial Drive, park in the left lot)
Oakville, ON, CA
L6H 2L1
I had to reinstall my workstation at work.  I didn't WANT to... but had to.  I had to.  I REALLY had to.
 
My boss, who is the NICEST GUY ON THE PLANET is probably reading this post right now. 
 
"I can't believe he broke Windows 7 Beta... I just can't believe it.... Only Kearney could... I'm 'calling him out!'"
 
Something like that.  In all fairness to Microsoft and my Boss (REALLY REALLY SUPER SUPER NICE GUY!!!) I *WAS* playing and loading it up and unloading things and well... *YES*
 
I broke it.
 
So limped for the day, and after the days end I had to reinstall.  My own dumb fault too.   There's only some much poking, prodding, hacking MSI installs ANY thing can take.
 
and I had a choice (Being trial software anyhow).  Windows 7 x64 RC1 or Server 2008 R2 RC1.
 
I wanted to see if this machine was Hyper-V capable (turned out it was Virtualization capable but no Hypervisor on the CPU) and I really wanted to have the ability to run ANY server administration built in. 
 
I can get RSAT (Remote Server Administration Tools) for Windows 7.  That's a non-issue.  I can run all my Administration under Windows 7. 
 
But somehow having a "Server O/S" as a Workstation was just TOO Geeky to pass up.   And maybe there would be a lesser chance of "Kearney Breaking it" ;)
 
So it installed, and with a few minor tweaks (Disabled the IE Enhanced Security, installed Java and My Office Apps) and putting in Vista x64 drivers.  Added in a whole WAAZZOOOO of Remote Server tools.  Yes it was painless and smooth.
 
But it felt... well.... lacking.  Something was wrong, something was missing.... something....
 
"MY WINDOWS7 INTERFACE!"
 
Yes I had been spoiled.   Months of Windows 7 Beta and you REALLY miss the new taskbar and features.  But all was not lost.   There was a similiar article for Server 2008 to enable Aero in Vista .  So I decided to see just what it would do in Server 2008 R2.
 
Follow all those wonderful steps (actually not THAT many) and you'll be looking at the Windows Search, Windows 7, Aero goodness in NO TIME at all.
 
And you get a really Kick butt Administration tool to boot (and a little *Geek Cred*)
 
And hopefully a Boss who won't be ready to "Call you out" because you managed to tie up most of the morning with reboots.
 
Because my Boss (like most boss's) is under a lot of pressure.   He needs a few buttons pushed as possible.
 
Oh and did I say it yet?
 
SERVER 2008 R2 RC1 and WINDOWS 7 RC1 ABSOLUTELY ROCK!
 
Sean
The Energized Tech
 

Let me start off by saying this.   I think Adobe makes an excellent product.  Adobe Acrobat is wonderful and powerful.

And their own personal reader takes a lot to desire.

One of the problems I have encountered over the years CONSISTENTLY is their own reader for viewing PDF documents tends to NEED to be upgraded and then tends to cause bigger problems as a result.  Whether it be the ActiveX component does not remove properly, or it causes the Reader to crash when printing PDF files that are a slightly newer version.

Or the fact that it’s a 45 meg download to view the silly files.

There are better solutions.   Adobe did good.  Other’s are doing better.

Take FOXIT.  They came up with a small footprint application that can view PDF files without taking out the system.  It’s simple effective and works.

http://www.foxitsoftware.com/pdf/reader/download.php

And not laced with Spyware or Malware is a nice bonus.   

It seems to have all the functionality of the Standard Adobe Reader without any of the mess.    I can zoom, print, select and copy text and even search as I could with the Adobe Reader.

I just don’t need to keep watching my system crash every time I go to print or browse a PDF file on a web site.

They even have an inexpensive application (About $30 US) for creating PDF Files or a Full Blown PDF Editor (About $99 US).

I don’t think Adobe Acrobat is a bad application.   But I do think they need to look into it’s incompatibility issues.  And perhaps the cost. 

But just food for thought, alternatives are good to have.

Sean
The Energized Tech

So we continue into trying to under Powershell.   This series of articles is not into “Deep Dive” so much as it is to help Administrators and ITPros get a quicker grasp and leap past some of the initial learning curves I had with Powershell

So this time we discover the “GET-MEMBER” command let.

I like to think of GET-MEMBER as my portable phonebook in Powershell.  It shows me everything about those objects in Powershell that a GET-CHILDITEM (or any other command producing output, which is pretty much all of them) does.

So let’s run a GET-MEMEBER on the results of GET-CHILDITEM it will show you everything contained in that list of Objects.  Not the values as such, but the types of information you can get.

image

As you can see there is a LOT of information just on the Filesystem OBJECTS alone.   But it’s not confusing.   It you look you will see it’s broken into two sections.  “System.IO.DirectoryInfo” and “System.IO.FileInfo”.

Similiarly if you run the GET-MEMBER on other Powershell results, it will show you information within them as well.

SET-LOCATION REGISTRY::

GET-CHILDITEM | GET-MEMBER

Will give these results, which show you what information you can manipulate in this context

image

GET-MEMBER is useful on more than just “GET-CHILDITEM”.  I find if I’m not sure types of information are available in the output to manipulate, you run GET-MEMBER.  GET-MEMBER is incredibly powerful because it not only reveals information we want to see, it also reveals “METHODS” which are code or functions we can use to manipulate that data in sometimes more useful ways (Like comparing dates, or parsing the information revealed to us)

We’ll get a little bit more into what we can do with some of the METHODS next time.  

Rock on with Powershell

Sean
The Energized Tech

Ok back to another posting I felt needed saying.   This one might even need a little video later.

One of the things that had me stumped in Powershell initially was the “Where do I go from here?” after you did a GET-CHILDITEM

Well after that, there is a LOT you can do.  But 'I’m more interested in the pieces.

So in Powershell it pulls down objects.  It’s not really pulling down “Text” as we ITPros think of it.   But let’s put it simpler.   It pulls down a big list.   We don’t really need to know too much about the list.  But it’s a list.  “Objects” or “Things”

There are much better articles to describe the whole theory between objects and C and stuff that’s way headier, so we’ll skip out of that.    By the way, if somebody DOES have a good “Objects for Dummies” link, I’ll edit this article later to reference it

So I run a “GET-CHILDITEM” which by itself pulls up a list of Objects in whatever context we’re presently defaulted to.

Be default in Powershell, you’re in the Context of your Drive structure.  

C:\

Or in my case

C:\Users\TheEnergizedTech\

Running a GET-CHILDITEM shows me this list of Objects (But to us it is a directory structure)

image

Now one of the things I found confusing is I kept thinking “What does GET-CHILDITEM” have to do with the directory?

The answer is NOTHING.  It is just asking for a list of OBJECTS in the current context.   If I were to change the location to the registry (because Powershell) can just as easily navigate the registry Objects it would be the same command.   The output will look different because it’s not pulling down a directory.  Again, it’s just pulling a list of OBJECTS.   Here’s an example of changing to the Registry to view it’s context.

I use SET-LOCATION to change my context in Powershell, to change what part of the system I am presently working in.  So I want to look in the Registry

SET-LOCATION REGISTRY::

allows me to change my view to that

And running GET-CHILDITEM on that context will give you a more familiar list

image

Now we change it back with SET-LOCATION C:\

So what can you DO with it?

How do I find the information these objects are providing and what to do with them?

Well that’s for our next session when we discover the “GET-MEMBER” command and the enormous box of Digital toys it reveals!

Sean
The Energized Tech

Today I had to search for something in a Text file.

In Powershell theres a simple command

GET-CONTENT

Which lets me simply enough, GET CONTENT from a text file (or files).   I’m going to deal with ONE file right now.  Let’s pick on the WINDOWSUPDATE.LOG

It’s big beefy and full of stuff.

Type typing in

GET-CONTENT C:\WINDOWS\WINDOWSUPDATE.LOG

Dumps a pile of stuff on the screen.

“Yeah impressive!” (I hear everybody in the back) “TYPE Command did that for years”

True.   But here’s the difference.

I can store the output of ANY Powershell command in a variable of my choosing without any thought

So.

$RESULT=GET-CONTENT C:\WINDOWS\WINDOWSUPDATE.LOG

Now here’s where TYPE command loses it’s luster

I can put that in this SCRIPT, and have it match lines that meet content in that logfile and save it as

“FINDAGENT.PS1” (Text format)

and run it anytime I want

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

# FINDAGENT.PS1
# This script will get the content of the WindowsUpdate.LOG file and search it for lines with the word “Agent” anywhere in the file

$RESULT=GET-CONTENT C:\WINDOWS\WINDOWSUPDATE.LOG

FOREACH ($LINE in $RESULT)
          {
          # Compare results in that “Object” that are “like” anything contained within the “Quotes”.  The “*” before and after indicate it could be anywhere
          if ($line.tostring() –like “*Agent* )
               {
               # write that output to the Console
               write-host ( $line )
               }
          }

# No more script.   All done

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

That will output EVERY line that has the word “Agent” in it when you run the FINDAGENT.PS1 file in a Powershell session.

Now here’s where NOTEPAD and TYPE fall down and cry.   I can take that SAME script and with minimal modification make it a FUNCTION I can call up all the time.   So it took a little longer to write, but I can now have a reusable feature in the system.

And again.  Not difficult

So we take the script and with the following changes

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

FUNCTION FILESEARCH ($FILENAME, $CONTENT)

{

# This script will get the content of the file passed through $FILENAME and search it for lines with the content passed by the user in $CONTENT

$RESULT=GET-CONTENT $FILENAME

FOREACH ($LINE in $RESULT)
          {
          # Compare results in that “Object” that are “like” anything contained within the “Quotes”.  The “*” before and after indicate it could be anywhere
          if ($line.tostring() –like $CONTENT )
               {
               # write that output to the Console
               write-host ( $line )
               }
          }

# No more function.   All done

}

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

Now again save that as FILEFIND.PS1 file and when you want to search things run

FILEFIND.PS1

which now gives you a new function / feature to run in your Powershell session called “FILESEARCH”

To run it just type

FILESEARCH C:\Windows\WindowsUpdate.log “*Agent*”

And that will give you the same results as the script.

But here’s where Powershell just is so better than sliced bread.    That new script, that easily became a function (Under 10 lines or less) can now be used to search ANY file on the computer.

We can also with minor changes make this same function pipe data to a CSV file or other Powershell Cmdlets.  With very small tweaks, you can use it to search the registry or WMI even.

I tell you.  I love Powershell.  Once you do something, you don’t have to think too hard to repurpose it.

Sean
The Energized Tech