How to protect all existing Organizational Units (OUs) in your Active Directory domain from Accidental Deletion by using PowerShell

We recently took on a new hire, although I was confident in their ability in managing Active Directory I wanted to take an extra step in protecting Organizational units from deletion.  I was sure that I could do this quickly using PowerShell instead of right-clicking each of our 80 odd OUs and going into their properties.

To do this we need to open the Active Directory Module for Windows PowerShell as an administrator.  Since I began in my System Admin role, I was creating OUs that were protected, so I only really needed to do this to the ones that were already here.  So first we need to work out what OUs are not protected from this list using PowerShell I can easily pipe it into the command we need to issue to protect the OUs

The first command below will output a list of all OUs currently not protected.

Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | 
where {$_.ProtectedFromAccidentalDeletion -eq $false} | ft

This command does the above but also sets the ProtectedFromAccidtenalDeletion to True.

Get-ADOrganizationalUnit -filter * -Properties ProtectedFromAccidentalDeletion | 
where {$_.ProtectedFromAccidentalDeletion -eq $false} | Set-ADOrganizationalUnit 
-ProtectedFromAccidentalDeletion $true

Once this command is issued, all the Organizational Units in our Active Directory have become protected and should help prevent you from getting into those sticky situations where someone (could be you) from deleting one by mistake.

Remove all disabled user from an Active Directory Group with Power Shell using Quest Active Roles AD Management

The following code snippet which I ran through PowerShell ISE (learn how to get it on Windows Server) will remove all disabled users from a particular group.  Useful for the end of year / start of year clean up in a school environment.

You will need the ActiveRoles Management Shell for Active Directory, available by clicking here which were made by Quest Software, now DELL.

Add-PSSnapin Quest.ActiveRoles.ADManagement

Get-QADGroup -SearchRoot "" | Foreach-Object {
     $group = $_
     Get-QADGroupMember -Identity $group -Disabled -Type User | Foreach-Object{
         Write-Host "Removing '$($_.Name)' from group '$group'" -Foreground Green
         Remove-QADGroupMember -Identity $group -Member $_ 
     }
 }

Swap out with a distinguished name of the group you want to remove disabled users from.  Once you execute it, it will run through the group and remove any user objects that are disabled.

Getting Folder Sizes and number of items in a Mailbox for a particular user on Microsoft Exchange using PowerShell

Recently one of our high-end users was going over their mailbox limit. In helping them to cut down I like to let them know what folders are using up the most of their quota (generally it is their sent items folder, but sometimes not). Executing the below PowerShell command in an Exchange Administration Shell gave me a nice ordered list (see output below) of folders in their mailbox along with an associated size and number of items.

Get-MailboxFolderStatistics -Identity <username> | Sort-Object FolderSize 
-Descending | FT folderpath, foldersize, ItemsinFolder -autosize

After executing the above PowerShell you’ll get an output similar to the below

FolderPath                    FolderSize                  ItemsInFolder
----------                    ----------                  -------------
/Inbox                        32.89 MB (34,486,717 bytes)           158
/Carbon Copies                16.9 MB (17,725,567 bytes)            168
/Sent Items                   685.3 KB (701,797 bytes)               14
/Deleted Items                554.4 KB (567,723 bytes)              189
/Calendar                     27.6 KB (28,267 bytes)                  7
/Contacts                     1.492 KB (1,528 bytes)                  4
/Drafts                       138 B (138 bytes)                       1
/Sync Issues/Local Failures   0 B (0 bytes)                           0
/Sync Issues/Conflicts        0 B (0 bytes)                           0
/Sync Issues                  0 B (0 bytes)                           0
/Sync Issues/Server Failures  0 B (0 bytes)                           0

From this I can could then give to the user so they could clear out their mailbox. Hope that helps someone out.

An error occurred while attempting to start the selected virtual machine(s) The security ID structure is invalid (0x80070539)

So I was recently working with some really old Virtual machines in a development environment that came across from another organisation. One particular virtual machine gave me an error message when I tried to start it up “An error occurred while attempting to start the selected virtual machine(s)… The security ID structure is invalid (0x80070539)”.  When this happens, Hyper-V basically doesn’t have permission to start the selected virtual machines under the user.  A quick administrative PowerShell cmdlet will grant me or a user permission and allow us to start the VM up;

Grant-VMConnectAccess -VMName "Name of VM not starting" -UserName 
"DOMAIN\Username of current user"

Changing -VMName to match the virtual machine giving you the error and a DOMAIN\Username of the user you are now logged on as.

Once you issue this command the virtual machine will start without any issues.

Generate Mailbox Size and Usage Report using PowerShell for Exchange 2010 / 2013

So I recently wanted to create a report to show us who was using up the most space on our mailbox servers, previous administrators had either done away for limits for mailboxes or had set them to be very very generous and our users weren’t really the ones to either keep their mailbox tidy or archive items away.

I knew the quick and easy solution would be powershell and then getting the output to either a CSV file or HTML.  So a bit of a look around TechNet for Get-MailboxStatistics got me the commands I needed, but what else could I select out of that.  After a bit more digging I found a list on MSDN for MailboxStatistics members which allowed me to extract exactly what I was after.  After putting all that together, I cam up with the following

Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select DisplayName,
TotalItemSize,ItemCount,Database,LastLogonTime,LastLoggedOnUserAccount | Sort 
TotalItemSize -Descending | ConvertTo-Html -Title "Mailbox Stats"| 
Out-file "C:\MailboxStatistics.html"

That gave me a nice HTML page output, you could easily improve on this with colours depending on outputs from StorageLimitStatus or LastLogonTime where we found that some mailboxes hadn’t even been used.

Allowing anonymous relay on Exchange 2007/2010 on connectors for programs to send via SMTP using your Mail servers and how to secure it for internal use only.

I was recently helping out a colleague at another school as they were having difficulty in a specialised application sending e-mails to external addresses.  After a bit of investigating we found that the send connector configured for internet e-mail wasn’t allowing anonymous connections to it (which is dangerous) but since this particular application didn’t allow us to specify authentication details we were forced to enable anonymous relay for this connector.

I will first show you the PowerShell command that we used to grant the anonymous permissions for the connector that you specify:

Get-ReceiveConnector “Default SBSSERVER” |
Add-ADPermission -User “NT AUTHORITY\ANONYMOUS LOGON”
-ExtendedRights “Ms-Exch-SMTP-Accept-Any-Recipient”

Now the above is really one command getting piped into another, so first of all we are specifying a particular receive connector, in this case Default SBSSERVER (change this to reflect the connector you want to modify).  We are then simply giving rights to anonymous logons (anyone) telling exchange to accept any recipient.

Now as for securing this connector, I would strongly suggest creating a separate one for this particular application (for example Sales App Connector).  We then add incoming IP restrictions, by editing the properties of the receive connector and adding entries to Receive mail from remote servers that have these IP addresses using either specific IP addresses or IP ranges in CIDR notation (so 10.1.0.0/16).

And there you have it, allowing anonymous connections / relay for internal applications to use.

Adding a ToolTip to a Picture Control in VB.Net

So here is a quick one. I was recently developing a small application written in VB.Net and went to add a tool tip to a picture control displaying the Windows UAC Shield but found that I couldn’t.  So after a litle poke around I found that I could initialise the ToolTip method and apply to the control that I wanted.  The following snippet is assigning the tooltip to my picture control (in this case picShield):

Dim tt As New ToolTip()
tt.SetToolTip(picShield, "Requires Administrative Privilages")

The above will then attach itself at run time to the control you specify and instance a Tool Tip for it.

Installing the PowerShell ISE (Integrated Scripting Environment) on Windows Server 2008 R2

I was recently looking at modifying our SharePoint warm-up script as we had found out that it wasn’t working as it should be.  So I went to fire up the small but useful PowerShell ISE and found that it wasn’t available.  So there are two ways to go about getting it installed.

First off is running the Windows Add Feature under Server Manager.  You will find the Windows PowerShell ISE and be able to tick and install the feature.  The other method which is quite easy is to use PowerShell.

First off we need to import the ServerManager module into PowerShell and then we can go ahead and add the ISE feature.  The following snippet will do it all for you via PowerShell.

Import-Module ServerManager
Add-Windowsfeature PowerShell-ISE

And that is all you have to do to get the wonderful PowerShell ISE going under Windows Server. Hope that helps.

Increase the number of visible users per page on group creation and user selection screen in Moodle 2.2

So we had a query come through our Help Desk recently to ask if we can increase the users in the user selection box as staff members were having difficulty managing their classes and creating groups as they couldn’t CTRL click and had to type in the names of their students. So I started having a dig around the code in Moodle to find out if we can change the default value.

After poking around the source code and looking at some search results on Google, I found the file that was needed and it can be found in user/selector/lib.php – Line: 740

So we want to go to line and change MAX_USERS_PER_PAGE to equal what we want (a higher value, and in this case we gave it 500). The following is an extract of what we are changing.

/**
 * User selector subclass for the list of users who are not in a certain group.
 * Used on the add group members page.
 */
class group_non_members_selector extends groups_user_selector_base {
    const MAX_USERS_PER_PAGE = 500;

Save the file and now reload your group creation page and you should now be able to select multiple users in a large user base list. Also, it is important to note that the MAX_USERS_PER_PAGE variable is in multiple places and affects different user selection boxes depending on where you edit it.

How to convert Hex Colour Codes into RGB Colour Codes using PHP

I was recently working on a web based piece of software that had some colour settings stored in a database table which were stored as hexadecimal colour code values. I needed a quick way to convert them into RGB (Red, Green, Blue) values so that I could use them in creating an image using PHPs builtin GD so after a quick search on Google found nothing that I was really after I decided to write my own. The difficulty was that colours were inputted by both other developers and a jQuery colour picker which meant that there was a mix of both shorthand and standard hexadecimal colour codes. I get past this little hiccup by simply counting the length of the hex string and running either a bitwise operation or a hexadecimal conversion. Anyway onto the function.

Firstly, we need to define the function.  We will have two variables, one being the actual hexadecimal colour code and the other whether we wish to return as a String or Array.

function hex2RGB($hexStr, $returnAsString = false) {
    $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr);
    $rgbArray = array();

After this we simply grab the variable of the function which should be our Hex colour code and check the length.  If the length is 6 then we are able to use PHPs bitwise operators to quickly convert the colour codes into the RGB values we are after. Using bitwise operators results in lower overhead and therefore leads to a faster output.

    if (strlen($hexStr) == 6) { // Proper Hex convert using bitwise operation
        $colorVal = hexdec($hexStr);
        $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
        $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
        $rgbArray['blue'] = 0xFF & $colorVal;
    }

Or if it is a shorthand hex colour code (ie: #FFF) then we can perform manipulation on the string to first extend it and then perform a conversion.

elseif (strlen($hexStr) == 3) { // If shorthand perform string manipulations
        $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
        $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
        $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
    }

or else if our string matches neither of the above then return nothing (false).

else {
        return false; // Invalid hex color code
    }

Now that we have our converted code, we need to return it back to what called for the code with the following in either an array or as a string.

    // Returns the rgb string or the associative array as specified
    return $returnAsString ? implode(",", $rgbArray) : $rgbArray;
}

We can call the above function in two ways

hex2RGB(“#FF0”) would output array( red =>255, green => 255, blue => 0)
or
hex2RGB(“#FF0”, true) would output 255,255,0

So there we have a completed function to convert hex colour values into RGB.