Skip to main content

Powershell 3.0 - Kerberos and SPN


Just a quick post about Powershell and SPN. I have "used" powershell for several years now. I mean used as in having created some very, very small scripts and cmdlets starting back in 2007 when Microsoft launched their powershell cmdlets for Exchange 2007. Any way, the last months I have been playing heavily with Powershell and have learned the beauty of it quite recently. 

I am kind of excited about the new Powershell 3.0 released with Win8 and Microsoft Server 2012. If you have not tried it, I recommend you download it and give it a go. The new built-in editor from Microsoft has actually become very good with intellisense and other goodies.



Quick-tip: When you install the Powershell ISE editor, you get a new cmdlet that gives you the ability to output the results to a sortable gridview. You may also copy and paste to Excel or other applications!




Recently I was tasked with creating a script to be able to set SPN for an Active Directory user. I created to functions named Get-ADUserSPN and Set-ADUserSPN. 


Function Get-ADUserSPN
{
<#

.Synopsis 
 This function returns the SPNs for a user object in ActiveDirectory 
.Description 
 Must be executed on a server with the active Directory module present
.Example 
 Get-ADUserSPN usera 
 Returns the SPNs for a user with sAMaccountName 'usera' 
.Example 
 Get-ADUserSPN -SAM usera 
 Returns the SPNs for a user with sAMaccountName 'usera'.   
.Parameter UserAccount [string] 
.Role 
 General 
.Component 
 FP 
.Notes 
 NAME: Get-ADUserSPN 
 AUTHOR: Tore Groneng LASTEDIT: November 2012 
 KEYWORDS: General scripting SCCM 
.Link 
 Http://www.firstpoint.no 
 Created by: Tore Groneng 
 tore@firstpoint.no #toregroneng tore.groneng@gmail.com 

#Requires -Version 2.0 
#> 

PARAM(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[Alias("SAM")]
[string]$UserAccount
)

# Load the AD module, if needed (in powershell 3.0 it will automatically load modules as needed and import-module will kind of be redundant)

if ((get-Module -Name ActiveDirectory -ErrorAction SilentlyContinue) -eq $null )
{
Import-Module ActiveDirectory
}

$theUser = get-aduser $UserAccount -properties *

if ($theUser.servicePrincipalName.count -eq 0){
write-host "No SPN found for the user '$UserAccount'" -fore yellow
}
else{
# Print the SPNs to the console
$theUser.servicePrincipalName
}
}

So to be able to set SPN for a user, we must do something like this:

Function Set-ADUserSPNSQL
{
<# 
.Synopsis 
 This function sets the SPNs for a user object in ActiveDirectory 
.Description 
 Must be executed on a server with the activeDirectory module present. 
 Exception is thrown if you try to set an SPN that already exists for the target       server and user.
.Example 
 Set-ADUserSPNSQL "usera" "bgo-vm-sql-01" 
 Sets the SPN for user 'usera' with target server bgo-vm-sql-01 using the default   port 1433 
.Example 
 Set-ADUserSPNSQL -SAM "usera" -target "bgo-vm-sql-01" 
 Sets the SPN for user 'usera' with target server bgo-vm-sql-01 using the default port 1433 
.Example 
 Set-ADUserSPNSQL -SAM "usera" -target "bgo-vm-sql-01" -port 14433 
 Sets the SPN for user 'usera' with target server bgo-vm-sql-01 using the port 14433 
.Parameter 
 UserAccount UserAccount [string] 
.Parameter 
 TargetServer TargetServer [string] 
.Parameter 
 PortNumber PortNumber [int] 
.Role 
 General 
.Component FP 
.Notes 
 NAME: Set-ADUserSPNSQL 
 AUTHOR: Tore Groneng 
 LASTEDIT: November 2012 
 KEYWORDS: General scripting 
.Link 
 Http://www.firstpoint.no C
Created by: 
Tore Groneng tore@firstpoint.no #toregroneng tore.groneng@gmail.com 
#Requires -Version 2.0 
#> 
PARAM(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[Alias("SAM")]
[string]$UserAccount
,
[Parameter(Position=1, Mandatory=$true)]
[Alias("target")]
[string]$TargetServer
,
[Parameter(Position=2)]
[Alias("Port")]
[INT]$PortNumber = 1433
)
[string]$targetKerb = "MSSQLSvc/"
[string]$dnsDomain = $env:UserDNSdomain
[string]$colon = ":"

# Load the AD module, if needed (in powershell 3.0 it will automatically load  modules as needed and import-module will kind of be redundant)

if ((get-Module -Name ActiveDirectory -ErrorAction SilentlyContinue) -eq $null )
{
Import-Module ActiveDirectory
}

$theUser = get-aduser $UserAccount -properties *

if ($theUser -eq $null{
write-host "Error - could not find user $UserAccount"
}
else {
$theUser.servicePrincipalName += "$targetKerb$TargetServer$colon$PortNumber"
$theUser.servicePrincipalName += "$targetKerb$TargetServer.$dnsDomain$colon$PortNumber"

try {
set-aduser -instance $theUser
write-host "Successfully set the SPN for the user ('$UserAccount'), user now have these SPNs:" -fore yellow
$theUser = get-aduser $UserAccount -properties *
write-host $theUser.servicePrincipalName -fore green
}
catch {
write-host "Exception - $_.Exception"
write-host "Useraccount:::$UserAccount" -fore yellow
write-host "TargetServer:::$TargetServer" -fore yellow
}


Comments

Popular posts from this blog

Serialize data with PowerShell

Currently I am working on a big new module. In this module, I need to persist data to disk and reprocess them at some point even if the module/PowerShell session was closed. I needed to serialize objects and save them to disk. It needed to be very efficient to be able to support a high volume of objects. Hence I decided to turn this serializer into a module called HashData. Other Serializing methods In PowerShell we have several possibilities to serialize objects. There are two cmdlets you can use which are built in: Export-CliXml ConvertTo-JSON Both are excellent options if you do not care about the size of the file. In my case I needed something lean and mean in terms of the size on disk for the serialized object. Lets do some tests to compare the different types: (Hashdata.Object.ps1) You might be curious why I do not use the Export-CliXML cmdlet and just use the [System.Management.Automation.PSSerializer]::Serialize static method. The static method will generate t...

Toying with audio in powershell

Controlling mute/unmute and the volume on you computer with powershell. Add-Type -TypeDefinition @' using System.Runtime.InteropServices; [Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IAudioEndpointVolume { // f(), g(), ... are unused COM method slots. Define these if you care int f(); int g(); int h(); int i(); int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext); int j(); int GetMasterVolumeLevelScalar(out float pfLevel); int k(); int l(); int m(); int n(); int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext); int GetMute(out bool pbMute); } [Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IMMDevice { int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev); } [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), Inte...

Creating Menus in Powershell

I have created another Powershell module. This time it is about Console Menus you can use to ease the usage for members of your oranization. It is available on GitHub and published to the PowershellGallery . It is called cliMenu. Puppies This is a Controller module. It uses Write-Host to create a Menu in the console. Some of you may recall that using Write-Host is bad practice. Controller scripts and modules are the exception to this rule. In addition with WMF5 Write-Host writes to the Information stream in Powershell, so it really does not matter anymore. Design goal I have seen to many crappy menus that is a mixture of controller script and business logic. It is in essence a wild west out there, hence my ultimate goal is to create something that makes it as easy as possible to create a menu and change the way it looks. Make it easy to build Menus and change them Make it as "declarative" as possible Menus The module supports multiple Men...