Powershell

Isolate a DC - Part 10: Reset KrbTGT password twice

This is Part 10 of a series on Active Directory Forest recovery; a new password for your domain. Rest KrbTGT password twice And finally, just in case someone still has a ticket lying around waiting to be used on your restored domain, sort that right out and update your KrbTGT password. function Reset-KrbtgtPasswordTwice{ [CmdletBinding( SupportsShouldProcess = $true, ConfirmImpact = 'High')]param() $targetPassword = (ConvertTo-SecureString "!7Dm$(get-random -minimum 10000000000000000 -maximum 1000000000000000000)$(get-random -minimum 10000000000000000 -maximum 1000000000000000000)#*&" -AsPlainText -Force) Write-Warning "Resetting the KRBTGT password twice without allowing replication of the update may result in Domain Controllers that cannot replicate if they have temporarily lost connectivity.

Isolate a DC - Part 9: Reset Intraforest trust passwords

This is Part 9 of a series on Active Directory Forest recovery; trust no-one, or at least no peer domains. Reset Intraforest trust passwords To avoid accidentally permitting interforest authentication with a Domain Controller that hasn’t been restored yet we need to reset the Intra-Forest trust passwords to a common value on both sides. This way the restored domains will all talk with the same hash. Update the trust shared secret to something actually secret before running this command.

Isolate a DC - Part 8: Metadata cleanup all other DCs

This is Part 8 of a series on Active Directory Forest recovery; make your DC lonely. Metadata Cleanup all other DCs Its not recovered until all the DCs are alive, but first, you have to kill them off with Metadata cleanup. Unfortunately the powershell commands won’t just delete a Domain Controller for you. So its up to NTDSUTIL automation to do the work again. You will need to run these in the Console host, not the PowerShell ISE.

Isolate a DC - Part 7: Seize all FSMO roles

This is Part 7 of a series on Active Directory Forest recovery; you need to have your FSMOs under control. Seize all FSMO roles The roles you seize will depend on if you are in a parent or child domain, the script below leverages NTDSUTIL to seize all roles for a forest root domain, and the Infrastructure Master, PDC and RID Master for Child domains. It also updates the FSMO owner attribute on your Application partitions (usually just Forest DNS zones and Domain DNS Zones)

Isolate a DC - Part 6: Raise RID pool

This is Part 6 of a series on Active Directory Forest recovery, in today’s exciting adventure we raise your RID pools by 100k and invalidate the current RID pool. Raise RID Pools Allocation Resource Identifiers are handed out whenever you create objects you can assign security to, if you are knee deep in restoration of your forest, you’ll want to make sure you don’t accidentally grant access to something unexpectedly by re-using a list SID.

Isolate a DC - Part 5: Disable Global Catalog

This is Part 5 of a series on Active Directory Forest recovery which requires brining up restored DCs in their own network; bring them up with good manners and we all benefit. Disable Global Catalog Now this step is strictly for Multi-Domain Forest recoveries. If your domains replicate cross domain boundaries, they’ll start complaining about their USNs and nobody wants that. If you’ve got yourself a nice simple single Domain environment, don’t sweat it and move on your Global Catalog can merrily sing into the night air without anybody noticing.

Extracting objects from commands that output text

There are many ways to throw a spanner. But if you really must throw it with powershell you’ll want it to result in an object.

The versatility of objects can give much to legacy commands that still linger in the Windows administration world. This short tutorial should teach you to turn most legacy commands into one or more commandlets in some concise code.

Isolate a DC - Part 4: Reset DSRM Password

This is Part 4 of a multi part blog post on Domain Recovery and DC Isolation with the aid of Powershell in todays installment we learn that Directory Services Restore Mode (DSRM) is not actually needed to perform a full forest recovery. Reset DSRM Password Another typically unnecessary step is getting your hands on your DSRM password - if you don’t already have it. DSRM password is only used in DSRM mode, which you don’t need for this fun exercise, but why not have it just in case!

Isolate a DC - Part 3: Activate Administrator Account

This is Part 3 of a multi part blog post automating AD Forest Recovery, take your forest to rehab, sit it down and force it not to have any AD corruption. Activate Administrator Account Now I am not one for a false sense of security, but people building environments that I support are. That is why, more often than not, the Administrator account is renamed, the password is divided in 2 and stored at different ends of the earth, one under the 6 watchful eyes of Cerberus the other stuffed in a filing cabinet lost to the ages.

import-svclog to import SVCLOG files

The Intune connectors dump all their useful information to .svclog files. You can read these files wtih svcTraceViewer.exe which you can get by installing the Windows Communication Foundation SDK.

Don’t want to download the SDK just to get one tool? Do not fear - they are just XML. Here is an imperfect script for reading svclog files.

Isolate a DC - Part 2: Reset SYSVOL Sync State

This is Part 2 of a multi part blog post covering the steps to Isolate a Domain Controller - if not emotionally, then logically. Reset your DFSR SYSVol State A DC booting into it’s own little world wont become healthy until SYSVOL has completed a sync with a partner in its domain, now this step is optional if your domain is temporary, but if you ever want to promote a new DC, or have a beautiful clear DCDIAG, then you’ll need to force SYSVOL into a synced state.

Isolate a DC - Part 1: Configure the Network

Dragging a single Domain Controller by its nostril into an isolated network can be time consuming. For testing or disaster recovery, the steps are the same, and while well documented almost everywhere, there don’t seem to be any quick and dirty tools to do the steps for you. That is why I wrote this series of powershell functions that can be applied to a DC you have restored in your Virtual environment to get your test Forest up and running quickly.

Assign EMS licenses to all licensed users

Azure conditional access provides amazingly flexible control over access to Office 365 resources and services based on location/user group membership/device etc. Leveraging it to block access generally requires EMS (Enterprise Mobility + Security) licenses for all users. This short script will assign EMS licenses to all users in your tenant who are licensed but do not have EMS yet.

User Profile Cleanup

Download Cleanup-UserProfiles.ps1 Big environments get messy, lots of users, lots of admins, lots of logging in here and there. Profiles accumulate, C drive starts to get full, oh the humanity! Fear not humble Admin, on our adventures today we discover how to remove old user profiles with naught but the flick of a WMI method. The meat and bonse of this function is getting user profiles and deleting them: $userprofiles = Get-WmiObject -Class Win32_UserProfile $userprofiles[$whichOne].

Paste an array into a variable

You’ve got a list of values, you want that in an array.

You could copy it to a file, and import it. You could dump it as a string and split it into an array.. or you could Create-ArrayFromPastedText.

Check if Office 365 has Your Updated ADFS Certificates

Download it here https://gallery.technet.microsoft.com/Check-and-Update-ADFS-3f27ee5e This script has probably lived its useful life, but I’m sharing it anyway, because.. well why not! When you want to quickly check to see if your published federation metadata (containing your ADFS token signing certificates) exists on Office 365 you can use Get-MsolFederationProperty that’s great if you have one domain.. but what if you have 25 or 50. Create a profile on your ADFS servers

Generate an SHA-1 signed certificate after cutover to SHA-2

You’ve finally made the switch on your Microsoft AD CS PKI infrastructure to SHA2 (SHA256)… but there is always one. One outlier application that won’t accept an SHA-2 certificate and needs an SHA1 certificate to keep chugging for 1 more year. Don’t worry, you can switch your Active Directory Certificate Services PKI infrastructure back to SHA-1 for a little bit. certutil -setreg ca\csp\CNGHashAlgorithm SHA1 restart-service certsvc Now issue your certificate, and switch back.

List all of a users group memberships

Download the script here Auditing user access is hard, usually you audit from resource out - eg, finding all Domain Admins, or finding all users with full acecss to SecretShare$ share on SecretServer01. But occasionally want to audit from user out.. this is hard.. even impossible (if you have a very big environment). Lets talk about the first step Enumerating Nested Groups. Token Groups Each user has a constructed attribute called tokengroups that returns a list of all transitive group memberships.

Clone OU Structure to New Domain

A quick, semi-powershell way to clone an OU structure from a source domain to a destination domain is to use the ldifde tool and then just modify the output. To generate the Output file Oustructure-cleaned.ldif we use ldifde to export all OUs and then remove the domain name (this is not necessary but helps later).

Remotely Retrieve active SSL certificate (HTTPS or LDAPS)

When replacing certificates on servers it is nice to be able to verify that the certificate has been updated after you have done the change. Download Retrieve-ServerCertFromSocket.ps1 With websites this tends to be very easy - enter the address in Internet Explorer and doubleclick the padlock to view the certificate. This doesn’t work in lots of situations though - no IE available in the environment, when you are trying to use a particular SNI header that doesn’t match your connectivity method on your client machine, or when you want to get a secure LDAP certificate - port 636 or 3269 from a Domain Controller.

Decoding legacy Exchange DN from NDR

Occasionally in Exchange you will accidentally or intentionally recreate a user, or delete some values from their object - this will impact the LegacyExchangeDN value. I have seen this happen where mailuser objects were removed from Office 365, the user objects were cloud only and the LegacyExchangeDN was gone forever. Contrary to its name, the LegacyExchangeDN value is critical to maintaining active conversations within your organisation. When a user’s legacyExchagneDN is lost, collegues replying to conversations with that user will get an NDR.

Track Lync Schema update with Powershell

When I perform schema changes in very large forests it is nice to be able to track the status of the change as it replicates throughout the forest. I wanted to create a script that would quickly tell me what the current schema was on over 100 DCs. If you don’t want to see how it was done you can just Download Track-LyncSchema.ps1 Starting with some scripts that I have built before foreach-parallel to do parallel processing, get-forestDomainControlles to get a list of all DCs in the forest and get-LdapData to do direct ldap lookups quickly.

Unable to verify an Azure AD domain

After you’ve added a domain to Azure AD (or Office 365) using powershell, while connected to your ADFS like this: New-MsolDomain -Name domaintest.wrish.com -Authentication Federated When you add your verification record and try to verify the domain from the GUI you might get an error like this: You can’t verify your domain using the GUI when you create the Domain using powershell, instead you have to confirm the domain using powershell while entering all Federation options.

Do it with the command line

You’ve built a Windows server without the GUI (Server Core only). You’re thinking, I use the command line all the time, this will be easy. It won’t. This cheat sheet has a few useful bits and pieces on how to configure it. #Force Windows Updates (New-Object -ComObject Microsoft.Update.AutoUpdate).DetectNow() #Dump the network interface config (to edit it) netsh interface dump > netcfg.dat #edit the config notepad netcfg.dat #Restore the interface config netsh exec netcfg.

Powershell Regex cheat sheet

A collection of regex’s that I always find myself looking up. #Match while tagging match groups 'CowColour Brown' -match '(?<Attribute>\w+) (?<Value>\w+)' | out-null $matches.Attribute $matches.Value #cowColour #Brown #Matching groups - your $matches object will have properties containing the valid matches "Subnet:10.1.1.0/24" -match 'Subnet:(?<SiteSubnet>(?:\d{1,3}\.){3}\d{1,3}/\d+)' #Replace to reformat a string 'This is a wild test' -replace '.*(w[^ ]+).*','Not so $1' #Not so wild #Lazy matching (to prevent over-matching) use a ? after the + or * "<h1>MyHeading</h1>" -replace '<([^/]+?

Download file the Powershell way

I was building a lab in Azure today and needed to download the Exchange binaries to extend my test AD schema. When you open up IE and browse to the Microsoft download site you have to add a list of 10 or 15 different sites to trusted - some of them are CDNs for shared Javascript code and resources. https://cdn.optimizely.com https://c.s-microsoft.com https://query.prod.cms.rt.microsoft.com https://mem.gfx.ms and then… Your current security settings do not allow this file to be downloaded sigh!

Cleaning Conflict and Deleted files on DFSR replicated SYSVOL

Perhaps you’ve done an ADRAP and youve got an item about Conflict and Deleted having some latent files. You found the AskDS entry about Manually Clearing the ConflictAndDeleted Folder in DFSR. But they use ugly WMIC commands, you want to use PowerShell, because PowerShell is awesome. get-addomaincontroller -filter * | %{ Get-WmiObject -Namespace "root/microsoftdfs" -class dfsrreplicatedfolderinfo -ComputerName $_.hostname } | ?{$_.replicationGroupName -eq "Domain System Volume"} | %{$_.cleanupConflictDirectory()}

Oh Damn Side by Side Comparison in Powershell

I work in Directories, usually lots of them at the same time. Spend a little time comparing the same user in 3 or 4 different directories and you long for a way to show them side by side. The Compare-Object cmdlet is handy for comparing lists of files but actually compare objects it does not! You have two or more objects, one works, one does not, you want to find out what is different between the two - this cmdlet is for you!

Highlight-String and Highlight-Output

You are a Windows Systems Administrator, you trawl through logs, compare datasets, peruse help files and you use PowerShell, but once, you were a Linux System Administrator and you revelled in tools like sed and grep. Perhaps you were looking for a way to replicate the glorious grep –color command, perhaps you found Wes’s Puzzling Blog for Highlighting Strings and What Have You. But for some reason, it didn’t quite cut it.