Archive

Posts Tagged ‘Powershell’

What are the Azure DirSync Cmdlets?

June 24, 2014 4 comments

As you may have seen, DirSync’s PowerShell functionality can now be called from the “Import-Module” cmdlet instead of running a custom DirSyncConfigShell.psc1 file. If we look at this new module, we can see 25 DirSync-related cmdlets:

DirSync PowerShell Module

Notice the screenshot is actually listing the commands of the Microsoft.Online.Coexistence.PS.Config module, not “DirSync”. That is because the DirSync module is a wrapper of sorts, calling “%programfiles% \Windows Azure Active Directory Sync\dirsync\DirSync.psd1″ on your behalf. The DirSync module itself contains no cmdlets.

So, what do these cmdlets do anyway? Not all of them are well documented online, so you should start with the help file. Run the below command to generate an output similar to the following table:

ipmo DirSync
gcm -m Microsoft.Online.Coexistence.PS.Config | get-help | select name, synopsis | epcsv $env:userprofile\desktop\DirSyncCmdlets.csv -notype


Name

Synopsis

Disable-DirSyncLog

This commandlet is used to disable logging for the Azure Active Directory Sync tool.

Disable-MSOnlineObjectManagement Disable-MSOnlineObjectManagement -Credential <pscredential> [-ObjectTypes <string[]>] [-WhatIf] [-Confirm] [<CommonParameters>]
Disable-MSOnlinePasswordSync Disable-MSOnlinePasswordSync -Credential <pscredential> [-WhatIf] [-Confirm] [<CommonParameters>]
Disable-MSOnlineRichCoexistence Disable-MSOnlineRichCoexistence -Credential <pscredential> [-WhatIf] [-Confirm] [<CommonParameters>]
Disable-OnlinePasswordWriteBack

This commandlet is used to disable writing back user password resets from cloud to onpremise Active Directory.

Disable-PasswordSyncLog

This commandlet is used to disable logging for the Password Sync feature of the Azure Active Directory Sync tool.

Enable-DirSyncLog

This commandlet is used to configure the logging level for the Azure Active Directory Sync tool.

Enable-MSOnlineObjectManagement Enable-MSOnlineObjectManagement -ObjectTypes <string[]> -TargetCredentials <pscredential> -Credential <pscredential> [-WhatIf] [-Confirm] [<CommonParameters>]
Enable-MSOnlinePasswordSync Enable-MSOnlinePasswordSync -Credential <pscredential> [-WhatIf] [-Confirm] [<CommonParameters>]
Enable-MSOnlineRichCoexistence Enable-MSOnlineRichCoexistence -Credential <pscredential> [-WhatIf] [-Confirm] [<CommonParameters>]
Enable-OnlinePasswordWriteBack

This commandlet is used to enable writing back user password resets from cloud to onpremise Active Directory.

Enable-PasswordSyncLog

This commandlet is used to configure the logging level for the Password Sync feature of the Azure Active Directory Sync tool.

Get-CoexistenceConfiguration

Gets a configuration information from the Microsoft Online Coexistence Web Server

Get-DirSyncConfiguration Get-DirSyncConfiguration -TargetCredentials <pscredential> [<CommonParameters>]
Get-DirSyncLogStatus

This commandlet is used to retrieve the current logging level for the Azure Active Directory Sync tool.

Get-OnlinePasswordWriteBackStatus

This commandlet is used to obtain the current status of writing back user password resets from cloud to onpremise Active Directory.

Get-PasswordSyncLogStatus

This commandlet is used to retrieve the current logging level for the Password Sync feature of the Azure Active Directory Sync tool.

Get-PreventAccidentalDeletes

This commandlet is used to retrieve the current status of the object deletion threshold for DirSync.

Set-CoexistenceConfiguration

Configures Microsoft Online Directory Synchronization Tool.

Set-CompanyDirSyncFeatures Set-CompanyDirSyncFeatures -TargetCredentials <pscredential> -FeaturesFlag <int> [<CommonParameters>]
Set-DirSyncConfiguration Set-DirSyncConfiguration -TargetCredentials <pscredential> -DirSyncConfiguration <CloudDirSyncConfiguration> [<CommonParameters>]
Set-FullPasswordSync

Resets the password sync state information forcing a full sync the next time the service is restarted.

Set-PreventAccidentalDeletes

This commandlet is used to enable or disable the object deletion threshold for DirSync.

Start-OnlineCoexistenceSync

Starts synchronization with Microsoft Online

Update-MSOLDirSyncNetworkProxySetting

Updates the directory sync service to use the current user’s http proxy settings.

The de-”magicification” of DirSync is definitely a good thing for all Azure customers.  Having said this, I’d still keep the Codeplex FIM modules around, since they do offer a lot more control of and visibility into the underlying FIM Sync Service.

As time allows, I will return with more detail on each of the above DirSync cmdlets; so long for now!

DirSync 1.0.6593.0012

February 3, 2014 4 comments

Late Monday, Microsoft released another update to the DirSync software, this time with a build number of 6593.0012. You can download it in from the usual link.

DirSync 1.0.6593.0012

As with previous DirSync updates, there has been no official announcement of the release, however the “use at your own risk” Wiki does mention one of the new features:

Version 6593.0012
Date Released 2/3/2014
Notable Changes

New features:

  • Additional Attributes are synchronized on User and Contact objects

Attributes documented here

The new attributes referenced in the link are userCertificate and userSMIMECertificate. Interestingly pwdLastSet was also added, however there is no mention of that one in the article. These additions serve an unknown purpose for now, however one might speculate that they are in support of new capabilities soon to be available in the service?!

Before you upgrade, you may wish to get a “before and after” review of the attribute inclusion list. The best way to review this is in the “Configure Attribute Flow” area of each management agent. At the end of this post, I have also shared an experimental PowerShell method of getting this information.

It is noteworthy that the author of this update, a Microsoft Program Manager for DirSync, is linking to yet another community wiki page instead of the seemingly defunct Knowledge Base article KB-2256198. Sadly, it would appear that the crumbling integrity of the TechNet/Support documentation may be latest casualty in a growing list of IT Pro-related cuts Microsoft has made along their quest to the cloud…

<#
Description:
This script counts and dumps the attribute inclusion lists from each MA.
It does not evaluate attribute flow or applicable object types.

February 3 2014
Mike Crowley

http://mikecrowley.us

#>

#Import Modules
Import-Module SQLps -WarningAction SilentlyContinue

#Get SQL Info
$SQLServer = (gp 'HKLM:SYSTEM\CurrentControlSet\services\FIMSynchronizationService\Parameters').Server
if ($SQLServer.Length -eq '0') {$SQLServer = $env:computername}
$SQLInstance = (gp 'HKLM:SYSTEM\CurrentControlSet\services\FIMSynchronizationService\Parameters').SQLInstance
$MSOLInstance = ($SQLServer + "\" + $SQLInstance)

#Get Management Agent Attribute Info
[xml]$OnPremAttributes = (Invoke-Sqlcmd -MaxCharLength 10000 -ServerInstance $MSOLInstance -Query "SELECT attribute_inclusion_xml FROM [FIMSynchronizationService].[dbo].[mms_management_agent] WHERE [ma_name] = 'Active Directory Connector'").attribute_inclusion_xml
[xml]$CloudAttributes = (Invoke-Sqlcmd -MaxCharLength 10000 -ServerInstance $MSOLInstance -Query "SELECT attribute_inclusion_xml FROM [FIMSynchronizationService].[dbo].[mms_management_agent] WHERE [ma_name] = 'Windows Azure Active Directory Connector'").attribute_inclusion_xml
$ADAttributes = $OnPremAttributes.'attribute-inclusion'.attribute
$AzureAttributes = $CloudAttributes.'attribute-inclusion'.attribute

#Output to Screen
Write-Host $ADAttributes.count "Attributes synced from AD to the Metaverse" -F Cyan
Write-Host $AzureAttributes.count "Attributes synced from the Metaverse to Azure" -F Cyan
Write-Host "See" $env:TEMP\DirSyncAttributeList.txt "for detail" -F Cyan

#Output to File
"******AD Attributes******" | Out-File $env:TEMP\DirSyncAttributeList.txt
$ADAttributes | Out-File $env:TEMP\DirSyncAttributeList.txt -Append
" "| Out-File $env:TEMP\DirSyncAttributeList.txt -Append
"******Azure Attributes******" | Out-File $env:TEMP\DirSyncAttributeList.txt -Append
$AzureAttributes | Out-File $env:TEMP\DirSyncAttributeList.txt -Append

##END

Exchange Proxy Address Report Update

November 15, 2013 2 comments

I’ve made an update to the popular “Exchange Proxy Address (EmailAddresses) Report” script.  If you’re into in that sort of thing, check it out:

http://mikecrowley.wordpress.com/2012/04/16/exchange-proxy-address-alias-report

Sample output to screen

Sample output shown in Excel

Dirsync: Determine if Password Sync is Enabled

October 22, 2013 1 comment

For those not interested in the complete DirSync Report I published last week, now you can run just the Password Hash Sync portion, in a script I published here: Dirsync: Determine if Password Sync is Enabled.

For deployments with remote SQL installations: As with the previous report, note that we make use of the SQL PowerShell Module, which must be present on the computer.

Sample Output(s)

DirSync “Busted Users” Report

October 17, 2013 6 comments

If you administer DirSync for your organization, you likely have seen emails like this, indicating some of your users didn’t sync.

DirSync Error Email

It can be a frustrating email, since the “error description” is for some reason blank and the “On-premises object ID” column is not something that’s easy to correlate to a user account within your Active Directory. There are also application event log entries (FIMSynchronizationService #6111 and Directory Synchronization #0), but again these aren’t exactly rich with detail.

Many of you know that DirSync is actually a customized installation FIM 2010 R2′s Synchronization Service. Within the miisclient.exe console, you can look at your most recent “Export” job and examine the errors one at a time.

Miisclient.exe Console


(By the way, this is actually the place to go if you wanted to configure filtering for directory synchronization.)

Using this console certainly works, but it’s not an efficient way to resolve errors. Microsoft seems to acknowledge this, but falls short of a fix with that email, in my opinion. Instead of wearing out your mouse, I propose you use the PowerShell script I have written below. Within, I leverage the free FimSyncPowerShellModule which you’ll need to download and copy to:

…\System32\WindowsPowerShell\v1.0\Modules\FimSyncPowerShellModule\FimSyncPowerShellModule.psm1

Once you’ve copied the module, you’re ready to run the report, which can be downloaded here.

Here is a sample output, followed by the code itself.

Sample Output

<#
Description:
This script generates a list of users who are failing to export to Azure AD.

This script makes use of the FimSyncPowerShellModule

https://fimpowershellmodule.codeplex.com/

(Download and copy to C:\Windows\System32\WindowsPowerShell\v1.0\Modules\FimSyncPowerShellModule\FimSyncPowerShellModule.psm1)

October 18 2013
Mike Crowley

http://mikecrowley.us

#>

#Import the FimSyncPowerShellModule Module
ipmo FimSyncPowerShellModule

#Get the last export run
$LastExportRun = (Get-MIIS_RunHistory -MaName 'Windows Azure Active Directory Connector' -RunProfile 'Export')[0]

#Get error objects from last export run (user errors only)
$UserErrorObjects = $LastExportRun | Get-RunHistoryDetailErrors | ? {$_.dn -ne $null}

$ErrorFile = @()

#Build the custom Output Object
$UserErrorObjects | % {
 $TmpCSObject = Get-MIIS_CSObject -ManagementAgent 'Windows Azure Active Directory Connector' -DN $_.DN
 [xml]$UserXML = $TmpCSObject.UnappliedExportHologram
 $MyObject = New-Object PSObject -Property @{
 EmailAddress = (Select-Xml -Xml $UserXML -XPath "/entry/attr" | select -expand node | ? {$_.name -eq 'mail'}).value
 UPN = (Select-Xml -Xml $UserXML -XPath "/entry/attr" | select -expand node | ? {$_.name -eq 'userPrincipalName'}).value
 ErrorType = $_.ErrorType
 DN = $_.DN
 }
 $ErrorFile += $MyObject
 }

$FileName = "$env:TMP\ErrorList-{0:yyyyMMdd-HHmm}" -f (Get-Date) + ".CSV"
$ErrorFile | select UPN, EmailAddress, ErrorType, DN | epcsv $FileName -NoType

#Output to the screen
$ErrorFile | select UPN, EmailAddress, ErrorType, DN

Write-Host
Write-Host $ErrorFile.count "users with errors. See here for a list:" -F Yellow
Write-Host $FileName -F Yellow
Write-Host

DirSync Report

October 16, 2013 7 comments

Azure Active Directory Sync (DirSync) seems so simple on the surface doesn’t it?  “Next, Next, Finish”, right?  Ha!  If you’ve ever had to revisit your DirSync server to troubleshoot or make a configuration change, you know there can be more than meets the eye.  A lot of useful information happens to be scattered across various registry keys, SQL tables and XML files.  If you’re not familiar with the FIM Management Console, and these other locations it might be hard to see what’s going on.

Here’s a free script that aims to help by creating a dashboard highlighting useful DirSync configurations.  See the image below for a sample output.  Before you run it you should be aware of the limitations listed in the “known issues” area of the script.

DirSync Report


You can Review the script below or download it and try it for yourself!

<#
Description:
This script gathers DirSync information from various locations and reports to the screen.

November 5 2013
Mike Crowley

http://mikecrowley.us

Known Issues:
1) All commands, including SQL queries run as the local user.  This may cause issues on locked-down SQL deployments.
2) For remote SQL installations, the SQL PowerShell module must be installed on the dirsync server.
    (http://technet.microsoft.com/en-us/library/hh231683.aspx)
3) The Azure Service account field is actually just the last account to use the Sign In Assistant.
    There are multiple entries at that registry location.  We're just taking the last one.
4) Assumes Dirsync version 6385.0012 or later.

#>

#Console Prep
cls
Write-Host "Please wait..." -F Yellow
ipmo SQLps

#Check for SQL Module
if ((gmo sqlps) -eq $null) {
    write-host "The SQL PowerShell Module Is Not loaded.  Please install and try again" -F Red
    write-host "http://technet.microsoft.com/en-us/library/hh231683.aspx" -F Red
    Write-Host "Quitting..." -F Red; sleep 5; Break
    }

#Get Dirsync Registry Info
$DirsyncVersion = (gp 'hklm:SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft Online Directory Sync').DisplayVersion
$DirsyncPath = (gp 'hklm:SOFTWARE\Microsoft\MSOLCoExistence').InstallPath
$FullSyncNeededBit = (gp 'hklm:SOFTWARE\Microsoft\MSOLCoExistence').FullSyncNeeded
$FullSyncNeeded = "No"
If ((gp 'hklm:SOFTWARE\Microsoft\MSOLCoExistence').FullSyncNeeded -eq '1') {$FullSyncNeeded = "Yes"}

#Get SQL Info
$SQLServer = (gp 'HKLM:SYSTEM\CurrentControlSet\services\FIMSynchronizationService\Parameters').Server
if ($SQLServer.Length -eq '0') {$SQLServer = $env:computername}
$SQLInstance = (gp 'HKLM:SYSTEM\CurrentControlSet\services\FIMSynchronizationService\Parameters').SQLInstance
$MSOLInstance = ($SQLServer + "\" + $SQLInstance)
$SQLVersion = Invoke-Sqlcmd -ServerInstance $MSOLInstance -Query "SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')"

#Get Password Sync Status
[xml]$ADMAxml = Invoke-Sqlcmd -ServerInstance $MSOLInstance -Query "SELECT [ma_id] ,[ma_name] ,[private_configuration_xml] FROM [FIMSynchronizationService].[dbo].[mms_management_agent]" | ? {$_.ma_name -eq 'Active Directory Connector'} | select -Expand private_configuration_xml
$PasswordSyncBit = (Select-Xml -XML $ADMAxml -XPath "/adma-configuration/password-hash-sync-config/enabled" | select -expand node).'#text'
$PasswordSyncStatus = "Disabled"
If ($PasswordSyncBit -eq '1') {$PasswordSyncStatus = "Enabled"}

#Get Account Info
$ServiceAccountGuess = (((gci 'hkcu:Software\Microsoft\MSOIdentityCRL\UserExtendedProperties' | select PSChildName)[-1]).PSChildName -split ':')[-1]
$ADServiceAccountUser = $ADMAxml.'adma-configuration'.'forest-login-user'
$ADServiceAccountDomain = $ADMAxml.'adma-configuration'.'forest-login-domain'
$ADServiceAccount = $ADServiceAccountDomain + "\" + $ADServiceAccountUser

#Get DirSync Database Info
$SQLDirSyncInfo = Invoke-Sqlcmd -ServerInstance $MSOLInstance -Query "SELECT DB_NAME(database_id) AS DatabaseName, Name AS Logical_Name, Physical_Name, (size*8)/1024 SizeMB FROM sys.master_files WHERE DB_NAME(database_id) = 'FIMSynchronizationService'"
$DirSyncDB = $SQLDirSyncInfo | ? {$_.Logical_Name -eq 'FIMSynchronizationService'}
$DirSyncLog = $SQLDirSyncInfo | ? {$_.Logical_Name -eq 'FIMSynchronizationService_log'}

#Get connector space info (optional)
$ADMA = Invoke-Sqlcmd -ServerInstance $MSOLInstance -Query "SELECT [ma_id] ,[ma_name] FROM [FIMSynchronizationService].[dbo].[mms_management_agent] WHERE ma_name = 'Active Directory Connector'"
$AzureMA = Invoke-Sqlcmd -ServerInstance $MSOLInstance -Query "SELECT [ma_id] ,[ma_name] FROM [FIMSynchronizationService].[dbo].[mms_management_agent] WHERE ma_name = 'Windows Azure Active Directory Connector'"
$UsersFromBothMAs = Invoke-Sqlcmd -ServerInstance $MSOLInstance -Query "SELECT [ma_id] ,[rdn] FROM [FIMSynchronizationService].[dbo].[mms_connectorspace] WHERE object_type = 'user'"
$AzureUsers = $UsersFromBothMAs | ? {$_.ma_id -eq $AzureMA.ma_id}
$ADUsers = $UsersFromBothMAs | ? {$_.ma_id -eq $ADMA.ma_id}

#Get DirSync Run History
$SyncHistory = Invoke-Sqlcmd -ServerInstance $MSOLInstance -Query "SELECT [step_result] ,[end_date] ,[stage_no_change] ,[stage_add] ,[stage_update] ,[stage_rename] ,[stage_delete] ,[stage_deleteadd] ,[stage_failure] FROM [FIMSynchronizationService].[dbo].[mms_step_history]" | sort end_date -Descending

#GetDirSync interval (3 hours is default)
$SyncTimeInterval = (Select-Xml -Path ($DirsyncPath + "Microsoft.Online.DirSync.Scheduler.exe.config") -XPath "configuration/appSettings/add" | select -expand Node).value

#Generate Output
cls

Write-Host "Report Info" -F DarkGray
Write-Host "Date: " -F Cyan -NoNewline ; Write-Host (Get-Date) -F DarkCyan
Write-Host "Server: " -F Cyan -NoNewline ; Write-Host  $env:computername -F DarkCyan
Write-Host

Write-Host "Account Info" -F DarkGray
Write-Host "Active Directory Service Account: " -F Cyan -NoNewline ; Write-Host $ADServiceAccount -F DarkCyan
Write-Host "Azure Service Account Guess: " -F Cyan -NoNewline ; Write-Host $ServiceAccountGuess -F DarkCyan
Write-Host

Write-Host "DirSync Info" -F DarkGray
Write-Host "Version: " -F Cyan -NoNewline ; Write-Host $DirsyncVersion -F DarkCyan
Write-Host "Path: " -F Cyan -NoNewline ; Write-Host $DirsyncPath -F DarkCyan
Write-Host "Password Sync Status: " -F Cyan -NoNewline ; Write-Host $PasswordSyncStatus -F DarkCyan
Write-Host "Sync Interval (H:M:S): " -F Cyan -NoNewline ; Write-Host $SyncTimeInterval -F DarkCyan
Write-Host "Full Sync Needed? " -F Cyan -NoNewline ; Write-Host $FullSyncNeeded -F DarkCyan
Write-Host

Write-Host "User Info" -F DarkGray
Write-Host "Users in AD connector space: " -F Cyan -NoNewline ; Write-Host $ADUsers.count -F DarkCyan
Write-Host "Users in Azure connector space: " -F Cyan -NoNewline ; Write-Host $AzureUsers.count -F DarkCyan
Write-Host "Total Users: " -F Cyan -NoNewline ; Write-Host $UsersFromBothMAs.count -F DarkCyan
Write-Host

Write-Host "SQL Info " -F DarkGray
Write-Host "Version: " -F Cyan -NoNewline ; Write-host $SQLVersion.Column1 $SQLVersion.Column2 $SQLVersion.Column3 -F DarkCyan
Write-Host "Instance: " -F Cyan -NoNewline ; Write-Host  $MSOLInstance -F DarkCyan
Write-Host "Database Location: " -F Cyan -NoNewline ; Write-Host $DirSyncDB.Physical_Name -F DarkCyan
Write-Host "Database Size: " -F Cyan -NoNewline ; Write-Host $DirSyncDB.SizeMB "MB" -F DarkCyan
Write-Host "Database Log Size: " -F Cyan -NoNewline ; Write-Host $DirSyncLog.SizeMB "MB" -F DarkCyan
Write-Host

Write-Host "Most Recent Sync Activity" -F DarkGray
Write-Host "(For more detail, launch:" $DirsyncPath`SYNCBUS\Synchronization Service\UIShell\miisclient.exe")" -F DarkGray
Write-Host "  " ($SyncHistory[0].end_date).ToLocalTime() -F DarkCyan -NoNewline ; Write-Host " --" $SyncHistory[0].step_result -F Gray
Write-Host "  " ($SyncHistory[1].end_date).ToLocalTime() -F DarkCyan -NoNewline ; Write-Host " --" $SyncHistory[1].step_result -F Gray
Write-Host "  " ($SyncHistory[2].end_date).ToLocalTime() -F DarkCyan -NoNewline ; Write-Host " --" $SyncHistory[2].step_result -F Gray
Write-Host

Converting SMTP Proxy Addresses to Lowercase

May 14, 2012 6 comments

Update: Be aware, this script has not been tested with SIP, X400 or other address types. I am working on an update to validate these scenarios, but in the meantime, proceed at your own risk with these address types.

I recently encountered a question in an online forum where someone asked for a script to convert all of their user’s email addresses to lower case values.  While this doesn’t affect the message delivery, it can have an impact on aesthetics when the address is displayed in an external recipient’s email client.  An Exchange Email Address Policy can do this to some degree, but I wanted to see how it could be done with PowerShell.

The challenge with a script like this is twofold:

  1. Email addresses (proxy addresses) are a multi-valued attribute, which can be tricky to work with.
  2. PowerShell is generally not case-sensitive, and therefore when we try to rename Mr. Gallalee’s email address in the screenshot below, we can see that it does not work:

WARNING: The command completed successfully but no settings of 'demolab.local/Users/Rob Gallalee' have been modified.

After a little bit of inspiration from a script written by Michael B Smith, I came up with the below:


$MailboxList = Get-Mailbox  -ResultSize unlimited

$MailboxList | % {

$LoweredList = @()
$RenamedList = @()

foreach ($Address in $_.EmailAddresses){
if ($Address.prefixstring -eq "SMTP"){
$RenamedList += $Address.smtpaddress + "TempRename"
$LoweredList += $Address.smtpaddress.ToLower()
}
}
Set-mailbox $_ -emailaddresses $RenamedList -EmailAddressPolicyEnabled $false
Set-mailbox $_ -emailaddresses $LoweredList

#Without this line the "Reply To" Address could be lost on recipients with more than one proxy address:
Set-mailbox $_ -PrimarySmtpAddress $_.PrimarySmtpAddress
}

This script works as follows:

  1. Puts all mailboxes into the $MailboxList variable.  If you don’t want all mailboxes,  edit the Get-Mailbox cmdlet as you see fit.
  2. Filters out X400 and other non-SMTP addresses.
  3. Creates an array called $RenamedList which stores each proxy address with “TempRename” appended to it (e.g. Rgallalee@demolab.localTempRename).
  4. Creates another array ($LoweredList) and use the “ToLower” method on each proxy address.
  5. Sets the proxy address for the user to the value of $RenamedList and then to $LoweredList.
    1. This is how we get around the case case insensitivity – name it to something else and then name it back.
  6. Step 4 and 5 don’t preserve the “Primary” / “Reply-To” address, so we set it back manually with the last line.

Note: This script turns off the email address policy for each user.

As always, feedback is welcome.

Combining PowerShell Cmdlet Results

April 17, 2012 19 comments

In my last post I used used New-Object to create an desirable output when the “Get-Mailbox” cmdlet didn’t meet my needs.  If your eyes glazed over trying to read the script, let me make it a bit simpler by focusing on a straight forward example.

Say you need to create a list of user’s mailbox size with their email address.  This sounds like a simple request, but what you’d soon find is that mailbox sizes are returned with the Get-MailboxStatistics cmdlet and the email address is not.  For that, you need to use another cmdlet, such as Get-Mailbox.

With the New-Object cmdlet, we are able to make a custom output that contains data from essentially wherever we want.

See this example:

$MyObject = New-Object PSObject -Property @{
EmailAddress = $null
MailboxSize = $null
}

In this example, I have created a new object with 2 fields, and saved it as the $MyObject variable.

For now, we’ve set the data to null, as shown below:

$MyObject

The next step is to populate each of those fields.  We can write to them one at a time with lines like this:

$MyObject.EmailAddress = (Get-Mailbox mcrowley).PrimarySmtpAddress
$MyObject.MailboxSize = (Get-MailboxStatistics mcrowley).TotalItemSize

Note: The variable we want to populate is on the left, with what we want to put in it on the right.

To confirm our results, we can simply type the variable name at the prompt:

$MyObject with data

Pretty cool, huh?

Ok, so now about that list.  My example only shows the data for mcrowley, and you probably need more than just 1 item in your report, right?

For this, you need to use the foreach loop.  You can read more about foreach here, but the actual code for our list is as follows:

(I am actually going to skip the $null attribute step here)

$UserList = Get-mailbox -Resultsize unlimited
$MasterList = @()
foreach ($User in $UserList) {
$MyObject = New-Object PSObject -Property @{
EmailAddress = (Get-Mailbox $User).PrimarySmtpAddress
MailboxSize = (Get-MailboxStatistics $User).TotalItemSize
}
$MasterList += $MyObject
}
$MasterList

$MasterList with data

Finally, if you wanted to make this run faster, we really don’t need to run “get-mailbox” twice.  For better results, replace the line:

EmailAddress = (Get-Mailbox $User).PrimarySmtpAddress

With this one:

EmailAddress = $User.PrimarySmtpAddress

Exchange Proxy Address (alias) Report

April 16, 2012 19 comments

EDIT (Nov 15 2013):

This script has been updated significantly, please make sure you’re using version 4.

————–

Exchange Server stores user’s alternate email addresses as a multi-valued attribute within Active Directory.  For example, if my colleague Jorge has jdiaz@demolab.local as well as diazj@demolab.local, his proxyAddresses attribute would look like this:

ADUC - ProxyAddresses

Notice, the capital SMTP vs. the lowercase smtp.  There can be only one uppercase SMTP, and this represents the primary, or “reply to” address.

While, it’s very easy to view someone’s proxy addresses (often called aliases, but don’t confuse it with the “alias” attribute) within the Exchange Management Console, it can be tough to work with in the Exchange Management Shell (PowerShell) due to the data being stored as a  “Multi-Valued” attribute.  The usual “Get-Mailbox” output not only shows all addresses as a single item, but in the case “mcrowley” below, we can see the shell truncates:

get-mailbox mcrowley | select emailaddresses

While there are ways (example1, example2) to manipulate this output on the screen, I recently needed to create a complete list of all users possessing one or more secondary email address, and document what those addresses were.

On the surface, this sounds simple.  We want a list of users who have more than 1 proxy address.  At first, I thought of something like this:

Get-Mailbox -Filter {emailaddresses -gt 1} | Select EmailAddresses

Get-Mailbox -Filter {emailaddresses -gt 1} | Select EmailAddresses

But we can see this doesn’t actually capture the correct users.  In the above example, LiveUser1 only has a single proxy address, but it was returned anyway.  This is because the result is actually converted to a number, and the “-gt” or “greater than” operation is done on this number; not what we want.

I have written a script to help!

Features:

  1. This script creates a CSV output of everyone’s SMTP proxy addresses.
  2. Reports to the screen the total number of users found.
  3. Reports to the screen the user(s) with the most proxy addresses.
  4. You can configure the threshold of users reported. For example, if you only wanted users with 2 or more proxy addresses included, you should change the line: “$Threshold = 0″ to “$Threshold = 2″

Misc:

  1. Does not currently work with Exchange Online (planned enhancement).
  2. This uses “get-recipient” with no filters by default.  You may want to  replace this with something more restrictive, like “get-mailbox”, or use the -filter parameter.
  3. Requires PS 2.0 (for Exchange 2007, see here)

Here is a sample output, shown in excel:

Sample output to screen:

The guts of this script might help with this exact scenario, or really, anywhere you want to break out and evaluate multi-valued attributes.  Feel free to use it and adjust as you see fit!

Download the script here, or copy from the text below:

<#
Features:
    1) This script creates a CSV output of everyone's SMTP proxy addresses.
    2) Reports to the screen the total number of users found.
    3) Reports to the screen the user(s) with the most proxy addresses.
    4) You can configure the threshold of users reported.
        For example, if you only wanted users with 2 or more proxy addresses included,
        you should change the line: "$Threshold = 0" to "$Threshold = 2"
Misc:
    A) This uses "get-recipient" with no filters by default.  You may want to
        replace this with something more restrictive, like "get-mailbox", or use the
        -filter parameter.

November 15 2013
Mike Crowley

http://mikecrowley.us

#>

#Console prep
cd \
cls

#Getting a list of Recipients to work with
$AllRecipients = Get-Recipient -ResultSize unlimited

#Initializing variables
$Threshold = 0
$AttributeList = @()
$UsersAndSMTPProxies = @()
$UpperLimit = 0

#Examine each recipient
$AllRecipients | % {

    #Get a list of SMTP and smtp proxy addresses for each User
    $SmtpProxyAddresses = $_.emailaddresses | ? {$_.prefixstring -like 'smtp'} | sort IsPrimaryAddress -Descending

    #Create a new placeholder object with only their name
    $UserAndSmtpObject = New-Object PSObject -Property @{
        Name = $_.name
        }

    #Initialize the proxy counter
    $counter = 0

    #Begin breaking out proxy addresses
    $SmtpProxyAddresses | % {

        $SMTPaddress = $_ -replace “smtp:”
        $counter += 1

        if ($counter -eq 1) {$UserAndSmtpObject | Add-Member -MemberType NoteProperty -Name PrimarySmtpAddress -Value $SMTPaddress}

        else {$UserAndSmtpObject | Add-Member -MemberType NoteProperty -Name (“SmtpAddress” + $Counter) -Value $SMTPaddress}

        #Keep track of the highest proxy count
        if ($Counter -gt $UpperLimit) {$UpperLimit = ($UpperLimit + 1)}

    }

   #Add the custom object to the master array
   if ($counter -gt $Threshold) {$UsersAndSMTPProxies += $UserAndSmtpObject}
}

$UpperLimitAttribute = ('SMTPAddress' + $UpperLimit)

$UpperLimitReference = $UpperLimit

#Build output selection
$AttributeList += "Name"
$AttributeList += "PrimarySmtpAddress"
while ($UpperLimit -gt 1) {
    $AttributeList += ("SMTPAddress" + $UpperLimit)
    $UpperLimit = $UpperLimit -1
    }

#Arrange attributes
[array]::sort($AttributeList)

#Output to file
$UsersAndSMTPProxies | select $AttributeList | Export-CSV $env:USERPROFILE\Desktop\UsersAndSMTPProxies.csv -notype

#Output to screen
# $UsersAndSMTPProxies | select $AttributeList
Write-Host “”
Write-Host "There are " -NoNewline -Fore DarkCyan
Write-Host $UsersAndSMTPProxies.count -Fore Cyan -NoNewline
Write-Host " recipients. "  -NoNewline -Fore DarkCyan
Write-Host (($UsersAndSMTPProxies | sort $AttributeList[-1])[0]).name -NoNewline -fore Cyan
Write-host " was the recipient(s) with the most amount of proxy addresses (Total: " -NoNewline -Fore DarkCyan
Write-Host $UpperLimitReference -Fore Cyan -NoNewline
Write-Host ")." -Fore DarkCyan
Write-Host “”
Write-Host "The report has been saved here: " -NoNewline -Fore DarkCyan
Write-Host "$env:USERPROFILE\Desktop\UsersAndSMTPProxies.csv" -Fore Cyan
Write-Host “”

PowerShell Tip – Running a Service Pack Report – Faster

February 17, 2011 Leave a comment

Imagine you wanted to run a quick report of all your server’s service pack level in your domain.  After all, SP1 just came out!  You could get this information quickly by using the Active Directory Module for Windows PowerShell.  If you don’t have at least one Windows 2008 R2 (RTM or SP1) Domain Controller, you could also do something similar with the free Quest PowerShell tools, but that’s for another day…

We can find this information using a few different methods.  Here I’ll show two:

Method 1

Get-ADComputer -Properties OperatingSystem, OperatingSystemServicePack -Filter * | Where-Object {$_.OperatingSystem -like '*server*'} |  Format-Table name, oper* -autosize

You can see with Method 1, we’re telling PowerShell to get all the computer accounts from Active Directory.  Then we pass those objects over to the “Where-object” cmdlet and ask it to select only those who have an OperatingSystem attribute containing “server”.  We then format the results in a table.  Give it a try.

Not too shabby; but let’s make it better!

Method2

Get-ADComputer -Properties OperatingSystem, OperatingSystemServicePack -Filter {OperatingSystem -like '*server*'} | Format-Table name, oper* -autosize

In Method 2, we’re making smarter use of the –Filter switch.  So instead of getting ALL the computer accounts, we do our filtering up-front.  This can lead to significant amount of time saved!

How much time, you ask?  Well, we can find out with the “Measure-Command” cmdlet.  Just put any command string in {} and it will tell you how long it took to run!

Here are the results from a small environment with fast servers. 677 milliseconds isn’t bad, but when you compare it to 73, you can begin to appreciate the potential.

clip_image001

One last thought:  You may wish to add this extra code to make your output prettier.  It will organize your results first by operating system and then by name:

Get-ADComputer -Properties OperatingSystem, OperatingSystemServicePack -Filter {OperatingSystem -like '*server*'} | Sort-Object operatingsystem, name | Format-Table name, oper* -autosize

Script for Missing UPNs

December 14, 2010 4 comments

For various reasons I’ve found myself needing to fix customer sites where the User Principal Name (UPN) was not present for AD user accounts.

image

Most frequently this is because the environment was once NT4, which did not require this attribute.  Whatever the reason, I’ve fixed it using PowerShell.

If you don’t have 2008 R2 domain controllers you can use the free Quest PowerShell add-ins downloaded here.

If you DO have 2008 R2 domain controllers you can use the native Active Directory Module for Windows PowerShell.

Below is a script you can use for either scenario.  This will take all users with missing UPNs from the “My Users” OU in the “contoso.local” domain and set their UPN to username@contoso.local

Quest:

Get-QADUser –SearchRoot “contoso.local/My Users” -UserPrincipalName $null -SizeLimit 0 | % {$CompleteUPN = $_.samaccountname +"@contoso.local"; Set-QADUser -Id $_.DN -UserPrincipalName $CompleteUPN}

2008 R2 Native:

Get-ADUser  -Filter {-not (UserPrincipalName -like '*')} -SearchBase 'OU=My Users,DC=contoso,DC=local' | % {$CompleteUPN = $_.SamAccountName + "@contoso.local" ; Set-ADUser -Identity $_.DistinguishedName -UserPrincipalName $CompleteUPN}

Converting a Mailbox to a MailUser (and preserving your custom attributes)

December 9, 2010 12 comments

It’s not often that you’ll need to convert a mailbox to a mail-user, but when you do, you’ll soon realize the steps go like this:

1. Mail-Disable the user (delete the mailbox)
2. Mail-Enable the user

So what’s the problem?  The problem is twofold:

  • First, you’ll want to automate this, and there is no “convert” button or command.  You’ll need to use PowerShell if converting multiple users.
  • Second, and perhaps more importantly, all the Exchange attributes are nullified when you delete the mailbox.  This includes CustomAttribute1-15

As we can see, you are not able to pass mailboxes to the Enable-MailUser (as you are able to do in reverse):

image
I’ve written a script to solve these problems.  Before you run with it, you do need to make one decision:

What do you want the mail-user’s external email address to be?

The below script takes the user’s mailbox alias and then appends @domain.com.  You may wish to modify this with whatever their new external address has become.

You’ll also notice I’m using a static domain controller for all configurations.  I have found in my testing, that if you do not pick the same DC for all operations, the script could out-run replication.

$DomainController = (Get-ADServerSettings).DefaultConfigurationDomainController.domain

$MailboxList= Get-Mailbox

foreach ($Mailbox in $MailboxList) {
    Disable-Mailbox -Id $mailbox.Identity -Confirm:$False -DomainController $DomainController
    Enable-MailUser -Id $mailbox.Identity -ExternalEmailAddress ($mailbox.alias +"@domain.com") -DomainController $DomainController
    Set-MailUser -Id $mailbox.Identity `
     -DomainController $DomainController `
     -CustomAttribute1 $Mailbox.CustomAttribute1 `
     –CustomAttribute2 $Mailbox.CustomAttribute2 `
     –CustomAttribute3 $Mailbox.CustomAttribute3 `
     –CustomAttribute4 $Mailbox.CustomAttribute4 `
     –CustomAttribute5 $Mailbox.CustomAttribute5 `
     –CustomAttribute6 $Mailbox.CustomAttribute6 `
     –CustomAttribute7 $Mailbox.CustomAttribute7 `
     –CustomAttribute8 $Mailbox.CustomAttribute8 `
     –CustomAttribute9 $Mailbox.CustomAttribute9 `
     –CustomAttribute10 $Mailbox.CustomAttribute10 `
     –CustomAttribute11 $Mailbox.CustomAttribute11 `
     –CustomAttribute12 $Mailbox.CustomAttribute12 `
     –CustomAttribute13 $Mailbox.CustomAttribute13 `
     –CustomAttribute14 $Mailbox.CustomAttribute14 `
     –CustomAttribute15 $Mailbox.CustomAttribute15
     }

(add more attributes if necessary, but remember that since you aren’t deleting the Active Directory object itself, most attributes remain…)

Follow

Get every new post delivered to your Inbox.

Join 59 other followers