Category Archives: Miscellaneous

Active Directory configuration report

‘Sup PSHomies,

Last blog I talked about how to create a AD configuration snapshot. I saved the AD Configuration using the Export-Clixml cmdlet. As promised here’s the follow up: How to create a report from the saved snapshot.

I’m a fan of HTML for reporting purposes. In the past I’ve dabbled in creating reports using XML in combination with CSS. The challenge was creating a well-defined XML file. If you’ve ever had the idea of using Export-Clixml to combine with CSS then you’re in for a disappointment! ConvertTo-HTML is a better fit for reporting. Having said that, creating a well-defined XML file can also be a challenge. As luck would have it there’s a mini-series on the subject, check it out if you want to go down that route.

My favorite way of creating HTML reports these days is using PScribo, brought to us  by Iain Brighton. I saw him demonstrate the module at the PowerShell Conference in Stockholm on youtube. PScribo sure makes creating reports easier! PScribo supports different output formats:

  • HTML
  • Word
  • Text
  • XML

You can also edit the style of your document. To get a better impression of all the possibilities have a look at the video. The module has enough examples to help you get started. Before you know it you’ll be hooked!

Here’s the script:

I’ve recently discovered markdown. If you’re comfortable creating HTML documents, then MD shouldn’t be much of a challenge ;-). BTW if you’re looking for a good MD reader, vscode has you covered. VSCode is gaining momentum in the PowerShell community. I’ll admit to being hooked on ISESteroids, still,  Tobias Weltner said there will be a major update pretty soon… So who knows what this might mean?

I decided to give it a try in MD Format as well!

Not bad…

MD Format ADConfiguration

MD format has a small footprint which could be interesting. MD files can be converted to other formats. Doug Finke has an excellent vscode extension to render md files in pdf, word or html, using PanDoc.

PScribo is definitely worth a try! MD is also an option. Generating reports in Powershell just got easier thanks to Iain & Doug! Great addition guys! Keep up the good work!

Hope it’s worth something to you

Ttyl,

Urv

Advertisements

Pester to validate ADUser properties

‘Sup PSHomies,

See if you can relate. You’re in the middle of a migration, the users need to be created asap. You get a xlsx file with all the necessary properties. A quick Copy/Paste to csv file, Import-Csv  user.csv -Delimiter "`t" | New-ADUser and presto! Whew! Glad we got that out of the way 😉

Feels pretty awesome right? 15 minutes after, your project manager comes asking: “Say, which file did you use?” The one you sent me last week, why? “Uh, there’s a new version on sharepoint, did you use that one?” Well I did ask which file I should use (in my defense I did, that’s why I always email, written proof!). “Well there’s an updated version, could you make sure the users get updated? Thanks!!!” Sigh, here we go again…

At this point I can do two things:

  1. Just delete and recreate. Thing is you’ll loose SIDs and access to homedirectory etc etc. Not exactly ideal.
  2. Update the user properties. Definitely a better option. Still tricky especially using the Set-ADUser cmdlet, but that’s another story.

But before you go off to update the user settings, how about validating what has been changed? Maybe the damage isn’t that bad. I mean if it’s under five changes, I just might  do it manually… Oh who am I kidding? Wait, gimme a minute to catch my breathe from laughing! 😛

Enter Pester for ADUser validation!

With a Pester script to validate your ADUser settings, you’ll never have to second guess if the settings are as they should.

Here’s the result:ADPesterResults

Here’s a quick rundown of the script:

First I’ll just get all the user settings using $verify = Get-ADUser -Identity $user.SamAccountName -Properties *.

$ADPropertiesToVerify =  ($csvADUsers | Get-Member | Where-Object {$_.membertype -eq 'noteproperty'}).name will get me all the properties in the csv file. No need to map properties manually. Now I can loop through any amount of properties!

Next up, making sure empty properties get $null

if (([string]::isNullOrEmpty($user.$attribute))) {
   $user.$attribute = $null
}

$null isn’t equal to empty (Ofcourse you already knew that!)

Now compare what’s in the csv to what Get-ADUser found:

if($attribute -eq 'Path'){
   it "User is located in $($user.$attribute)" {
      $verify.DistinguishedName.Contains($user.$attribute)
   }
}
else{
   it "User property $($attribute) value is $($verify.$attribute)" {
      $user.$attribute | Should be $verify.$attribute
   }
}

Quick note: I used Path to create the user in a specific OU. There’s no Path property in Get-ADUser. So I did the next best thing, just verify that path is part of the user’s distinguishedname 😉

I also added a little bonus to verify the user’s homedirectory exists and that the user is also the owner.

Being able to validate will definitely give you peace of mind…

Hope it’s worth something to you

Ttyl,

Urv

Custom Intellisense for AD cmdlets with SearchBase parameter

Sup’ PSHomies!

You gotta love the PowerShell community! Found this little gem in my twitter feed (again) :-). Trevor Sullivan demonstrates how we can create custom intellisense for cmdlets if they haven’t been provided as yet. Great video! Trevor really does a great job explaining this.

The first thing that came to mind was Active Directory! I can’t tell you how often I needed the DistinguishedName of an OU. Now imagine having a dynamic list generated for you! No more errors,  just select and you’re good to go! Excited??? I sure am!

Sometimes you need to limit your searchbase depending on you AD size. Let’s say I want to retrieve all users starting from a specific point

Get-ADUser -Filter * -SearchBase 'OU=Users,OU=IT,DC=pshirwin,DC=local'

A simple typo will generate an error. Distinguished names are notorious for being lengthy…

Now the obvious AD cmdlets would be Get-ADUser,Get-ADGroup & Get-ADComputer. So that got me thinking , just how many AD cmdlets have SearchBase as a parameter?

Get-Command -Module ActiveDirectory |
ForEach-Object{
   $psItem.Name |
   Where-Object {
        (Get-Command $psItem).ParameterSets.Parameters.Name -eq 'SearchBase'
   }
}

Turns out there are quite a few using SearchBase

  • Get-ADComputer
  • Get-ADFineGrainedPasswordPolicy
  • Get-ADGroup
  • Get-ADObject
  • Get-ADOptionalFeature
  • Get-ADOrganizationalUnit
  • Get-ADServiceAccount
  • Get-ADUser
  • Search-ADAccount

So I can have Intellisense on all these cmdlets? Awesome!!!

Intellisense completed the DistinguisedName on -SearchBase for me. No need to type it in, no errors, just select and go!

TabExpansionSearchBase

Here’s the result:

TabExpansionSearchBase-result

I’m sure you guys will find your own use for this… Thanks again Trevor for bring this to our attention! Good looking out for the community! Be sure to watch Trevor’s video for in depth explanation.

Hope it’s worth something to you…

Ttyl,

Urv

Pester script to validate GPOs Scope of Management

So here’s another spin on using Pester to validate operational readiness… 😉

Group policies can be pretty tricky! Troubleshooting can be a challenge. There might be even times that you start doubting yourself. Depending on the link order of your Policies, you might not get what you expected…

Operations is dynamic, things get moved around, enabled/disabled, blocked, name it and it’s bound to happen.

How about… some way to validate your GPOs Scope of Management! Once everything is working as it should, create a validation set you can verify later on. Trust me, I’ve been there… Using Pester will definitely give you that edge…

So I improvised a little on Ashley’s McGlone’s GPO Report and made a function Get-GPOsSoM. Just be sure to save it in the same folder as Domain-GPOSoM.Tests.ps1

Now for the fun part! 🙂

So here’s the result:

Pester Test GPO SoM

Now Imagine someone changed your GPO link order:

Pester Test GPO Change Link Order

Run Pester test script again:

Pester Test GPO Change Link Order -Detected

No more doubt! The link order has been tampered with! This is definitely a game changer for Operations!

My new motto : “If you can automate it, you should test it” 😛

Pester for everyone!

Hope it’s worth something to you

Ttyl,

Urv

Pester script to Test DNS Configuration

So I recently blogged about Configuring DNS zones and resource records. While going through my twitter feed, I stumbled upon this little gem by Kevin Marquette. He recently did a session on Pester and uploaded his demo. If you’re interested in Pester (as you should) you should definitely check it out!

So one of the demos was a eureka moment for me: The Active.Directory.System.DC.tests.ps1!

Wait you can do that? I thought Pester was about unit Framework testing not about validating script output. So I can test if my script did what I expected it to do? (Pause to let that sink in). Well alrighty then!!! 😛

So I decided to give it a go for the DNS Configuration.

And here’s a screenshot of the results:

Pester-DNS

So there’s more to Pester that meets the eye… Imagine the possibilities… No wonder Microsoft is shipping Pester with 2016…

Hope it’s worth something to you

Ttyl,

Urv

Configuring DNS zones and resource records

“Hey Irwin! Do you have a script to configure DNS autodiscover?” Eh, no not really… I’m assuming you’re doing something with PowerShell DNS cmdlets? 😉 And so begins another PowerShell journey…

My colleague Ofir is our Exchange guy.

“Ok so what exactly do you want to accomplish Ofir? I’m trying to automate registering some Resource records in DNS, but it isn’t working. I’d like to add some IPAddresses to a specific zone… “Ok let’s see what you’ve got!

Add-DnsServerResourceRecordA -Name "autodiscover" -ZoneName "domain.local" -AllowUpdateAny -IPv4Address "IP address 1","IP address 2","IP address 3" -TimeToLive 01:00:00

“So when I use the cmdlet directly it works. When I use varaiables it doesn’t… Ideally the code should be re-usable…”  Ofir’s words not mine… I’ll admit, I teared up a bit… Kids, they grow up so fast… Hehe…

I think we can do this…

So Ofir was using read-host to get ZoneName and IPvAddress. Ah! What a lovely opportunity to demonstrate params!

“Ok Ofir, instead of using read-host, we’re better off using parameters. Using [CmdletBinding()] gives you the possibility to use Write-Verbose, no extra charge!”

[CmdletBinding()]
Param(
   [string]$fqdn ='domain.local',
   [string[]]$ServerIPAddress
)

Now because the Resource record could be multi-valued we’ll go on and define a string array variable [string[]]$ServerIPAddress

“To make you’re code more readable we’ll just go ahead and create a hashtable we can use to splat your parameters.”

$dnsSplat = @{
   Name = 'AutoDiscover'
   Zonename = $fqdn
   AllowUpdateAny =  $true
   IPv4Address = $ServerIPAddress
   TimeToLive = '01:00:00'
}

“Now all we need to do it run the appropriate cmdlet and we’re good!”

Add-DNSServerResourceRecordA @dnsSplat

Ok, so this got Ofir started… Mind you there’s no error handling or anything of that sort…
We did some tinkering on the fly and this was the end result:

<#

Author: I.C.A. Strachan
Version:
Version History:

Purpose: Create AutoDiscover Zone and add ResourceRecord

#>
[CmdletBinding()]
Param(
   [string]$fqdn ='domain.local',
   [string[]]$ServerIPAddress= @('192.168.1.4', '192.168.1.5')
)

BEGIN{
    $dnsRRA = @{
       Name = 'AutoDiscover'
       Zonename = "autodiscover.$($fqdn)"
       AllowUpdateAny =  $true
       TimeToLive = '01:00:00'
    }

    $dnsPZ = @{
        Name = "autodiscover.$($fqdn)"
        ReplicationScope = 'Forest'
        DynamicUpdate = 'Secure'
    }

    Import-Module DNSServer -Verbose:$false
}

PROCESS{
    #Only Add Zone is count is zero (doesn't exists)
    If (@(Get-DnsServerZone $dnsPZ.name -ErrorAction SilentlyContinue ).Count -eq 0 ){
        Write-Verbose "Creating DNS Zone: $($dnsPZ.name)"
        Add-DnsServerPrimaryZone @dnsPZ
    }

    #Get string equivalent of all A records
    $RR = Get-DnsServerResourceRecord -ZoneName autodiscover.domain.local -RRType A |
    Out-String

    $ServerIPAddress | ForEach-Object {
        If (!$RR.Contains($_)){
            Write-Verbose "Adding resource record $_ to $($dnsPZ.name)"
            Add-DNSServerResourceRecordA @dnsRRA -IPv4Address $_
        }
    }
}

END{}

Ofir was quite happy! Nice! Another satisfied customer. So the other day asked him to send me the code for future reference…

This is what he sent me:

What??? This wasn’t the code I expected! Turns out Ofir had a lot more he needed to configure. Just pointing him in the right direction was sufficient to generate this! Awesome! Give a man a fish… 😉

Go Ofir! It’s fun to see colleagues get excited about PowerShell. Sometimes all that’s needed is just a nudge in the right direction…

Ttyl,

Urv

Creating PowerShell GUIs

I’m old school. I’m a big fan of the “Real men don’t click” club!

My PowerShell bestie, Michaja van der Zouwen, is all about the GUI! We would go back and forth about to GUI or not to GUI… Good times…

We got a great introduction in creating PowerShell GUI app at the recent DuPSUG meeting by none other than June Blender! Just google June Blender… We’re being spoiled here!

Back in the days June was also part of the “Real (wo)men don’t click” club. So what changed? I can totally relate to June’s story about providing a script that could resolve a contractors problem. Now you would think the manager would be grateful eh? Nope! They weren’t interested in learning or using PowerShell even if it solved their problem. The idea was too daunting for them. Enter GUI.

GUI took away that initial fear of learning something new. “Just run this and click this button!” Doesn’t get easier than that eh? So should we all be creating GUIs? Well you should at least know how to 😉 Hence the workshop!

So I’m not against GUI, but it is a different mindset when creating a GUI app. You really need to think in events. You still need to validate parameters, but you need to anticipate what a user’s next move could be. The user’s move needs to be processed by ‘event-handlers’. With a script I have some parameters, I validate them and I’m good! With a GUI you need to think ahead of what could happen if…

We used Sapien PowerShell Studio to create a small GUI app. June gave us some excellent Gotcha and Aha tips! Sapien PowerShell Studio makes creating the GUI easy! Once the GUI interface was created we added the script logic. The event-handlers are basically script blocks!

Here’s where you need to think ahead:

What do I want happen if the textbox value is empty? Then you shouldn’t be able to click the button. Ok… But what if someone enters spaces only? We should validate that and make sure the value isn’t empty or spaces. But what if there’s a lingering space somewhere? Make sure Trim your textbox value.

Sapien PowerShell Studio makes it easy to export the complete script. Just go to Deploy -> “Export To Clipboard”. Paste in ISE and run it! Works! Have look at the script, there’s a lot going on under the hood… Imagine creating that by hand…

All the script logic can be found under ‘User Generated Script’ comment block. The rest PowerShell Studio took care of…

As an introduction to creating PowerShell GUI scripts, mission accomplished!

Here’s the link to June’s github repository for more information.

Thanks June it was a pleasure meeting you in person! I’m more open to the idea of creating a GUI around scripts, only after putting up a fight though… Old habits die hard… Hehe…

Ttyl,

Urv