Monthly Archives: February 2016

Remove and Add Users to an Active Directory Group

The more people that recognize that I’ve made an investment in Windows PowerShell, the more these posts write themselves. I was recently asked by a previous colleague to help them make some modifications in Active Directory (AD). They needed to strip out all the users from a single AD group, and then add a bunch of them back that were, conveniently, stored in a text file. While you can compare the current users in the group with the ones you want to add, this post will assume it’s suitable to momentarily remove all the users from a specific AD group.

When I completed this, out of the kindness of my heart, and because I want to promote and teach PowerShell whenever possible, I sent the previous colleague an email with the five steps I had completed. They might be useful for others as well, so here we are. I think I’m getting a lunch out of this, too. While it might not be Chipotle, I like food, so I’m sure it’ll be suitable.

1. Export Users in the AD Group: This command will return the current members of the VPN-Users group and store them in a Csv file. While this will allow us to compare our final results, its original purpose was as my safety net in case I made a mistake and wanted to make the previous members, members again.

PS> $GroupName = 'VPN-Users'
PS> Get-ADGroupMember -Identity $GroupName | Export-Csv -Path C:\VPN-Users01Pre.csv -NoTypeInformation

2. Remove Users from Group: This next command removes all the members of the group (which I had checked were only users). It did this by piping each member of the group to a ForEach-Object loop that ran Remove-ADGroupMember against the current user. Had there been other object types, you’d have to use a Where-Object command in between these two commands (command 1 | Where-Object… | command 2), filtering on the ObjectClass. The Remove-ADGroupMember cmdlet is using the -Confirm parameter with the $false value, so there’s no need for manual confirmation of each removal.

PS> Get-ADGroupMember -Identity $GroupName | Foreach-Object {Remove-ADGroupMember -Identity $GroupName -Members $_ -Confirm:$false}

3. Add Users to Group: After I allowed a few moments for replication, I went ahead and added all the users in the text file I had been supplied by using the Get-Content command and piping each entry to the ForEach-Object and Add-ADGroupMember cmdlets. It threw two errors when it wasn’t able to find a couple users in AD. While I didn’t, we could’ve written in precautions in this command to avoid this error, or programmatically fixed the file prior to this command.

PS> Get-Content -Path C:\UserNames.txt | Foreach-Object {Add-ADGroupMember -Identity $GroupName  -Members $_}

4. Export Users in the AD Group: Now that we have all the old group members removed, and the new ones added, we can create a new export of the group members for comparison. This isn’t necessary, but helps to see who was removed and added, if we desire that kind of information and comparison.

PS> Get-ADGroupMember -Identity $GroupName | Export-Csv -Path C:\VPN-Users02Post.csv -NoTypeInformation

5Compare Before and After Group Memberships: The next command will reach into the SamAccountName column inside both Csv files and compare them. Results that indicate <= mean they are in the file on the left (the file as the value to -ReferenceObject parameter), and results that indicate => mean they are only in the file on the right (-DifferenceObject parameter). Don’t forget, you can always use the -IncludeEqual parameter if you want to see which users where there before and after.

Compare-Object -ReferenceObject ((Import-Csv -Path C:\VPN-Users01Pre.csv).SamAccountName) -DifferenceObject ((Import-Csv -Path C:\VPN-Users02Post.csv).SamAccountName)

There ya go. The previous colleague said they had a problem finding some good examples of doing this online, so here’s to hoping that this will help someone when it they need it. Just maybe, I’ll be back with the right way to do this, where the users that are going to be added back, never get removed in the fist place.

Automate App Server (Non Visual) Website Test

This is part II of this post: http://tommymaynard.com/quick-learn-automate-app-server-visual-website-test-2016. It might be beneficial to read that first.

It was minutes before my family needed to leave the house and start our Saturday, when my desire to monitor eight of my application servers hit. In a quick moment, I wrote three commands in three PowerShell consoles and left the house.

Before I show you what was in console one, I have to show and mention a couple functions on which it relied. These functions are a bit of a continuation of the link above. The Watch-MyApp function below, will visually and textually display indicators so that I know if my app servers’ websites are responding, or not. The -Visual parameter will open an instance of Internet Explorer for each server URL, so I can visually check the app servers’ websites (see the link to view this function).  Not using the -Visual parameter, which is how it’s used here, uses Invoke-WebRequest to determine a webpage’s status code. A 200 status code (OK response) means our webpage is up, and responding. If it’s not up, it’ll indicate a timeout warning. It could also produce a different status code, if the page is up, but produces something other than a 200 status code. Other more well-known status codes are the dreaded 404 (page cannot be found), or a 5xx error which indicates a problem with the web server. It may also be helpful to know that the $MyAppServers variable contains the default properties for five servers, returned from the Get-ADComputer cmdlet.

Function Watch-MyApp {
    Param (
        [switch]$Visual
    )
    
    If ($Visual) {
        $MyAppServers.Name | ForEach-Object {
            Open-InternetExplorer -Url "$_.myapp.mydomain.com"
        }
    } Else {
        $MyAppServers.Name | ForEach-Object {
            try {
                $StatusCode = (Invoke-WebRequest -Uri "http://$_.myapp.mydomain.com" -TimeoutSec 10).StatusCode
                "$StatusCode`: $_"
            } catch {
                Write-Warning -Message "$_"
            }    
        }
    }
 }

The first of my three consoles wrapped the function above, Watch-MyApp, in a never ending loop ($true is always true). Every minute it would get the date and time and write it to a log file. Immediately after that, it would run the function to get the status code of each web server, and append it to the same log file. A minute later and it does the same thing. Here’s the command and a sample from the log file it created.

Do {
    (Get-Date).ToString() | Out-File -FilePath 'C:\MyApp.txt' -Append
    Watch-MyApp | Out-File -FilePath 'C:\MyApp.txt' -Append
    Start-Sleep -Seconds 60
} While ($true)
2/21/2016 10:48:29 PM
200: appsrv01
200: appsrv02
200: appsrv03
200: appsrv04
200: appsrv05
2/21/2016 10:49:29 PM
200: appsrv01
200: appsrv02
200: appsrv03
200: appsrv04
200: appsrv05

The second console ran another endless Do-While loop. The difference, is that this loop’s job was to copy the file that was being updated by the command in the first console, to my Dropbox folder every ten minutes. Genius, right? While I could have, I opted to not have my first command write/overwrite the file directly in my Dropbox folder. I didn’t feel it was necessary to update Dropbox each minute for hours on end. When I was back home later, I changed this from ten minutes to 30 minutes, or 1800 seconds, as it was even less important to update Dropbox then.

Do {
    (Get-Date).ToString() | Out-File -FilePath 'C:\MyApp.txt' -Append
    Copy-Item -Path 'C:\MyApp.txt' -Destination 'C:\Users\tommymaynard\Dropbox\MyApp.txt' -Force
    Start-Sleep -Seconds 600
} While ($true)

What this meant is that while I was away, I was able to check Dropbox on my phone and quickly determine if there were any status codes other than a 200. Every ten minutes and there would be an update to my file that would include the status code results for each minute in the last ten.

The final console didn’t do much other than allow me to manually check the file in Dropbox, for something other than a date entry, and status code of 200. So far so good: None of the web apps returned anything more than a 200 status code. Maybe the change at the end of the day on Friday really did fixed things. Here’s the command I used to read the file and exclude lines that had a date and a 200 status code (all the lines unless there was a problem).

Get-Content -Path 'C:\MyApp.txt' | Where-Object {($_ -notlike '*2016*') -and ($_ -notlike '200*')}

But why visually scan the file myself, when PowerShell can do that too!? This third command could’ve also been an endless loop. It could’ve automated scanning the file for me, like I was doing already, and then could’ve been set up to send me an email using the Send-MailMessage cmdlet if it found something, other than the 200 status code. I could’ve avoided looking at the file in Dropbox and just watched my email. One better, and I could’ve had my command do email to text with a specially crafted email address. Here’s what I mean for US Verizon customers: http://www.verizonwireless.com/news/article/2013/06/computer-to-phone-text-messaging.html. Many days, it feels like PowerShell is only limited by what you can think do with it.

There have been times in my life where my wife will ask me, “How would people that don’t know computers, know how to do this?” I usually answer by saying, that “They wouldn’t,” or “I don’t know, I’m not that person.” The same thing applies here: “How would a Windows System Administrator know what to do if they hadn’t already learned PowerShell?” Those three commands might take someone new with PowerShell half a day to consider, and then write. Learn it while you don’t think you need it, because one day you will.

So, to recap, while I was away doing the family thing, my computer sat on the kitchen table at home, checked on eight app servers for me and updated a file in Dropbox, that I was able to check at times while we were away. PowerShell has a purpose, and without it, you’re losing yours.

Automate App Server (Visual) Website Test

To visually determine if a website is loading slowly, or not, you might open the browser, enter the URL, and note the speed at which the page loads. Well, since I write tools to speed things up, writing one for this need, seemed to make sense. Part of the work was already done, thanks to the little function below that I had already written. It’s a function called Open-InternetExplorer and you can likely guess what it does. If you feed it a URL as the value for the -Url parameter, it’ll open up that webpage, otherwise, it’ll just open to the default homepage.

Set-Alias -Name iexplore -Value Open-InternetExplorer
Function Open-InternetExplorer {
    Param ([string]$Url)
 
    If ($Url) {
        Start-Process -FilePath iexplore $Url
    } Else {
        Start-Process -FilePath iexplore
    }
}

If you didn’t already notice, I’ve also included an alias be set for this function. With that in place, I can also enter iexplore to invoke the Open-InternetExplorer function. Notice that the Start-Process cmdlets inside the function include iexplore as the value for the -FilePath parameter. This is the Internet Explorer executable, and not the function alias.

Okay, so now we know how we can quickly open a new IE browser and determine what webpage to load. Let’s assume the page I want to check is http://appsrv01.subdomain.mydomain.com. This means, I can enter Open-InternetExplorer http://appsrv01.subdomain.mydomain.com and IE will open to that webpage (on that server). I may use a load balanced, front end URL for users to access the application, such as http://myapp.subdomain.mydomain.com. While the app is important (as it is one of the servers), knowing that all the app servers are responding and loading the page quickly is helpful.

For the remaining examples, let’s assume I have a variable called $MyAppServers that contains the default properties for five servers, returned from the Get-ADComputer cmdlet.

PS> $MyAppServers = Get-ADComputer -Filter * -SearchBase 'OU=MyApp,DC=subdomain,DC=mydomain,DC=com'
PS> $MyAppServers.Name
appsrv01
appsrv02
appsrv03
appsrv04
appsrv05

Now, let’s combine the $MyAppServers variable, with the function (and the ForEach-Object cmdlet, as the function wasn’t written to accept multiple URLs), so that we can open each app server’s webpage. This will allow us to determine if any of the pages load slower than any others, or more importantly, to determine if a page doesn’t load at all. Here’s how we do that.

PS> $MyAppServers.Name | ForEach-Object {Open-InternetExplorer -Url "$_.subdomain.mydomain.com"}

Once this command is run, it’ll open an Internet Explorer browser window for each app URL. In my case (Windows 8.1), I can hover over the IE taskbar items and view a small image of each IE window. Notice in the image below that one of the application servers didn’t load. I’ll need to look into that server!

automate-app-server-visual-website-test01

While I haven’t yet, the command above could be added to its own function, so I don’t have to type it out each time, and instead can simply enter the function’s name, or alias. In closing, I’ll mention another small function I added to my profile. This one will dump all running instances of Internet Explorer, allowing me to avoid manually closing each IE window, or typing out the Get-Process–Stop-Process command that the function runs.

Set-Alias -Name diexplore -Value Stop-InternetExplorer
Function Stop-InternetExplorer {
    Get-Process -Name iexplore | Stop-Process
}

Keep PowerShell Cmdlets Powerful

I’ve seen what I’m about to show you done repeatedly in Windows PowerShell. With that thought in my mind, I’ve decided it’s time to officially write about it. The first time I noticed someone doing it, well, it was me. I did, however, write a correction to my team so they knew I was aware of my error, and as a hope they wouldn’t repeat it.

Those doing this may be new to PowerShell, but if you aren’t careful and don’t fully understand the capabilities of the cmdlets you use, then it’s possible you might make this mistake, too. What am I talking about? I’m talking about Invoke-Command and an improper way that it’s sometimes used.

Invoke-Command‘s purpose is to run a command, or commands, on remote computers and return the results back to the local computer. That said, it can be used on the local computer, as well; however, this is usually only necessary to check if PowerShell Remoting is working on the local computer. While I don’t normally do this in my examples, I’m piping my result of this example to Format-Table -AutoSize once they’re returned from the remote computer. This is so it’ll display better on this webpage.

Invoke-Command -Computer DC01 -ScriptBlock {Get-PSDrive -PSProvider FileSystem} | Format-Table -AutoSize
Name Used (GB) Free (GB) Provider Root              CurrentLocation PSComputerName
---- --------- --------- -------- ----              --------------- --------------
A                                 A:\                               DC01
C        12.91     26.75          C:\  Users\tommymaynard\Documents DC01
D                                 D:\                               DC01

This example of Invoke-Command connected to the remote computer DC01, ran a filtered Get-PSDrive command, returned the results to my computer, and then were formatted by the Format-Table cmdlet.

Now, let’s say we have… 23 computer names stored in the variable $Computers and we want to run the command we used above, against each computer. What so many people seem to do is wrap Invoke-Command in a Foreach construct (think: loop). I’m guessing, because I’ve made the error myself, that it’s because someone learned about Foreach first. Like I said, I discovered my error on my own, and only moments later. It didn’t wake me at 2 a.m. in a cold sweat after two months, which could’ve been possible.

Here’s how not to do this, and again, $Computers is holding the names of 23 computers.

Foreach ($Computer in $Computers) {
    Invoke-Command -ComputerName $Computer -ScriptBlock {Get-PSDrive -PSProvider FileSystem}
}
Name           Used (GB)     Free (GB) Provider      Root                                CurrentLocation PSComputerName
----           ---------     --------- --------      ----                                --------------- --------------
C                  20.47         59.18               C:\                                 ...rd\Documents DC02
D                                                    D:\                                                 DC02
A                                                    A:\                                                 WEB01
C                  50.36         29.30               C:\                                 ...rd\Documents WEB01
D                                                    D:\                                                 WEB01
A                                                    A:\                                                 SQL01
C                  53.59         26.06               C:\                                 ...rd\Documents SQL01
D                                                    D:\                                                 SQL01
... # Not all results included.

What we’ve done here is force Invoke-Command to run against only one computer at a time. During each iteration of the Foreach loop, Invoke-Command runs against the computer name currently stored in $Computer. This variable is updated to the next computer name in the variable at the start of each loop. It’s like this: connect to DC02 and run the command. Now, connect to WEB01 and run the command. Are you done, Invoke-Command? Okay then, now Foreach says to run the same command against the computer SQL01. That’s not how this cmdlet was designed to be used.

Before we go any further, I wrapped this command inside the Measure-Command cmdlet to determine how long it took my system to run this against the computers in $Computers. It took nearly 30 seconds. While that’s not an eternity, we’re only talking about 23 computers, and we’re only talking about a single command.

Measure-Command -Expression {
    Foreach ($Computer in $Computers) {
        Invoke-Command -ComputerName $Computer -ScriptBlock {Get-PSDrive -PSProvider FileSystem}
    }
}
Days : 0
Hours : 0
Minutes : 0
Seconds : 27
Milliseconds : 513
Ticks : 275132689
TotalDays : 0.000318440612268519
TotalHours : 0.00764257469444444
TotalMinutes : 0.458554481666667
TotalSeconds : 27.5132689
TotalMilliseconds : 27513.2689

Now, let’s set this command up the proper way. The ComputerName parameter of Invoke-Command can take a collection of computers. It should be said that many cmdlets can take more than one computer as a value to their ComputerName parameter. The difference is that Invoke-Command can run against all of the 23 computers at the same time. In fact, the default throttle limit—the number of computers in which the command will run against simultaneously—is 32. It can be changed by including the ThrottleLimit parameter, such as -ThrottleLimit 50 or -ThrottleLimit 15.

Now, here’s how this command should’ve been written.

Invoke-Command -ComputerName $Computers -ScriptBlock {Get-PSDrive -PSProvider FileSystem}
Name           Used (GB)     Free (GB) Provider      Root                                CurrentLocation PSComputerName
----           ---------     -------u-- --------      ----                                --------------- --------------
A                                                    A:\                                                 DC02
A                                                    A:\                                                 WEB01
C                  41.72         37.93               C:\                                 ...rd\Documents WEB01
C                  41.13         38.52               C:\                                 ...rd\Documents DC02
D                                                    D:\                                                 DC02
D                                                    D:\                                                 WEB01
A                                                    A:\                                                 SQL01
C                  46.75         32.91               C:\                                 ...rd\Documents SQL01
D                                                    D:\                                                 SQL01
... # Not all results included.

I measured this command five times, and the average of those five runs was only 2.8 seconds. Remember, the Foreach loop took almost 30 seconds to get the same results. This is due to the fact that, again, Invoke-Command will work with the remote computers simultaneously (when it’s not inside a Foreach). There’s never any waiting to run the command on any additional computers unless there’s more computers than the value of ThrottleLimit.

Please keep the topic in this post in mind, as it’s possible to momentarily forget this feature just long enough to wrap the Invoke-Command cmdlet in a Foreach, or other looping construct.

 

Determine If There’s a Current PowerShell Remoting Session

Ever need to reboot a server and worry someone else may be actively logged on? In this situation, you can either check Task Manager > Users, or use the quser.exe command-line tool. If you’re not familiar with the command-line tool quser.exe, it can be used against a remote computer, as in the example below.

PS> quser.exe /server DC01
 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
 adminbob                                  2  Disc      2+01:17  1/29/2016 8:58 PM

You can use this command-line tool on a local computer, as well, in order to see if anyone else is logged on. All you need to do is enter quser.exe (drop the /server switch [which indicates the remote server to query]), and the remote computer name. Since quser.exe is located in C:\Windows\System32, you don’t even need to include the .exe. The Path variable, $env:PATH, will assist in correctly determining the executable.

The problem is that this command-line tool, and Task Manager, don’t tell us if anyone has a current PowerShell Remoting session to the server. That’s where the Get-WSManInstance cmdlet can help. Here’s an example of using this cmdlet to check our DC01 server — the same server as in the example above.

PS> Get-WSManInstance -ComputerName DC01 -ResourceURI Shell -Enumerate
PS>

Because it didn’t return any information, we can safely assume there are no active PS Remoting sessions on DC01. Had there been, it would have returned something like the results below.

PS> Get-WSManInstance -ComputerName DC01 -ResourceURI Shell -Enumerate

rsp             : http://schemas.microsoft.com/wbem/wsman/1/windows/shell
lang            : en-US
ShellId         : AB4D6A3B-213B-20F6-A61C-9CCAG41A1C2E
Name            : Session1
ResourceUri     : http://schemas.microsoft.com/powershell/Microsoft.PowerShell
Owner           : MYDOMAIN\adminbill
ClientIP        : 10.10.10.20
ProcessId       : 10192
IdleTimeOut     : PT7200.000S
InputStreams    : stdin pr
OutputStreams   : stdout
MaxIdleTimeOut  : PT2147483.647S
Locale          : en-US
DataLocale      : en-US
CompressionMode : XpressCompression
ProfileLoaded   : Yes
Encoding        : UTF8
BufferMode      : Block
State           : Connected
ShellRunTime    : P0DT0H0M6S
ShellInactivity : P0DT0H0M4S
MemoryUsed      : 70MB
ChildProcesses  : 0

The default properties are much more than I need. Here’s a filtered down version of the cmdlet’s properties using the Select-Object cmdlet. In my opinion, these properties are the ones that include the most desirable information.

PS> Get-WSManInstance -ComputerName DC01 -ResourceURI Shell -Enumerate |
>>> Select-Object Name,Owner,ClientIP,State

Name         Owner                  ClientIP        State
----         -----                  --------        -----
Session1     MYDOMAIN\adminbill     10.10.10.20     Connected

It seems I have a difficult time remembering the required parameters in this command; therefore, I wrapped the whole thing in a function and placed it in my profile. This, in order to make sure that I’ll never remember them. My function also allows me to run this command against multiple remote computers at nearly the same time. The -ComputerName parameter of Get-WSManInstance only accepts a single computer per execution, so wrapping this cmdlet in a Foreach construct (within the function), allows us to work around this behavior. Take a look at the function and the example below, as the function runs against three different computers.

Function Get-PSRemotingSession {
    Param(
        [string[]]$ComputerName
    )

    Foreach ($Computer in $ComputerName) {
        Get-WSManInstance -ComputerName $Computer -ResourceURI Shell -Enumerate |
            Select-Object -Property @{N='ComputerName';E={$Computer}},Name,Owner,ClientIP,State
    }
}
PS> Get-PSRemotingSession -ComputerName DC02,WEB01,DC03

ComputerName : DC02
Name         : Session1
Owner        : MYDOMAIN\admindave
ClientIP     : 10.10.10.22
State        : Connected

ComputerName : DC03
Name         : Session1
Owner        : MYDOMAIN\admindave
ClientIP     : 10.10.10.22
State        : Connected

These results indicate that two of the three computers have active PS Remoting sessions. In this case, the two sessions were initiated by MYDOMAIN\admindave. The IP is not the remote computer’s IP, such as DC02 and DC03, but instead the IP from the connecting computer (Dave’s computer).

Keep this cmdlet in mind when you’re doing anything that will restart the WinRM service, to include restarting the server. Restarting this service on a computer where there’s an active PS Remoting session, will instantly break the remoting session.