OWSUG.ca

Welcome to Ottawa's Windows Server User Group Community!
Welcome to OWSUG.ca Sign in | Join | Help
in Search

Canadian IT Pro Blog

Browse by Tags

All Tags » PowerShell   (RSS)

  • Powershell on the Way to Work–Part 9

    Today is car pool day.   Only problem is somebody at work took that literally and I’m squished in the back seat of a Compact with a “Mr. Turtle” pool.

    So I promised to show you one of the cooler Cmdlets I ran into, EXPORT-CSV.

    Ok, so what if I told you I could give you a line in Powershell you could run on a staff member’s computer to show just HOW MANY Mp3 files were sitting on their personal folder?

    Let’s pick on fictional employee Mary Smith.  Mary’s boss has suspected (Due to the overheating LAN cable behind her computer) that she has been downloading a LOT of MP3’s and storing them on the company workstation.  He like to know just how bad.

    So you remember GET-CHILDITEM right?

    If we did something like this

    GET-CHILDITEM C:\USERS\MARYSMITH\ –recurse

    That would dump MarySmith’s entire folder to the screen.   That’s neat but useless.    So say we want to filter and only show MarySmith’s massive music collection?

    GET-CHILDITEM C:\USERS\MARYSMITH\ –recurse –include *.mp3

    As the screen scrolls on by for what seems hours (for you see, MarySmith had a VERY detailed music collection) you realize it would be nice to have report to hand off to her manager to show how detailed the collection is.

    Well with Windows Powershell, you can take the output that is going to the screen and pipe it (SEND IT) to another Cmdlet called EXPORT-CSV.   EXPORT-CSV just takes whatever is given to it and “EXPORTS” it to a “Comma Separated Value” file.  Nothing more than that.

    So to get all of MarySmith’s detailed collection into a nice sheet that the Boss could navigate in Excel you just run.

    GET-CHILDITEM C:\USERS\MARYSMITH\ –recurse –include *.mp3 | EXPORT-CSV C:\Report\MarySmithMp3Collection.CSV

    Moments later a nice CSV file perfect for the Spreadsheet of your choice is ready.   The neat thing is you can run just about ANYTHING that is on the screen into EXPORT-CSV.

    Of course this was completely fictional.  The real Mary Smith is law abiding citizen.  When you get into Active Directory and Windows Powershell, you could with a MINOR change pull down a userlist or Group Memberships and drop them in as a CSV file.

    But that is another story.  We’ll chat later as soon as I get “Mr. Turtle out of my ear”

    DSC_0158 (640x425)_thumb

    Sean Kearney
    Twitter: @energizedtech
    www.powershell.ca

  • Powershell on the Way to Work–Part 8

    Ok feeling better today.   Today we’re going to quickly touch on “Objects”.

    Now before all of you IT Pros go running into a corner screaming and casting oil slicks beyond you, we are NOT opening up Visual Studio.   But we are going to touch lightly on a topic that is important to be aware of when using Powershell. 

    No, you will not get tested on this.  Really it’s not that bad either.

    Let’s think in Dos terms first.

    In DOS we did this to set a variable

    SET THISTHING=A Whole pile of words I am staring at on the screen

    or

    SET THISOTHERTHING=55

    If you had to look at that and try to describe it, what would you say it was?  Really.

    I would say it would a bunch of letters.  But to describe it further it isn’t just a BUNCH of letters, it is a Number of letters. Or I might describe the other one as a number. Visually to ME it appears to be a number.

    If I was to have certain applications in Dos that could manipulate that data, I would have some Methods at my hand.

    Really that’s an Object.   The way we would look at that particular information as a WHOLE is an Object and what we can do to it.   (Ok all of you Developers peeking in, this is a REEEEEAALLY simplified explanation, so please stop laughing) Winking smile

    Is your brain spinning a bit?  Let’s look at this Powershell Variable I’m going to make.

    $BrainHurts=’Please Stop Talking About Objects.  Our brains are spinning.’

    In Windows Powershell anything that is stored in a variable is just an object.  That’s all.   To see what is attached to this object we pull out the almighty Powershell Canopener for viewing what’s attached to an Object called GET-MEMBER

    We ‘re going to “Pipe” that variable into GET-MEMBER.  Piping is a term you should be familiar with in Dos land.

    $BrainHurts | GET-MEMBER

    It will give us something like this

    image

    What is tell us looking up is that $BrainHurts is a String (System.String).   There’s a pile of methods (Think built in applications you can use to manipulate what $BrainHurts has) and maybe some extra information like “Length”.

    image

    Do you really care?  If you try to echo it on the screen it will still work.   But understanding that everything in Windows Powershell is an object is important.  It is so much of the Power it contains.   Later on when we touch on Active Directory and understand that each user is an Object, GET-MEMBER will be a way to see what “properties” that user has (IE: Group Membership, Account Expiry, Last Logged on Date)

    We’ll touch on Objects sometime later.   For now, I’ll put the Genie back into the bottle (GET IN THERE GENIE!  *WHAP!*) and we’ll turn to some basics.   I’ll show you the first Cmdlet I ran into that made working with Active Directory a breeze.   EXPORT-CSV.

    Chat soon everyone, time to get back on the road (which is a lousy place by the way for Ballroom dancing)

    DSC_0158 (640x425)_thumb

    Sean Kearney
    Twitter: @energizedtech
    www.powershell.ca

  • Powershell on the Way to Work–Part 7

    “Aaaaaachoo!”

    Sorry got as cold today.  But we can still chat right?

    Today we’re going to learn about Variables in Powershell.   Ok don’t run away.  I’m not going to get all Developer on you and starting speaking in Tongues and spout Functions and code.

    We’re going to use Variables for the moment the same way we did in Dos.   Dos was easy

    SET THIS=SomethingOrOther

    And if we wanted to see that we did

    ECHO %THIS%

    Looks familiar right?

    In Windows Powershell we don’t have to use SET and the Variable name always starts with “$”  (That’s to remind you of all the money you’re going to save with Windows Powershell Winking smile)

    In actual fact, I think they stole it from Python (no not Monty Python) but I could be wrong.  So here is the same Variable we did in Dos in Powershell

    $THIS=’SomethingOrOther’

    You’ll see another difference.   I put quotes around the text.   Powershell is Smart enough to know the difference between Text and numbers.  But it has to be told that.   To identify TEXT from a Number you put either a Single quote around either side or Double quotes.  There is a difference but don’t worry about that now.   Text is still text.   Double quotes just give us “extra Powers” later on.

    Now if want to Echo that back to the screen I can just type in

    $THIS

    or

    WRITE-HOST $THIS

    Here’s the neat part with Powershell variables.   They do all the hard work.   I can tell a Powershell variable that it’s a Number, Text or even the Date and IT will figure it out.  Like this

    $ABunchOfSillyWords=’Hi Diddly Dee, an IT Pro Life for me’

    $MostImportantNumberEVER=42

    $TheCurrentDay=(GET-DATE)

    I can see a few eyes popping open.  “What do you mean you ran a Cmdlet and stored it’s output away?”

    That’s because we’re working with Objects.  We’ll talk about that next time, Right now I have to go sneeze

    Cheers

    DSC_0158 (640x425)_thumb

    Sean Kearney
    Twitter: @energizedtech
    www.powershell.ca

  • Powershell on the Way to Work–Part 6

    Hello, back on the grid again.  literally.   It appears that “Somebody” decided that redirecting all the traffic down a one lane residential street was a good idea.  So I’m stuck for a bit.  We can talk.

    Being that I have Time on my hands I think today we’ll talk about time in Powershell.   It IS far cooler than the old CMD.EXE prompt and far more Powerful.   Let’s try something simple.  I’ll introduce you to GET-DATE

    GET-DATE

    Yep, that was awe inspiringly boring.  I get the date.   But that’s not all it can do.    It can tell me what Day that was.

    (GET-DATE).DayOfWeek

    Or better yet, maybe I just want to know how many days into the Year we are.

    (GET-DATE).DayOfYear

    I could even with a wave of my hand do this and step into the Future

    (GET-DATE).Adddays(24)

    Pretty neat eh?  There’s even built in formats you can choose from like a Short Date or just the Time.

    (GET-DATE).ToShortDateString()

    (GET-DATE).ToShortTimeString()

    I can even tell it to show me a date based upon Criteria I give it.

    GET-DATE –Month 9 –Day 13 –Year 1999

    (Ed….Hmmmm I see no “Space:1999” fans in the audience here.   Well THAT joke was lost. )  But as you can see, GET-DATE is incredibly powerful as I can even produce content from it.   In fact later on when we show you how easy it is to work with Dates and Times in Windows Powershell you’ll wonder why you never used it before.

    Well traffic is cleared up, I’ll be going now.  Don’t forget anytime you need examples of what a Cmdlet can do in Windows Powershell just key in GET-HELP NameOfCmdlet –examples

    GET-HELP GET-DATE –examples

    Touch base soon!

    DSC_0158 (640x425)_thumb

    Sean Kearney
    Twitter: @energizedtech
    www.powershell.ca

  • Powershell on the Way to Work–Part 5

    Oh hey.  Back again are you?  Good thing too.  Flat tire so I’m stuck on side while the Tow Truck driver changes my tire….

    So let me take a few minutes today and show you a pretty cool Cmdlet called GET-CHILDITEM.

    If you remember a bit back, I showed you how typing DIR executes a GET-CHILDITEM.

    So you might think “Ah! GET-CHILDITEM is Powershell’s version of DIR!”

    You might think that but it wouldn’t be accurate.  I could get into great descriptions about Objects and DotNet but then you would fall asleep and my head my explode.    So let me show you some things GET-CHILDITEM can do and YOU can decide just what it is.

    First off, it’s not only good for the File System.   It can access what the Powershell world refers to as “Providers”.   The File system is only one. 

    For example if I do

    GET-CHILDITEM C:\

    You see a file directory of C:\ but I can also do this

    GET-CHILDITEM HKCU:

    Which will dump all of the keys in the Root of HKEY_CURRENT_USER

    GET-CHILDITEM CERT:

    Which will give me the ability to access my certificates.  There are others it can do as well.   We can access the built in Environment variables in Windows (Remember all stuff we used to access in DOS?  Yep! Nothing lost!) or even Navigate and filter on a much higher level.

    So it IS a Directory Cmdlet in a sense.  It will much of the content that you want.   To call it directory is not precise but it does meet our needs as the IT Pro.   Now let’s show you something neat it can do.   Like the old DIR it can recurse

    GET-CHILDITEM C:\ –recurse

    But we can also filter and say “Only give me these file types”

    GET-CHILDITEM C:\ –recurse –include *.txt, *.ini

    Or this was a neat one I ran across.   Go through a structure and show me ONLY files or ONLY directories

    GET-CHILDITEM C:\ –directory

    GET-CHILDITEM C:\ –file

    You can even combine this bits together

    GET-CHILDITEM – C:\SomeFolder –recurse –directory

    By default hidden files like System are still hidden but you can view them with a –force added on

    GET-CHILDITEM –C:\ –Force

    GET-CHILDITEM is an incredibly Powerful Cmdlet.   I’m betting you’re seeing what I did as an ITPro.  That even if I didn’t learn to script, just knowing this means I COULD have a far more powerful search tool on me.   But it get’s better.    You could actually delete files in Powershell based upon Date Time in only two lines.   But we’ll get into that later.  

    For now, the tire is back on the car.  Back to work and we’ll chat soon.

    DSC_0158 (640x425)_thumb

    Sean Kearney
    Twitter: @energizedtech
    www.powershell.ca

  • Powershell on the Way to Work–Part 4

    Traffic was rotten today so I’m sitting in a coffee shop.  Don’t tell the boss ok?

    So last time I mumbled something or other about Aliases and did a Wave of my hands to make you look the other way.  No ? I didn’t do that?  Darn Jedi mind tricks.

    So we mentioned Aliases.    Those familiar with the Unix world will know what an Alias is.   It’s just another word or set of characters to represent something else.  Sometimes to ease typing, sometimes to give us a comfort zone.

    We showed you GET-CONTENT also worked if you did TYPE.  Again this was because an ALIAS already existed for this.

    If you’re curious… we’ll take a few minutes to look at Aliases.  They’re kinda neat.

    If you type in

    GET-ALIAS

    This will show you a list of the current Aliases active in your Powershell console.   But since very few people can read as fast as I can normally talk, I would recommend our friend MORE get’s tacked on.

    GET-ALIAS | MORE

    image

    We can see Aliases for most of the Cmdlets.   If you look near the bottom you’ll see a familiar one called ‘dir’ – When you type in ‘dir’ in Windows Powershell it’s ACTUALLY running ‘GET-CHILDITEM’.  Type it in and take a look at the results

    DIR

    You’ll see output that looks an AWFUL lot like the DIR command in CMD.EXE and DOS.  That’s because GET-CHILDITEM run against a folder will do exactly that.   So although GET-CHILDITEM is an unfamiliar command to you since you’ve just started in Windows Powershell, it DOES work very much (although not the SAME) as DIR.   Using the Aliases can help Powershell become more comfortable using familiar names.

    Now if you’re curious what is the Powershell Cmdlet for a particular Alias, just ask Powershell.  So let’s say we were using what we THOUGHT was the TYPE command and we needed to know what it really was in Powershell?  Just key in.

    GET-ALIAS type

    image

    Afterward you’ll see output on your screen showing you the Alias name “type” under the heading “Name” and the actual Powershell Cmdlet “Get-Content” under “Definition

    Now the flip side is what if you found a Powershell Cmdlet and were curious if there are any predefined Aliases for it?  That’s an easy one as well

    GET-ALIAS –Definition Get-Content

    Again how I figured most of that out was play with GET-HELP GET-Content –examples to see if there was an example of how to use this particular Cmdlet.  I found the third example provided in help had what I wanted but I had to edit the name of the Cmdlet.

    If you’re feeling curious I can take a few moments and show you how to make an Alias.  It’s actually very easy.  We use the “NEW-ALIAS” Cmdlet.

    So let’s say we’d like to make an extra alias for Get-Content called “showfile

    All we’d have to do is type in

    NEW-ALIAS –name showfile –value Get-Content

    Now you can type in showfile as well as type for Get-Content.   Take note, this is a temporary change and will go away. 

    Yes you can make it permanent but my Boss is now buzzing me.  I should actually get back on the road to work

    Until next time, Keep on Shellin’

    DSC_0158 (640x425)_thumb

    Sean Kearney
    Twitter: @energizedtech
    www.powershell.ca

  • Powershell on the Way to Work–Part 3

    Hey!  Glad to see you again.   I took the bus today.   Gives me a little more relaxing time to clear my brain.  It’s nice not to be stuck on the HIghway today.

    We were playing with getting some basic help on a Powershell Cmdlet.  As we said, most of them are pretty good as they provide examples.

    Let’s take a look at one of the simpler Cmdlets called “GET-CONTENT”. 

    So who here would like to place bets on what “GET-CONTENT” does?  Anybody?  Anybody?  Bueller?  Bueller?

    Let’s find out.

    GET-HELP GET-CONTENT –Examples

    image

    If you look at some of the presented examples you should be quick to pick up that “GET-CONTENT” will GET the CONTENT of a file.  It will Get the Content of any file you specify just like TYPE did.  For example if you were to key in

    GET-CONTENT C:\FOO\Somefile.txt

    It would output to the screen the content of “Somefile.txt” located in the C:\FOO folder (whether that content may contain legible data is another issue of course)

    Unlike TYPE in DOS we have newer features like “Tail” which can view the “Tail end” of the text file.    This line will show me the last 5 lines of a Text file called “Booga.txt” in C:\Stuff folder

    GET-CONTENT C:\Stuff\Booga.txt –tail 5

    Now here’s a neat trick, try using “TYPE” in Powershell

    TYPE C:\Stuff\Boogs.txt

    Isn’t that interesting?  It still seems to work.  That's because Powershell offers us a feature called “Aliases” to use other words or short forms to call up the same Cmdlets.

    We’ll talk about Aliases a little later on and how you can use them.  Right now my bus has just gotten to it’s stop.

    Chat soon!

    DSC_0158 (640x425)_thumb

    Sean Kearney
    Twitter: @energizedtech
    www.powershell.ca

  • Powershell on the Way to Work–Part 2

    Gimme a second here, just have to park the car for a moment and get out my coffee.   Rush hour is crazy today.

    If I remember correctly we introduced you to a new Console called Powershell.   Really.  Just that.  A Shell.  Yeah we’re pretty certain it may bring about World Peace someday but we’re going to stick to the basics.

    Last time we run a Cmdlet (CoMmanD-LET) called

    GET-COMMAND

    To give us a list of available Cmdlets in Powershell.  But then I changed the landscape on everybody and added something to it to only show me the available Cmdlets

    GET-COMMAND –CommandType Cmdlet

    So how did I know I could do that?

    Within Powershell is a Help system.  It works a bit like the DOS and CMD.EXE one did where you would say “HELP” and put the Console Command afterwards.  But in Windows Powershell it’s called

    GET-HELP

    I can type

    GET-HELP GET-COMMAND

    and it will show me the parameters of that Cmdlet.

    Keying in

    GET-HELP GET-COMMAND –detailed

    or

    GET-HELP GET-COMMAND –full

    Will give me far more detailed information on it or the Full wallop that particular Cmdlet.   Just like in DOS I can use MORE and start pausing all of those goodies on the screen.

    GET-HELP GET-COMMAND –full | MORE

    But most Powershell Cmdlets have the ONE thing the ITPro needs.   Real world examples of how they can be used.   For the GET-COMMAND Cmdlet if I type

    GET-HELP GET-COMMAND –examples

    Will give you samples of how GET-COMMAND can be used.  Play with GET-COMMAND with some of the examples.  Get comfortable.  Relax

    Did you blink?  Guess what.  You’re already using the basics of Windows Powershell and may not have realized it.   Nice eh?

    Next time we’ll try some of the other Cmdlets to see what they offer us as the IT PRo.

    Until next time, go ahead and play.  It looks like traffic is clearing up and I’m back on the highway.

    Go ahead get your hands dirty Smile

    DSC_0158 (640x425)_thumb

    Sean Kearney
    Twitter: @energizedtech
    www.powershell.ca

  • Powershell on the Way to Work–Part 1

    I’ve heard from many IT Pros who want to learn Powershell.   They want to because they need to.   All the new technology revolves about Powershell.  Many vendors are beginning to adopt Powershell as an automation solution.

    But just where do you start?

    Let’s start at the beginning.   An Introduction.   My friends, this is the Powershell Console

    image

    Powershell, please say Hello to everyone out there.

    image

    Ok yes… that was silly but that is your first introduction to Powershell.  It is a Shell just like CMD.EXE was a Shell.  It can accept simple commands.  Just like ECHO was a simple command.   That is the direction we’ll try to go with.

    You’ll hear a lot about how Powershell is a new Scripting Solution, it can manage Active Directory, it can (if you teach it apparently) tie your shoes.   But for the ITPro you don’t need to know ANY of that just to use Powershell.

    Key word in there… SHELL.  We used to do a lot in the Shell before we had the GUI, there was much we did in the Shell AFTER we had the GUI.   So what we have here is a new Shell.  For me personally I consider it a Management Shell.  I do many day to day tasks with Powershell.   Sometimes it makes more sense to leverage a tool in the GUI.

    But to use it, I didn’t really have to sit down for days and learn it.  I just picked up some simple Cmdlets I needed to aid me in my job as a Network Administrator when I started with Powershell.

    First off, what is available?

    There is a massive amount of Commands here referred to a Cmdlets (Pronounced CoMmanD-LETs) which all follow a simple VERB-NOUN structure.   You will have options like

    DISABLE-ADACCOUNT

    GET-CONTENT

    EXPORT-CSV

    Many of them are written to just make sense out of the box.  These are actual features that can be accessed from Powershell.  Imagine being able to easily UNLOCK a user account or DISABLE a computer?  Maybe even find files buried in the filesystem. This is what I use Powershell for. 

    To get a list of available Cmdlets in your Powershell console key in

    GET-COMMAND

    Of course your eyes will buzz out of your head with the rows pouring on the screen.   But just like in the world of CMD.EXE our friend “MORE” is still there to help

    GET-COMMAND | MORE

    That will let us step through and view the pages full of Content.  Just like in DOS and CMD.EXE.   You’ll three different types, Alias, Function and Cmdlet.   We’ll talk about the differences next time.  But for now We’ll change the GET-COMMAND to only show us Cmdlets.

    GET-COMMAND –type Cmdlet | MORE

    image

    Nice.   Only Cmdlets to see.   Less to confuse us with a smaller pile.   Where do you start?  Believe it not.  Just try typing in a Cmdlet to see what it does.   All of the Hotkeys you had in CMD.EXE still work too.  CTRL-C is still your best friend.

    But how did I find out how to work “GET-COMMAND” ? What if I want bigger letters?  What if I don’t like Blue?  What if I want to customize the console?

    All of this and more when we return.  Time for me to head out of the car and get to work.  I’ll see you soon.

    DSC_0158 (640x425)

    Sean Kearney
    Twitter:  @energizedtech
    www.powershell.ca

  • Resources for Retention

    imageYou can attend all the conferences, seminars, and training courses that you want, but just watching and listening will only allow you to retain about 10% of the information given to you. A measly 10%. That’s a pretty low return on your investment. Luckily, we’ve designed TechDays to help participants remember and recall a whole lot more than that.

    For those attending the conference in person (there is still time to register for Vancouver and Montreal!) there are the Instructor-Led Labs where you can bring your notebook and get your hand dirty on the cool technology that you’ve been learning about. You can also review the materials – session recordings and access to the labs will go live on the TechDays site after the conference is finished, in December. But in addition there are resources that you can use to supplement your learning.

    The complete list of session resources will be coming out soon as my colleagues pull together information for each of their areas. But for now, I’ll list the ones for the sessions that I’ve been working on organizing – the Security, Identity and Management sessions. These sessions cover a wide range of topics – everything from securing your wireless network to how the latest innovation in System Center, called Orchestrator, helps you build a flexible private cloud infrastructure by creating automated process workflows from numerous vendor products.

    Whether you’re able to join us in-person at TechDays or not, below are some great resources for diving in and learning more about securing and managing your infrastructure. Happy Learning!

    Securing your infrastructure:

    General systems management using System Center products:

    Information on System Center Orchestrator:

    Information on System Center Operations Manager:

    Learning more about PowerShell:

    Software Asset Management:

    signature2 (100x78)

  • The Hammer of Thor, the Lightening of Zeus, None compares to Windows Powershell! It can CLOSE MY OPEN FILES!

    Hi, I’m Sean.

    I’m an ITPro and about three years ago (and you can’t tell my wife this) I began my affair with Windows Powershell.   As you can tell from my background (and forget all the silly letters) I really just consider myself a true blue, grease under my fingers, crimpers in my pocket, screwdriver in my mouth, TECH.

    A few months back somebody asked on TechNet Talk Radio if Powershell could close files.   It might be able to do this but somebody else already wrote a great utility that already does this.  It’s called HANDLE.EXE from Sysinternals 

    The STRENGTH of this application is that it works well and can’t accidentally close all the files on the server. The weakness is that I cannot easily (out of the box) automate it. Or can I?

    Within Powershell one of the biggest pieces you need to remember is that everything (And I mean EVERYTHING) is returned as an “Object”.

    Now the rest of you ItPros, quit hissing like Gollum.   An “Object” really isn’t scary or nasty.   You won’t turn into “Darth Vader” because you used one.

    So here we’ve downloaded HANDLE.EXE into a little folder called C:\HANDLE PROGRAM and we’re going to query for all the open Word documents on the local computer.  As per the instructions in HANDLE.EXE I have run the console as an Administrator to gain the rights needed to globally close files

    C:\Handle Program\HANDLE.EXE .DOCX

    And we’ll get some output on the screen like this

    Handle v3.45
    Copyright (C) 1997-2011 Mark Russinovich
    Sysinternals - www.sysinternals.com

    WINWORD.EXE        pid: 13352  type: File           15C: C:\TEC2011\Why does Sean always leave his files open.docx
    WINWORD.EXE        pid: 13352  type: File           1B0: C:\TEC2011\If Sean Keeps doing this we won.docx
    WINWORD.EXE        pid: 7496   type: File            1A8: C:\TEC2011\demodocbadsean.docx

    It appears “SOMEBODY” who shall remain nameless has been leaving their Word documents open (tap tap tap)

    Normally if I would like to close an open file in HANDLE.EXE I would execute

    C:\Handle Program\HANDLE.EXE -c 15c -p 13352 –y

    And we would get an output like this, which if it’s successful even outputs a line with the status at the end.

    Handle v3.45
    Copyright (C) 1997-2011 Mark Russinovich
    Sysinternals - www.sysinternals.com

      15C: File  (R--)   C:\TEC2011\Why does Sean always leave his files open.docx

    Handle closed.

    So I can do this in Windows Powershell as well with a minor difference.  I’m going to store all the output from HANDLE.EXE (Since the output to my screen is an Object) into a Variable.

    $RESULTS=(& 'C:\HANDLE PROGRAM\HANDLE.EXE' .docx)

    So the output that WOULD have gone to the console (which is an Object) is stored in $RESULTS.   If you type $RESULTS into the Powershell Console you’ll see the same output as before.

    But since it’s in a variable we can now access and manipulate that output in a way we couldn’t before.  If we look at the screen we’ll see that the output is consistent.   All the lines that have the information we need contain “pid:” just before the Process and “type: File” just before the File handle.

    So in Windows Powershell I can take the [String] object that is stored in $RESULTS (My Console output) and pull all of that out with a quick comparison, which I’ll store away in a variable I’ll call $HANDLEDATA

    $HANDLEDATA=$RESULTS –match “pid:”

    Which will output to the screen only that data.  At this point we can run each line through a SELECT-STRING to find where in the string the content sits.  I need to find the location of “pid:” and “type: file” in each line and pull the number following it out.  I’m going to work on the first entry in the [String] array as an example

    We’ll grab the ProcessID number first.  SELECT-STRING will find it’s position which we’ll store away as $StartPid

    $StartPid=($HandleData[0] | SELECT-STRING 'pid:').matches[0].Index

    Then we’ll access the content which is consistently starting at positions away (The length of ‘pid: ‘) and is never more than 7 bytes long (I counted Smile with tongue out).  We tack on the “trim()” to make sure if there are any blank spaces before or AFTER the Number they are “Trimmed” off

    $Processpid=$Handledata[0].substring($StartPid+5,7).trim()

    We’ll repeat the process for the File Handle in a similar method.  Find the String with SELECT-STRING, Grab it’s index and then pull out what we need with a little substring()

    $StartFileID=($HandleData[0] | SELECT-STRING 'type: File').matches[0].Index
    $Fileid=$HandleData[0].substring($StartFileID+10,14).trim()

    At this point we have a way of pulling out consistently the the necessary data to send it back to HANDLE.EXE and close it.  I can execute a line like this now after I pull the information on each line.

    (& 'C:\HANDLE PROGRAM\HANDLE.EXE' –p $ProcessId –c $FileId -y)

    Now this will work but looks messy on the screen.  We could just store the results away in a variable and grab that last line showing a success/failure

    $CLOSEFILESTATUS=(& 'C:\HANDLE PROGRAM\HANDLE.EXE' –p $ProcessId –c $FileId -y)[-1]

    Ok so there’s all the pieces.   So what does it look like as a script?

    Just look below

    -------------------------CLOSEWORDDOC.PS1-------------------------------------------------------------------------

    #
    # Script to close all open Word Documents on my File Server because Sean keeps forgetting
    # Requires HANDLE.EXE from Sysinternals on the system.  Free download
    #

    $RESULTS=(& 'C:\HANDLE PROGRAM\HANDLE.EXE' .docx)

    $HANDLEDATA=$RESULTS –match ‘pid: ‘

    Foreach ($File in $Handledata)
         {
         # Get the Handle ID of the Process for this file

         $StartPid=($File | SELECT-STRING 'pid:').matches[0].Index
         $Processpid=$File.substring($StartPid+5,7).trim()

         # Get the File ID of this open File

         $StartFileID=($File | SELECT-STRING 'type: File').matches[0].Index
         $Fileid=$File.substring($StartFileID+10,14).trim()

         # Close It

         $CLOSEFILESTATUS=(& 'C:\HANDLE PROGRAM\HANDLE.EXE' –p $ProcessId –c $FileId -y)[-1]

         }

    #

    -------------------------CLOSEWORDDOC.PS1-------------------------------------------------------------------------

    Now of course this is a pretty static solution.  We could improve this in so many ways like using a variable for the file name or extension, dropping in some error handling.  But this is to give you a taste of how you can automate systems that weren’t DESIGNED to automate.

    If you want to have some real fun, here is a script that within Windows Powershell I took that SAME application (HANDLE.EXE) and extended it’s features into New Cmdlets via Advanced Functions.  One to show the open files, one to obtain their Process ID’s and FILE ID’s and a third to close them.  If you’re interested on where this one has gone I’ve uploaded it to the Technet Script Repository so you can download it.  With this version you can execute Cmdlets like

    GET-openfile DOCX

    To get the list

    GET-openfile XLSX | Close-Openfile –whatif

    To CAUTIOUSLY do it

    GET-openfile DOCX | Close-Openfile

    This can easily be turned into module as well (how I’m running on the system right now) to extend the abilities of your shell as well.  

    If you’re interested more in playing with Powershell and some of your legacy applications, there is an entire series on “Hey Scripting Guy” which delves into this. 

    Ah Powershell.  Where were without you before Smile

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

    clip_image001

    Sean Kearney is an infrastructure support analyst and Microsoft MVP in Window PowerShell. He is absolutely passionate about automation technologies—especially Windows PowerShell. If you say, “Powershell,” he may just break into song. Sean considers himself “just a tech at heart,” but he can often be found dabbling with most Microsoft technologies at a moment’s notice. We have also been advised to keep him at arm’s length from any open Starbucks in Seattle. We have been advised that any rumors about him ever singing for Microsoft JobsBlog are completely unfounded. Complete rubbish. Let us just keep it between you and me, OK?

    Sean's contact information:
    Twitter: EnergizedTech
    Blog: Energized About Technology
    Website: Powershell: Releasing the Power of Shell to You

  • Scripter? Like Automation? Powershell Scripting Games are for YOU!

    clip_image002

    “…Sweat pours from your brow, your muscles tighten as you hammer away the Cmdlets into the Windows Powershell console.   A bead drips onto the keyboard revealing the smell of Ozone in the air. That last line poured out of your soul onto the page, and it felt so right.  One more task automated.  The systems bow down to the scripter…”

    Is this you?  Are you an ITPro with that rare untouched gift?  Automation?  Scripting?

    How about a chance to put those skills to the test and an opportunity to Script real world scenarios to test your mettle, improving your skills at the same time!  A rare chance to pit yourself against the best and build upon yourself at the same time!

    The 2011 Scripting Games are for Novices and Enthusiasts to with an opportunity for Fame and Prizes as well as EXPERIENCE in scripting against REAL Scenarios!

    THAT is what the 2011 Scripting Games are offering for FREE and they’re coming your way.  

    The Excitement starts April 4th 2011 and continues on through to April 15th 2011.   TEN (10) Events with both options for Beginners and Scripting Guru alike to pit their skills in Windows Powershell, it’s a rare chance to improve while improvising and have your code reviewed by a panel of judges comprised of Windows Powershell Celebrities and Experts!

    How can you lose? 

    You CAN’T!  Not only will your name possibly be in lights, but this is a chance to get critique on your scripting by Internationally recognized Windows Powershell experts and MVP’s as well as Daily Chances at Prizes!

    So why not give it a shot?  This could be YOUR chance to shine!  Why not take the chance?  You have nothing to lose and EVERYTHING to gain!

    The 2011 Scripting Games are no small event either.  Last year THOUSANDS of Scripts were launched and submitted from HUNDREDS of countries across the planet from people JUST LIKE YOU!   Which has got to be the coolest part.  Competing with people just like yourself!  

    So a chance to Grow and LEARN for FREE? Have Powershell Masters review your scripts?  Really? FREE?

    YES!  Spectators and Competitors pour on in to the Scripting Games and benefit each and every year benefiting from the camaraderie as well as the INTENSE competition!

    Interested?

    You too can participate!  Don’t fear on whether you’re a specialist or an enthusiast.  The 2011 Scripting Games are for everybody! It’s all about learning Powershell and having some fun at the same time…. And perhaps a chance to rub your friend’s nose in it if you one up them! clip_image002

    Need more information? Head directly here for all the information you’ll ever need or watch POSHCODE and “Hey Scripting Guy” for more details!

    Curious what the games were like?  Information from the Scripting Games from 2010 and Scripting Games from 2009 are still online for you to review! 

    Except one difference.  The future is here with 100% Fresh Pure poured Windows Powershell!

    So what are you waiting for?

    The 2011 Scripting Games are calling you!  STEP up and seize the day! 

    It’s yours to have O Mighty Scripter!

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

    Note From Rick: Who better then our friend Sean Kearney, Powershell MVP to write up a blog post about The Scripting games, eh? Thanks Sean!

  • Guest Blogger – Searching with PowerShell

    Sean Kearney has been doing some work with PowerShell as of late and sent in this little write up about searching with PowerShell!  Enjoy, and remember if you have any tips you want to share email us!

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

    A post I threw onto "Energized about Technology" and "Energized Tech". A simpler intro to a small script that can be a function in PowerShell. Today I had to search for something in a Text file.  In PowerShell there's 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, and type 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” 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 I run this new script, 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

    Sean Kearney

    Friday Funny Guy

    fridayfunnyguy@energizeit.ca

    addthis_pub = 'CDNDPE';

  • Free PowerShell Book

    Every so often you miss something, perhaps it was all the Energize IT prep the team was heads down in, regardless I woke up this morning with tweets, emails, blog posts in my RSS all about a free PowerShell book.

    Powersheelbook

    Free as in beer, not even an email registration!  Just hit the link below and download the 1MB PDF full of great information on PowerShell!

    Effective PowerShell: The Free eBook

    One of the blog posts was written by Wilbour Craddock, a Canadian transplanted in Ireland, who mentioned the Virtual PowerShell User Group.  This group is run by a Canadian MVP, Marco Shaw, who always manages to get some great guests.  All their meetings are recorded and he is always willing to speak to other user groups through the power of LiveMeeting.

    Lastly be sure to check out PowerShellCommunity.org where you’ll find Marco and many other PowerShell experts.

  • A Few Sleepless Nights

    A while back Ruth did an interview with Cameron McKay about an upcoming infrastructure project he was in the planning stages on.  While the planning is done and the implementation also complete, I thought it was time to revisit with Cameron and talk about how things went.  Turns out Cam was one step ahead and posted an entry on his blog which we are cross posting here.

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

    And here we are.... it's March 15th, I'm now 25 Years old, and the largest infrastructure project of my career to date is wrapping up. Now, I originally planned to have all work completed in a weekend... I may have been off by a week or two. Not a result of unknown factors, but delays in setting up systems and the occasional hour or two of sleep.

    February 27th at 10PM my Team and I started by redirecting all web facing sites to the ubiquitous "planned downtime" graphic to alert clients that the geeks are hard at work somewhere... :)

    First up on the task list was to modify our Cisco switches and firewalls and setup 10 new VLAN's. The tricky part here is that the Cisco VOIP servers also need to be re-IP addressed and this is where we had to take our time. While our contractors were busy checking everything with the telephony systems, our team was busy setting up the base AD Infrastructure (DNS, DHCP) and getting ready to deploy all our new servers.

    What servers exactly?

    • Windows Server 2008 /w Hyper-V
    • Exchange Server 2007 SP1
    • SQL Server 2008
    • IIS7
    • Team Foundation Server 2008
    • Office Communications Server 2008 R2
    • Groove Server
    • ForeFront Client Security
    • SharePoint Office Server 2007

    Not to mention:

    • WSUS
    • NAP
    • Certificate Services
    • Rights Management
    • File Screening

    And if that wasn't enough... We rolled out Vista Enterprise and Office 2007 to 100 workstations and also deployed the latest Blackberry Enterprise Server. I also felt the need to deploy the latest version of GFI Faxmaker to handle our some 300 faxes a day at the office.

    And of course, it's all managed by System Center.

    So around 2am on Saturday morning all the network changes were completed and the base AD deployment completed. At this point, we have taken a flat network and diced it up into 10 VLAN's, a DMZ, and 4 Windows domains. I'm still pretty excited and pushing through the night.

    Next up was taking all our existing physical and virtual servers and switching the IP's. This took us until around 6am...

    We took a coffee break and then moved onto deploying Exchange Server 2007. About this time I realized that I haven't slept yet and shrugged it off... I'm an IT Pro. At 9am we brought our SQL Servers online and IIS 7 web farm. My network team was working on all the ACL's and settings for the DMZ to make sure that we were ultra secure, as this is a Fortune 18 we work for and information security is paramount.

    Our developers came in around 10am to start migrating content from the old network and get the business up and running again. One challenge here is that there was no connectivity from the old LAN to the new network, so terabyte hard drives were used to move all the files.

    This took the better part of the day to get all the files over and onto the new servers. Once this was done, the Dev's could start configuring all the new database servers and IIS sites. I had our network team leave the edge network accessible from the internal LAN to make it as easy as possible for the development team to get access and complete the migration.

    Around 6pm on Saturday evening the Boss realized that I hadn't been to sleep yet and "suggested" that I go over to the hotel and get a few hours sleep. I slept from 7 until 11 and then showed back up at the office to continue working on the deployment.

    Sunday morning we started our LT deployment of Vista and Office 2007 to all the desktops. I was left configuring Exchange 2007 and the Blackberry Server and a half dozen other servers. We were having some issues with migrating the data. As it turns out, moving everything onto SQL 2008 and IIS7 is a big deal. Who would have thought? At this point, the comment of "backing out" came up. I didn't like the sound of that... and the discussion became a pow-wow a couple hours later.

    I'll spare everyone the discussion, but we decided to push forward and not roll back. Forgetting that all the workstations were already converted to Vista and on the new network, it would of been about 6 hours work to bring the old LAN back up.

    Around 2am on Monday morning I had my first real challenge of the deployment. The Exchange Hub Transport and Edge Servers suddenly stopped working. The EdgeSync connectors were all there and all the settings were correct and by-the-book.... but still, I couldn't send or receive email. So, 6 hours from the start of business, email was down. This was my worse nightmare. After a couple hours of troubleshooting and rebuilding the EdgeSync, I had email working again.

    Come Monday morning, we had core systems online and our CRM application was functional but none of the file shares or printers were up. Throughout the day we were busy assisting the developers, as their apps are all client facing and most of my Infrastructure changes were completed.

    Again, sent over to the hotel late Monday afternoon for a few hours sleep. Back at the office come 2AM. At this period, I'm feeling like the biggest geek in the world... and loving it.

    Tuesday I had the file shares and printers online. The task for the next couple days was to import all the old email from our 5.5 server and load it into each users new mailbox. This was a tedious task that took us until Friday to complete. Why? Lot's of old email...

    Over the weekend we brought ForeFront Client Security online. This is probably my most favorite piece of the new Infrastructure. All workstations and servers were now protected.

    The following week we were tweaking group policies and completing the configuration of all our web portals and databases.

    Fast forward to today. It's Sunday March 15th... and we have the most modern network in the company. Built for High Availability and Security from the ground up using the latest Microsoft technologies. I am very proud to say that I was apart of this great project and it has definitely been a fun and exciting ride.

    The best part is that 90% of the Datacenter is virtualized on Hyper-V. I'm a huge fan of the technology, and the benefits it provides our business in the DR / BC areas.

    It was interesting to see the entire IT Team, all 9 of us, pull together and stand unified behind this project. Sure, it's difficult and I've only had 20 hours total sleep in two weeks, but this is what I live for. We now have a platform to work off of that will drive the business for the next 6 Years.

    Was it as easy as I thought? NO. Would I do it again knowing what I know now? YES. Why? Because it had to be done. Our business is very competitive and we were working off technology that was 10 to 15 years old. More time was spent on maintenance and workarounds, then innovation.

    And how do I feel? Great. I slept in this morning and looking forward to getting back into the office tomorrow to work on my new state-of-the-art Infrastructure. All 100% Microsoft software based.

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

    You can read more about the project at Cameron’s blog!

More Posts Next page »

This Blog

Syndication

Powered by Community Server, by Telligent Systems