Author Archive

Powershell – Interactive Ping Test…

May 16th, 2013 by Jeremy Pavlov | No Comments | Filed in PowerShell, Scripting

Here’s a fun, goofy little PowerShell script for you. 

Last week Matt and I were working on a “Go-Live” event — where every moment is part of a timed, scripted series of steps — and one of Matt’s critical remote workstations crashed.  Matt had to move on to other tasks while waiting for the machine to come back up, but in that waning moment we wondered to each other… “In all the PowerShell scripts and tools we’ve written, how is it that we never wrote a ‘Host Up’ notification script?”

Well, we can’t let that stand.  So we began to devise the scripts in our heads, and later that evening I scratched it down so that we’d have it next time. 

 

$MyRemoteHost = "8.8.8.8"
$MyFlag = "False"
while ($MyFlag -eq "False")
{
  $MyResult = ping -n 1 $MyRemoteHost |findstr /C:"Reply "
  if ($MyResult -ne $null)
  {
    #write "$MyRemoteHost is up!"
    #Or do something cool here...
    $LoadStatement = [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    $MyInput = [System.Windows.Forms.MessageBox]::Show("$MyRemoteHost is up.  Do you want to EXIT?","Yuuup!","YesNo","Warning")
    if ($MyInput -eq "YES")
    {
      break
    }
  }
  Start-Sleep 5
}

…why?  Just because we can.

;)

 

 

Did you like this? Share it:

Sarah, The Team, and the “Walk For Wishes”…

May 9th, 2013 by Jeremy Pavlov | 2 Comments | Filed in Announcement

It all started simply enough — fellow Coreteker Sarah Roland sent out an email mentioning that she was starting out a Coretek walking team for the “Walk For Wishes” event, and asked for anyone to join or support her in her effort.  The Southeast Michigan Walk for Wishes 2013 event was to be held at the Detroit Zoo, in support of the Make-A-Wish Michigan foundation

Upon seeing the email, I immediately thought of my wife, who had done some charity-focused walks in the past, and forwarded the email.  She loved the idea, and immediately joined in. 

Fast-forward to a sunny,  wonderful Saturday May 4th at the Detroit Zoo where 3000 of our closest friends came out to help raise more than $345,000, and had a great time doing it.  And Sarah’s little Coretek team even raised over $500 in the process — not bad! 

And once we arrived on the morning of the walk, the kids and I could not resist either, and jumped in with Sarah’s family, making it a two-family team.  Sarah’s son was an excellent zoo tour guide!  We had great time all the way through.  Here’s a pic of some of our team crossing the finish line…

walkForWishesFinish

It ended all-too fast, and wrapped up with a nice celebration ceremony and lunch.  Afterward, we made our way back through the zoo afterward just to see some more sights at a little more of a leisurely pace.

All in all: great enthusiasm, a great zoo, great company, great food, and of course, a great cause. 

Thanks to Sarah for putting it together, and thanks to many of you reading this for donating.

See you there next year!

:)

 

Did you like this? Share it:

Earth Day Reflection, 2013…

April 24th, 2013 by Jeremy Pavlov | No Comments | Filed in Announcement

As you may recall, last year the folks at my <un-named customer location> graciously permitted me to participate in their Earth Day recycling “event”.  During this event, the organization encourages the employees to bring in certain items to recycle, which are picked up and utilized by nearby recycling organizations.  This year, the supporting organizations again included those that accept old eyeglasses, old mobile phones for soldiers, etc., as well as computer component recycling by local organization re-Source Partners. 

No matter what your opinion of “Earth Day” itself, I think it’s a great idea to utilize this day in a way that fits your motivations.  As I’ve mentioned before, I don’t think it matters as much *why* you do good things, as it does that you just *do*.  So in my busy life, I think it’s great to have these sorts of reminders to make at least a tiny donation (like the eyeglasses, phones, etc.), especially when the stuff doesn’t even matter to you any more.  Even recycling old computer junk with organizations like this can be considered a “donation” when you think about all the componentry and raw material that will be scavenged from the old computer hardware and returned to usefulness in new products; so much better than filling up a land fill!

 EarthDay2013This year, while my part was fairly small (my mother’s old PC and monitor, 2 of my wife’s old laptops, 2 desktops I got off eBay fro Dev/Testing, and 2 Intel clone servers that served me well), I took a moment to reflect on a couple things:

  1. Even though these are all *working* computers and parts, all of the computing power — combined — is still just a fraction of just ONE of my Virtual Machine hosts that replaced them
  2. It’s a tiny piece of “mess” in my basement that can’t and won’t be re-made; these types of computer components are just not seen as much anymore (and certainly will not be seen in my home anymore) as smartphones, tablets, and other modern devices (and cloud services) have pretty much replaced the need for these things

So that’s all the good news…  The bad news is that my basement still has a ton more of this old hardware.

;)

But I hope Earth Day 2013 helped you in some way, too.

 

 

 

Did you like this? Share it:

Tags: , ,

Powershell – How recursive directory searches got better with PSv3…

April 18th, 2013 by Jeremy Pavlov | No Comments | Filed in Microsoft, PowerShell, Scripting

In the old days, we ate dirt for dinner, brushed our teeth with sticks, used PowerShell v2 — and we *liked* it! 

There, that’s my tribute to Dana Carvey as “Grumpy Old Man”.  Google it, kids.

Anyway, I’ve got an absolute ton of old PowerShell scriptlets that I have lying about that I regularly cannibalize or resuscitate back into production.  And since we are in that squishy transitional period between PowerShell v2 and v3, I don’t always bother to check them for compatibility with v3 or update features in the script to take advantage of new capabilities.  But I hit on one v3 improvement the other day that solved a problem has bugged me so much for so long that I wanted to shout from the mountaintops about it!  And since I live in mostly-mountainless Michigan, the blog is the best I can do…

Really it’s such a little thing.  But it’s so overdue.

In the past, if you wanted to recursively inspect a folder structure on a remote server — for instance while fishing for explicit NTFS permissions on folders — you were forced to inspect all folders *and* files, no matter if you only wanted folders.  Basically, you had to ask for everything (all children folders and files, recursively), then parse the result to extract the folders (check psIsContainer) from the listing.  Here’s an example of this, similar to what you might see all around the internet:

# For PowerShell v2
$containers = Get-ChildItem -path $TopPath\$CurrentParent -recurse | ? {$_.psIscontainer -eq $true}

 Of course, this could be incredibly wasteful in processing, network bandwidth, time, etc…   All this time I’ve always wished there was a way in my loops to just ask for ONLY the folders, to save all of that waste.  Thankfully, this has arrived with v3.  Behold:

# For PowerShell v3
$containers = Get-ChildItem -Directory -path $TopPath\$CurrentParent -recurse

 This has significantly sped up some of my analysis scripts that I run in a large enterprise, cutting as much as half a day off of some of my execution times (I did mention it was large).  So really what this means is that I have to start spending more spare time looking through the v2/v3 differences…  But I won’t have any spare time until I implement more v3 changes…  Quite a conundrum… 

;)

 

Did you like this? Share it:

Tags: , , , , ,

Powershell – Query Active Directory for Server Versions…

March 21st, 2013 by Jeremy Pavlov | No Comments | Filed in Microsoft, PowerShell, Scripting

Today, I’m writing about a simple-but-useful command that just might help you get a better understanding of the quantity and variety of Windows servers you have in your environment, with just a few caveats.  The most accurate way to get such information, of course, is to query Active Directory in real-time to get the most current information possible.  And the easiest way to do that (in my opinion), is to use PowerShell.  So launch a console and let’s get to it…

But first, if you haven’t launched the pre-loaded Active-Directory PowerShell Module, then let’s do that now:

Import-Module ActiveDirectory

Here’s a first blush at how we can list all AD-based computers, grabbing only the interesting properties we need, formatting the output to a list, and redirecting the results to file (I’ve seen some things like this while ‘Googling):

Get-AdComputer -Filter * -Properties IPv4Address,OperatingSystem,OperatingSystemServicePack | Format-List Name, IPv4Address, OperatingSystem* > OutputServerList.txt

Now, let’s dig deeper, and perhaps refine the command a bit.  First, the filter is a wildcard, and retrieves all computers.  That might be fine in a small environment with few computers; but we’re really only after Servers here, and we might be working in a larger environment.  So, we will change the filter to use an LDAPFilter and get a bit more granular like this:

-LDAPFilter "(OperatingSystem=*Server*)"

Next, I think the results will actually look better if we output them to a CSV, so we’ll drop the redirect and list formatting, and replace it with a pipe like this:

| Export-Csv ExportCsvServerList.csv

Now a warning about the CSV export…  Unfortunately, Microsoft chose to include a “restricted” symbol (little r in a circle) in the Server 2008 (non-R2) name, like this:

Windows Server® 2008 Standard

…and, the CSV export operates only with the ASCII set by default.  Sheesh.  So, we use the UTF8 flag to make sure the wacky “restricted” mark is rendered correctly, like this:

| Export-Csv -Encoding UTF8 ExportCsvServerList.csv

So with all that, we end up with a command looking like this:

Get-AdComputer -LDAPFilter "(OperatingSystem=*Server*)" -Properties IPv4Address,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion | Export-Csv -Encoding UTF8 ExportCsvServerList.csv

And since it’s a spreadsheet you can further filter/format/manipulate the results how you see fit.

One more thing that causes confusion sometimes: 

Be aware that even though we are calling ActiveDirectory for these servers and their correlating properties, there’s one of these items that don’t come from there: the IP Address.  As you are likely aware, the IP address of a computer object is not stored in the directory; so what is actually happening is that the Get-AdComputer module is retrieving the FQDN of the computer, and doing a DNS query to resolve it to the address for you. 

Now, this can be good or bad, depending on your situation; for instance, it might slow down your 8000+ server export… or might also help alleviate the burden on your AD server as you make the query (while it delays the processing a tad to retrieve the name).  Also, you’d better be able to rely on your DNS to return valid values, or the results might be confusing/misleading! 

I hope that helps…  Thanks for reading, and by all means if you have additional tips, be sure to comment!

 

 

 

Did you like this? Share it:

Tags: , , , , , , , , , ,

PowerShell – Detect Group Membership Type…

March 7th, 2013 by Jeremy Pavlov | No Comments | Filed in Microsoft Infrastructure, PowerShell, Scripting

It should come as no surprise that adherence to naming conventions and good Active Directory (AD) Organizational Unit (OU) structure are things that can make an Enterprise Administrator’s life much easier. 

Take, for example, the situation of having a naming convention for group objects in AD that dictates a single-letter suffix of either a “C” (to indicate a group of computer objects) or a “U” (for a group of user objects).  In this case, a group might be named something like, “Detroit Application Data U”, or “Chicago Printers Floor2 C”.  And with intentions such as these — and human beings being what they are — it’s inevitable that some users will end up in computer groups, and vice versa.

So how to we check for this messiness?  With PowerShell, of course…

We create a script that will accept an array of our AD OUs (or group-specific OUs if you’re lucky), loop through them, grab all the groups and the memberships, and do a validation to make sure the members are of the correct class (note that I could fill up pages of the lines of code for this, depending on your specifics; so I’ll just stick with the main conceptual points).  Let’s dive into the code snippets!

First, add your OUs into an array, and other variables.  Of course, you might not be able to just scrape a level with PowerShell and grab all your OUs…  Oh, but you *do* have a perfectly-regulated AD hierarchy, don’t you?  Whether it’s perfect or not, AD structure goes a long way here; and my examples show how convenient it is if you have all your groups in a standard ou=GROUPS structure or some predictable way.

$OUs = @("Detroit", "Chicago", "Los Angeles")
$MyDomain = "dc=MyDomain,dc=org"

Then you start to loop and grab all the groups in an OU:

foreach ($OU in $OUs)
{
  #... skipped a few more lines of code here...
# Here we get the list of our groups for the loop
$OuGroupNames = Get-ADObject -Filter {(ObjectClass -eq "group") -and ((name -like "* U") -or (name -like "* C"))} -SearchBase "ou=Groups,ou=$OU,$MyDomain"

And, now that you have the groups, you can start to evaluate each group like this:

  foreach ($OuGroup in $OuGroupNames)
  {
    #...skip more code.. What are we skipping here? Oh, validations, error-checking, and stuff...
# we need the group name and DN    $OuGroupName = $OuGroup.Name     $OuGroupDn = $OuGroup.DistinguishedName

Now, we can truly check the object membership type!

    # If it is a user group...
if ($OuGroupName -like "* U")     {       $MemberList = Get-ADGroupMember -Identity "$OuGroupName"
# ...it had better be a user...       if ($Member.ObjectClass -like "computer")
{
#...or we kick out an error to the report!

And so on.  Of course, you’d do the converse of the snippet above for a user-type object in a “C” group.  By the way, this can lead to all kinds of other error detection too; in fact, the main reason I couldn’t show all my code is that I ended up adding checks for empty groups, groups with members from external OUs, and so on.  Because basically, once you have the group attributes and its membership list in hand, you may as well do some validation while you’re there…

So have fun with it, and see where it leads you…  And make sure to drop me a line if you need any help putting the whole thing together.

:)

 

 

 

 

Did you like this? Share it:

Tags: , , , , ,

Windows Activation Error: Code 0x8007232b

February 14th, 2013 by Jeremy Pavlov | No Comments | Filed in Microsoft, Windows 8

Every once in a while I like to pass along a helpful tip from another website or blog that helped me.  Today, I want to thank György Balássy for his blog posts (post 1, and post 2) last year that helped me with a goofy error, and maybe they can help you too.  I’ll just summarize the problem and results below.

I build a lot of lab servers and VMs for testing various things (including on my laptop or in my home lab, etc.), and I commonly install new Windows servers or workstations from the MSDN media ISO, using what is effectively a volume license.  Usually, I enter the key early in the build, it is accepted without error, and the install continues. 

However, occasionally after the installation completion, the Windows Server 2012 or Windows 8 machine reports an activation error:

Activation Error: Code 0x8007232b
DNS Name does not exist

And back when this first happened to me, it took a little bit of searching before I stumbled on György’s post.  But I’ve referred back to it a handful of times as this frustrating symptom seems to re-appear at random.  In a nutshell, he explains in his two posts that in order to fix this annoying error, you can do it with either the command prompt or GUI, as follows:

Command Prompt:

slmgr.vbs –ipk "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"

GUI:

slui 3

And it has worked perfectly for me every time.

Now, mind you, I did mention this problem was intermittent.  And the main reason I’m writing this post today after all this time is that it just happened to me again 3 days ago when I was in a hurry.  And today, when I had time to try and reproduce the error for a screen capture for this post, of course the key registration worked just fine and I cannot make it fail.  Argh.  So please take my word for it.

So thanks again György; and to the rest of you, I hope it helps you as well  And if it should pop up again, I’ll try to get a screen shot…

;)

 

 

Did you like this? Share it:

Tags: , , , ,

How To Query Active Directory For Object Group Memberships…

February 7th, 2013 by Jeremy Pavlov | No Comments | Filed in PowerShell, Scripting

Not too long ago, I was working with a colleague who was doing a lot of user management and provisioning, and needed to be able to look up the group membership of a user (or a computer) without being too complex or having to memorize anything.  So I installed RSAT on the computer, and made a little batch file that he could run that will take the username (as samAccountName) and dump out the direct or inherited memberships.  Easy as pie.

And as I often do, I thought I’d put up a little blog post detailing the mechanics and concepts of the script.  Of course, we’ve touched on some of these concepts before in this blog, but never in this direct of a way.  So without further ado…

How to Check Group Memberships from the User or Computer Perspective

If you already have the userID/samAccountName, then you can check *user* DIRECT group memberships like this example:

dsquery user -samid "JPavlov" |dsget user -memberof

…and to check *user* INHERITED group memberships, use the expand flag:

dsquery user -samid "JPavlov" |dsget user -memberof -expand

 

Similarly, you can check *computer* DIRECT group memberships like this example:

dsquery computer -name "CTS004895" |dsget computer -memberof

…and to check *computer* INHERITED group memberships:

dsquery computer -name "CTS004895" |dsget computer -memberof -expand

 

How to Check Groups Memberships from the Group Perspective

Of course, I just can’t leave it there.  What if you want to approach it from the other direction?  For instance, if you have a group name (or a prefix if you have a naming convention), and you want to get a membership list of that group?  It’s still doable.  And while I’m at it, I thought I’d sprinkle in a little bit of PowerShell, and still use dsquery to get the job done, as in the following example:

$StartingContext = "OU=Groups,OU=Location,DC=Coretek,DC=local"
$GroupPrefix = "CTS FH "
$GroupList = dsquery * $StartingContext -limit 9000 -filter "(&(objectClass=Group)(name=$GroupPrefix*))" -attr samAccountName,member
$GroupList

…and this works, but… unfortunately, the output is horrible because the dsquery output is ugly.  But, if you happen to already have a list of group names (as in my example groupList.txt below), you could do something like in this example:

$GroupList = Get-Content .\groupList.txt
$StartingContext = "OU=Groups,OU=Location,DC=Coretek,DC=local"
foreach ($GroupItem in $GroupList)
{
  write ""
  write "Group is $GroupItem"
  dsquery * $StartingContext -limit 9000 -filter "(&(objectClass=Group)(samAccountName=$GroupItem))" | dsget group -members
}

…and while it’s basically the same dsquery as in the snippet above, the output is much nicer — since we are piping it into dsget, which makes for a much prettier report. 

Now… perhaps my favorite of all, we can do pretty much the same procedure as the previous command, but this time all in PowerShell, and using the Get-AdGroup command (remember to import the ActiveDirectory module!):

$GroupPrefix = "CTS FH "
$MemberList = Get-ADGroup -ldapFilter "(&(objectClass=Group)(name=$GroupPrefix*))" -Properties Members
foreach ($MemberItem in $MemberList)
{
  write ""
  write "Membership for: $MemberItem"
  $MemberItem.Members
}

And that’s it!  You should have a list of group members for the correlating groups. 

So as usual, we have a couple ways to do a few different things.  Have fun with it!

 

 

Did you like this? Share it:

Tags: , , ,

PowerShell v3 and DNS Queries…

January 31st, 2013 by Jeremy Pavlov | No Comments | Filed in PowerShell, Scripting

As I mentioned in last week’s post, “PowerShell v2 and DNS Queries…“, it is much easier to do scripted DNS queries in PowerShell v3 than it is in v2 — thanks to the new Resolve-DnsName command.  Following along the same lines as the previous post, and using the exact same example hosts, we can show the same correlations and results for comparison. 

We’ll start off with a request similar to our first nslookup in the previous post, but this time using the Resolve-DnsName command:

And as before, the same holds true with out multi-valued results:

On its face, the results are very similar to nslookup results.  However, since we’re dealing with objects here instead of scraped screen executable output, we can actually manage our results very neatly.  Here’s what I mean, as I enclose the object, and only request the “.IpAddress” from it for my two example hosts:

See how neat, clean, and powerful that is?  This same thing works with other object elements, like “.NameHost“, and such.  By the way, I’ve seen some advice posts out on the ‘Net that advise you to use an increment indicator like this:

(Resolve-DnsName $server_name)[0].IpAddress

…but that will cause you to only get the first result returned!  And sometimes, that may be what you’re after; but in the case of the multivalued host, that’s probably not what you want.

Now, to contrast last week’s post, I’ll show you how we take the 12-line PowerShell v2 script down to a 3-line PowerShell v3 script:

$ARecord = "labdc1.lab.local"
$NameServerQueried = "192.168.6.4"
(Resolve-DnsName -Name $ARecord -Type A -Server $NameServerQueried -ErrorAction SilentlyContinue).IpAddress

 …But of course, it’s only 3 lines because 2 of them are variables; but it’s a fully functional equivalent.  And you can start to see how efficient it can be when looped.  And for the sake of completion of the comparison, here’s the results of my v3 script with the “fakehost” multi-valued host:

…and with the original “labdc1″:

So there you have it.  We love the new commands in PowerShell v3, and they are making our lives soooo much easier (once you know about them).   Now, I’m just waiting for the commands I’ve been asking for… Like Get-MyCoffee… and Get-WorldPeace…. and Solve-GlobalHunger

;)

 

 

 

Did you like this? Share it:

Tags: , , , , ,

PowerShell v2 and DNS Queries…

January 24th, 2013 by Jeremy Pavlov | 1 Comment | Filed in PowerShell, Scripting

For this week’s (and next week’s) post, I decided I’d kill a few birds with one stone.  Since it’s “PowerShell month” here at TekTopics.com, and since I’m still making my way through all the differences between PowerShell v2 and v3 (like we all are), I thought I’d tell you about how I just discovered how a relatively simple thing was relatively hard to do in PowerShell v2, and how it got relatively WAY easier in PowerShell v3:  DNS lookups.

Probably like you, I’ve been doing DNS queries for years in all kinds of scripts and languages — like bash, perl, DOS batch files, and of course, PowerShell.  And up until recently, I treated them all pretty much the same — in that I typically just made a system call out to running OS and used the native DNS client query tool, nslookup.  Of course this requires that I grab the output of the tool, scrape out just the information I want (and ignore other data), and continue on to make use of it.

However, in PowerShell v2, the problem is that when trying to grab the desired results back from the system call, the resulting address from the query is not as easy to discern from the “courtesy” information that is returned along with the answer from nslookup.  What I mean is that searching for the string “Address” could get you in trouble, since you end up with two lines that start with “Address” — the one you don’t want (the address of the server that was queried), and the one you want (the query response). 

And in some cases, they could theoretically be the same value, especially if you’re looping through a list of nameservers and query the name of the server you’re querying.  See what I mean in this unfiltered example query and response: 

 

Note that the record could be multi-valued too, like this example:

So if I just attempt to grab all the strings that match “Address”, as in the following…:

…I could end up with some strange results.  So, instead, I search for all strings in the form of an IP address, and I implement a simple counter to skip the first one, catch any subsequent ones, and split the result to strip out the words.  Here’s the code for my loop:

$ARecord = "fakehost.lab.local"
$NameServerQueried = "192.168.6.4"
$FullAddressList = nslookup -type=a $ARecord $NameServerQueried | findstr "[0-9].[0-9].[0-9].[0-9]" 
$counter = 0
foreach ($line in $FullAddressList)
{
  $counter = $counter + 1
  if ($counter -ne 1)
  {
    write "$line" | %{ $_.Split(" ")[2] }
  }
}

…and here are the results, with the query for the multi-valued “fakehost” host record, as in the $ARecord variable as above (inside my Example.ps1 script):

…and with the original “labdc1″ nameserver query, as in my first example:

As you can see, DNS queries are do-able in PowerShell v2, but it’s a pain.  The little snippet above should work just fine inside of a larger loop in a validation script, or on its own, for whatever you need to get done.  And I’m sure there are other ways to accomplish the same thing, but this has worked for me in the past (and present) in PowerShell v2. 

Well — now, there’s a new way of getting the same queries done in PowerShell v3, that is much, much, much easier…  And I will jump into that next week.  See you then!

Next week:   The PowerShell v3 way!

 

Did you like this? Share it:

Tags: , , , , ,