PowerShell

Domain Controller – Sysvol and Group Polices

Posted by robd on February 16, 2021
Active Directory / No Comments

Had some strange issues recently where some group polices weren’t populating to certain sites.

i.e. you’d logon to a new device on a site and the work folders GPO wouldnt apply, after spending 5 minutes looking at RSOP.MSC I could see the policy just wasnt applied, at all.

So after some digging on the domain controller and googling events in the event viewer I found:

https://support.microsoft.com/en-gb/help/2958414/dfs-replication-how-to-troubleshoot-missing-sysvol-and-netlogon-shares

Which lead me to this nifty command to check the sysvol folder:

For /f %i IN ('dsquery server -o rdn') do @echo %i && @(net view \\%i | find "SYSVOL") & echo

As you can see from the above, all looks ok!!!

So now lets have a look-see at the DFS replication:

For /f %i IN ('dsquery server -o rdn') do @echo %i && @wmic /node:"%i" /namespace:\\root\microsoftdfs path dfsrreplicatedfolderinfo WHERE replicatedfoldername='SYSVOL share' get replicationgroupname,replicatedfoldername,state

Run it and look for the “state”, the  values can be any of the following:

0 = Uninitialized
1 = Initialized
2 = Initial Sync
3 = Auto Recovery
4 = Normal
5 = In Error

As you can see on the above, the last one is wonky donkey!!! DFS BE BROKEN

So lets have a look through the events for dfs broken events:

and to double check with Powershell on the affected DC:

Get-WmiObject -Namespace 'root\MicrosoftDFS' -Class DfsrReplicatedFolderInfo

Nothing comes up, this is BAD!

So in the regisrty you should be able to check the recovery status

Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DFSR\Parameters

So its stopped and not recovering.

The fix:

First get the guid of the C:\ drive:

MountVol

Now run this in a elevated command prompt:

wmic /namespace:\\root\microsoftdfs path dfsrVolumeConfig where volumeGuid="cc9a4e7a-0000-0000-0000-602200000000" call ResumeReplication

Wait 10 and check the replication status again:

and run the dsquery again:

HORRAY!!!!!  GPOs for everyone.

Tags: , , ,

Disable weak RDP Vulnerabilities remotely

Posted by robd on January 28, 2021
powershell, Vulnerabilities / No Comments

Hello,

Here’s another handy fix for resolving RDP vulnerabilities remotely.

The script is a bit rubbish as I’ve not used CredSSP (I was in a rush) so you’ll need to run PowerShell as a admin and you’ll need a CSV with the servers in:

csv format:

Server

server1

server2

server3

Import-Csv "c:\temp\RDP_Vun.csv"| ForEach-Object {

write-host ""
write-host "===================================="
write-host "Computer: $_.server"
write-host "===================================="

write-host "-----------------------------------"
write-host "Fix RDP Vunrability"
write-host "-----------------------------------"

# Remote Desktop Services: Enable NLA Requirement
(Get-WmiObject -Computer $_.server -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -Filter "TerminalName='RDP-tcp'").UserAuthenticationRequired  
(Get-WmiObject -Computer $_.server -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(1) 

# Remote Desktop Services: Require 'High' level of encryption
(Get-WmiObject -Computer $_.server -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -Filter "TerminalName='RDP-tcp'").SetEncryptionLevel(3) 

# Remote Desktop Services: Set Security Layer to SSL
(Get-WmiObject -Computer $_.server -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -Filter "TerminalName='RDP-tcp'").SetSecurityLayer(2)


} 

 

Tags: , ,

Check and change DNS on all the servers in the domain

Posted by robd on February 19, 2020
DNS, powershell / No Comments

Here’s a brilliant PowerShell scipt to check what the DNS servers are set as accross the domain then change it:

 

$allservers = @()
$domainpcs = Get-ADComputer -Filter * -Properties operatingsystem | where {$_.operatingsystem -like "*Server*"} | sort name
foreach ($pc in $domainpcs)
{
    if (Test-Connection $pc.DNSHostName -Quiet)
    {
        $thisserver = $null
        $DNSsettings = $null


        $DNSsettings = Get-DnsClientServerAddress -CimSession $pc.DNSHostName | where {($_.AddressFamily -eq 2) -and ($_.InterfaceAlias -notlike "Loopback*") -and ($_.InterfaceAlias -notlike "isatap*") -and ($_.ServerAddresses -ne $null)} | select @{n='DNSServers';e={$_ | select -ExpandProperty serveraddresses}},InterfaceIndex
        $thisserver =  New-Object psobject -Property @{
                       Servername = $pc.Name
                       interfaceindex = $DNSsettings.interfaceindex[0]
                       DNSsetting1 = $DNSsettings.dnsservers[0]
                       DNSsetting2 = $DNSsettings.dnsservers[1]
                       DNSsetting3 = $DNSsettings.dnsservers[2]
        }


        $allservers += $thisserver
        $thisserver
    }
    
}




foreach ($server in $allservers)

{

        $newdns1 = $null
        $newdns2 = $null
        $newdns3 = $null

        $needchange = $false

        write-host $server.Servername -ForegroundColor Green

       $newdns1 = $server.dnssetting1
        $newdns2 = $server.dnssetting2
        $newdns3 = $server.dnssetting3

       write-host $newdns1 -ForegroundColor Red
       write-host $newdns2 -ForegroundColor Red
       write-host $newdns3 -ForegroundColor Red


    

       Switch ($server.DNSsetting1)
       {
           "10.5.1.4" {$newdns1 = "8.8.8.8";$needchange =$true}
           "10.5.1.5" {$newdns1 = "8.8.4.4";$needchange =$true}
           "10.5.1.6" {$newdns1 = "1.1.1.1";$needchange =$true}
       }

       Switch ($server.dnssetting2)
       {
           "10.5.1.4" {$newdns2 = "8.8.8.8";$needchange =$true}
           "10.5.1.5" {$newdns2 = "8.8.4.4";$needchange =$true}
           "10.5.1.6" {$newdns2 = "1.1.1.1";$needchange =$true}
       }

       Switch ($server.dnssetting3)
       {
           "10.5.1.4" {$newdns3 = "8.8.8.8";$needchange =$true}
           "10.5.1.5" {$newdns3 = "8.8.4.4";$needchange =$true}
           "10.5.1.6" {$newdns3 = "1.1.1.1";$needchange =$true}
       }


       write-host $newdns1 -ForegroundColor Cyan
       write-host $newdns2 -ForegroundColor Cyan
       write-host $newdns3 -ForegroundColor Cyan

       $needchange
       if ($needchange)
       {      
           Set-DnsClientServerAddress -cimsession $server.servername -InterfaceIndex $server.interfaceindex -ServerAddresses ($newdns1,$newdns2,$newdns3)  -whatif
       }
}

 

Tags: ,

Check DNS accross all your Domain Controllers

Posted by robd on November 22, 2019
Active Directory, DNS, powershell / 1 Comment

Handy bit of PowerShell my bestest ever friend wrote to check DNS accross domain controllers:

 

#do dns servers agree for dns
$results = $null
$results = @()
$DNSServers = Get-ADDomainController -Filter * 
$hostname = Read-Host('enter dns record to check')
foreach ($DNSServer in $DNSServers)
{
    $dnsrecord = Resolve-DnsName -Name $hostname -Server $DNSServer.HostName -Type A
    $result = New-Object psobject -Property @{
    dnsserver = $DNSServer.Name
    hostname = $dnsrecord.name
    IPAddress = $dnsrecord.ipaddress
    }
    $results += $result
}

$results | select hostname,ipaddress,dnsserver | sort ipaddress

 

Tags: ,

Run PowerShell through a Proxy

Posted by robd on August 27, 2019
powershell, Proxy / No Comments

At work I’m behind a proxy which caused me havock when trying to install modules into PowerShell.

That was until I found this amazing script to tell PowerShell to use a proxy.

First open your PowerShell profile by either doing this in PowerShell:

notepad $PROFILE

Or open “Microsoft.PowerShell_profile.ps1” and  “Microsoft.PowerShellISE_profile.ps1” in Explorer with notepad:

C:\Users\%Username%\My Documents\WindowsPowerShell

Once open, paste in the following, editing the proxy address and port.

[system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy('http://ProxyName:ProxyPort')

[system.net.webrequest]::defaultwebproxy.credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

[system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true

This will use your current credentials you’re logged in with to pass the commands to the proxy server.

Test with a

update-help

 

Tags: , ,

Set-ACL – Se file and folder permissions

Posted by robd on May 12, 2019
powershell, Server / No Comments

I wanted to add an AD group to all the files and folders in a share, the problem is inheritance had been turned off on lots of the folders so I couldn’t just add the AD group to the top and let it filter down. So the solution was to use PowerShell.
First I mapped a drive to the Share (x: in this case). Why didn’t I run this on the server? UAC is a pain in the bum.

You’ll need to change the path and the domain and AD group.

$folders = Get-ChildItem -Directory -Path X:\ -Recurse
foreach ($folder in $folders){
$acl = Get-Acl -path $folder.FullName
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule `
("DOMAIN\AD_GROUP", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl -path $folder.FullName
}

 

Tags: ,

Get-ACL – Report file and folder permissions

Posted by robd on May 11, 2019
powershell, Server / No Comments

If you need to report out file and folder permissions of a file share, see the below PowerShell.

First map the the share to a drive if it isnt already.  In my case X: drive.

Why didn’t I do this on the server hosting the files?  UAC gets in the way and is a pain the bum.

$FolderPath = dir -Directory -Path "x:\" -Recurse -Force
$Report = @()
Foreach ($Folder in $FolderPath) {
$Acl = Get-Acl -Path $Folder.FullName
foreach ($Access in $acl.Access)
{
$Properties = [ordered]@{'FolderName'=$Folder.FullName;'AD
Group or
User'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights;'Inherited'=$Access.IsInherited}$Report += New-Object -TypeName PSObject -Property $Properties}
}
$Report | Export-Csv -path "C:\temp\Folder_Permissions.csv"

 

 

Tags: ,

Edit VMs using PowerShell and PowerCLI

Posted by robd on January 28, 2019
powershell, vmware / No Comments

To resize VMs using PowerShell with PowerCLI from a csv list, first install the software:

 

https://my.vmware.com/web/vmware/details?downloadGroup=PCLI650R1&productId=614

 

Then create a list of servers to resize and save it as a CSV file in C:\temp\VMs.csv:

 

Server01

Server02

Server03

 

Save the below as Something.PS1 and run from PowerCLI

Note: Change VCENTRE to your vCentre, this script will TURN THE SERVER OFF then give each VM two CPUs, one socket and 5GBs of RAM.

 

$me = Get-Credential

connect-viserver "VCENTRE" -User $me

$vms = get-content C:\Temp\VMs.csv

ForEach ($vm in $vms){

$vms | Shutdown-VMGuest –Confirm:$False

Sleep 60

$vms | Set-VM –MemoryGB 8 –NumCpu 2 –Confirm:$False

$vms | Start-VM

}

 

Tags: , ,

Forcing a SMTP on a Mailbox fails

Posted by robd on October 24, 2018
Exchange Online / No Comments

As I mentioned in another post, you can force a EoL mailbox to take on a SMTP with this command:

Set-Mailbox User.Name -WindowsEmailAddress User.Name@Bohemiangrove.co.uk

But occasionally it won’t work:

The proxy address "SMTP:User.Name@Bohemiangrove.co.uk" is already being used by the proxy addresses or LegacyExchangeDN of "User.Name_bohemiangrove.co.uk#EXT#". Please choose another proxy address.

    + CategoryInfo          : NotSpecified: (Adri Donkers:ADObjectId) [Set-Mailbox], ProxyAddressExistsException

    + FullyQualifiedErrorId : [Server=VI1PR04MB4349,RequestId=8938a92c-006d-4f9f-b230-937f591d20e4,TimeStamp=22/10

   /2018 06:18:53] [FailureCategory=Cmdlet-ProxyAddressExistsException] 169E5E0,Microsoft.Exchange.Management.Rec 

  ipientTasks.SetMailbox

    + PSComputerName        : ps.outlook.com

So to find who’s using the address you can search all of Azure using:

Get-Recipient | where {$_.EmailAddresses -match "User.Name@Bohemiangrove.co.uk"} | fL Name, RecipientType,emailaddresses

 

Tags: ,

Exchange Online – Hybrid – Missing SMTP

Posted by robd on October 23, 2018
Exchange Online / No Comments

Strange issue today, synced a bunch of users from on prem to Exchange which was successful.

Then the user was missing his default SMTP address on EoL but the SMTP was there on prem:

EoL, no COM:

EX prem, has COM

First thing to check, is the domain setup as a accepted domain in EoL (should be as the migration would of failed otherwise).

Next you can “override” the sync process by using the following EoL cmdlet:

Set-Mailbox user@domain.com -WindowsEmailAddress new@domain.com

 

Tags: ,