Powershell – Check for PS version and act accordingly…

2013-05-22T22:29:39+00:00 May 22nd, 2013|Uncategorized|

In recent posts, we’ve been outlining some important day-to-day differences in PowerShell CMDlets and features between v2 and v3.  And right now I’m working with a customer that is in the midst of transitioning between XP and Win7, and between Server 2003 and 2008/2012, where these differences really start to matter performance-wise. 

So, we’ve got lots of PowerShell tools we wrote in v2 that we are slowly getting around to updating to the new features in v3.  But the thing is, we still can’t be certain where these scripts will be run, and by whom.  So we’ve put together a little “version detector” to help run the correct version of the command and give the best performance possible, whenever possible.  And as a result, you — the reader — can apply this type of thing to any script that might be run in a mixed environment.

This example below features the new -Directory flag in the PowerShell v3 Get-ChildItem, though you could just as easily replace that line in each section with any other CMDlet that behaves differently between versions.  Just modify this section, and wrap it around your CMDlet with the updated v3 capability…


$hostVersionInfo = (get-host).Version.Major
if ( $hostVersionInfo -eq "2" )
  # For PowerShell v2
  write "We appear to be using PS version $hostVersionInfo... That's okay, but this script processes faster with PS v3!"
  write ""
  $containers = Get-ChildItem -path $MoLoPath$CurrentParent -recurse | ? {$_.psIscontainer -eq $true}
elseif ( $hostVersionInfo -eq "3" )
  # For PowerShell v3
  write "We appear to be using PS version $hostVersionInfo... Good!"
  write ""
  $containers = Get-ChildItem -Directory -path $MoLoPath -recurse
  write-host "Unknown/unapproved version of PowerShell. Exiting!"


Normally, I’d explain some of the functionality in the script; but it’s fairly simple, well-commented, and in general pretty descriptive.  It just detects which version of PowerShell you’re running, and runs one of the two version of the CMDlet.  So you should be able to figure it out quickly even if you’re new to this stuff. 

Of course, if you have a question (or have a better way of getting it done), feel free to comment. 

So that’s it, I hope it helps!




Powershell – Interactive Ping Test…

2013-05-15T22:39:09+00:00 May 15th, 2013|Uncategorized|

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 = ""
$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")
  Start-Sleep 5

…why?  Just because we can.




Powershell – How recursive directory searches got better with PSv3…

2017-07-27T00:01:04+00:00 April 17th, 2013|Uncategorized|

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… 



Powershell – Query Active Directory for Server Versions…

2013-03-20T22:45:57+00:00 March 20th, 2013|Uncategorized|

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!




PowerShell – Detect Group Membership Type…

2017-07-27T00:01:04+00:00 March 6th, 2013|Uncategorized|

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.






AD Attributes – LastLogon vs. LastLogonTimeStamp…

2017-07-27T00:01:04+00:00 February 27th, 2013|Uncategorized|

A little while back I was working at an enterprise that has many locations across the United States.  I had a list of 30 usernames (from one specific out-of-state location) and a couple brand-new test accounts that I wanted to report on their “last logon times” from the Active Directory domain.  I put together a quick PowerShell script to loop through each user and report on the “lastLogon” time and I had (what I thought were) my results in no-time.  Here is a snippet of the code:

Get-ADUser $UserNameToSearch | Get-ADObject -Properties lastLogon

First, I opened up an RDP session to a domain workstation that I had access to at the out-of-state location that I was working with at the time and I went ahead and logged in with my test user.  I waited a few minutes for the replication to occur back to my location’s domain controller and then I ran the script from my local workstation.  Surprisingly, there were no results reported for that test account, but there were current up-to-date results for 95% of the users who were on my list that are said to work at that same location.

So I logged out, logged back in, waited, and ran the script again.  Still, no “logon time” results for my test user account.

Very interesting….

I did a few minutes of research on the “lastLogon” attribute and then I discovered I was searching the wrong attribute, per Microsoft’s MSDN Attribute Library which states: “This attribute is not replicated and is maintained separately on each domain controller in the domain. To get an accurate value for the user’s last logon in the domain, the Last-Logon attribute for the user must be retrieved from every domain controller in the domain. The largest value that is retrieved is the true last logon time for that user.  But since the enterprise I was working with had more domain controllers than I could count on one hand so I chose to find a simple alternative.

After a few more minutes of research I then found the attribute that is replicated across all domain controllers, the “lastLogonTimeStamp” attribute.  I updated my script to:

Get-ADUser $UserNameToSearch | Get-ADObject -Properties lastLogonTimeStamp

I then had the results that I expected and I carried on with my day.

Hopefully this experience will save you time and effort!




How To Query Active Directory For Object Group Memberships…

2017-07-27T00:01:04+00:00 February 6th, 2013|Uncategorized|

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

…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"

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!



PowerShell v3 and DNS Queries…

2017-07-27T00:01:04+00:00 January 30th, 2013|Uncategorized|

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 on Windows 8 and Windows Server 2012 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)

…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 = ""
(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




 (Updated 20130815)

PowerShell v2 and DNS Queries…

2017-07-27T00:01:04+00:00 January 23rd, 2013|Uncategorized|

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 = ""
$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!


PowerShell Basic Commands 101

2017-07-27T00:01:04+00:00 January 16th, 2013|Uncategorized|

It looks like January has turned into “Powershell Month” here at the TekTopics.com! 

And while typically, we write these Powershell-related posts with the assumption that you’re already at least reasonably versed in the language, I thought it might be good to give a few introductory tips to those of you who need the first few basics of Powershell to get you up and running.  Then, you can take these tips and start getting creative with some of the great scripts, loops and commands we’ve talked about here in this blog.

First off, when in the PowerShell command prompt type in “Get-Command” and hit enter:


This will list every PowerShell command available. It is quite lengthy, but can be very helpful if you have the time to scroll through the entire list to discover new and exciting scripting tools.

If you wanted to save this list, you could by outputting it to a file by using the “|” (“pipe”) combined with the “Out-File” command, for example:

Get-Command | Out-File C:Commands.txt

If you are like me and require the list to be sorted by “practical application” then you can sort it by `Module Name’ by simply running:

Get-Command | Sort Module

You can then take it one step further to narrow your search results by filtering by Module name and a “*” (wildcard) as seen here an example of searching for BitLocker:

Get-Command -Module BitLock*

Or if you are looking for a specific command to run to `Enable’ BitLocker:

Get-Command –Module BitLock* -Name Enable* 

From there, if you need usage commands or examples of any newly found Powershell command you can use the “Get-Help” command. The following example would give you helpful information for the “Get-Command” cmdlet as previously mentioned:

Get-Help Get-Command

Or for “Select-String”, the PowerShell equivalent to “FindStr” or the ever-so-popular string search tool called “Grep”:

Get-Help Select-String

One final note to tie this all together: Instead of memorizing the entire cmdlet, module or function names you can use the built-in aliases, which are shorter commands that execute the same command as the long name function, for example: gcm is Get-Command and help is Get-Help

So you could run the following command, which is the same as the above “Get-Help Get-Command”:

help gcm

And you can view the entire list of “Aliases” by running:

gcm -Type Alias

That is all for now! Stay tuned for PowerShell Basic Scripting 101!



Load More Posts