PowerShell

Domain Trust and AD Groups

Posted by robd on April 26, 2023
powershell / No Comments

The company I work for is much like the Borg where they like to assimilate new companies.

Part of this assimilation often involves a domain trust and adding users from one domain to a second domains AD groups to gain access to permissions in Domain 2.

This is really useful if your giving a user a laptop on domain 1 but they need access to files on domain 2.

 

My Mate Handsom Dave came up with this script too:

Compare users from Domain 1 and Domain 2 on display name (username didnt match),

Get the Domain 2 groups,

Look at domain 2 groups members,

If they exist in domain 1 then add those people into the group in Domain 2.

Remember: The AD groups need to be Domain Local.

 

 

#Get the users from domain1
$domain1 = get-aduser -filter * -Server dc01.domain1.com
#get the users from domain2
$domain2 = get-aduser -filter * -Server dc02.domain2.net
#compare the users on name (not username as they didnt match)
$usercompare = Compare-Object -ReferenceObject $domain1.name -DifferenceObject $domain2.name -IncludeEqual
#If its the same then save to this variable
$inboth = $usercompare | where {$_.sideindicator -eq "=="}
#In Domain 2 get all the AD groups that start with ACL_
$domain1groups = Get-ADGroup -filter {name -like "ACL_*"} -Server dc01.domain1.com

#Here we go
foreach ($group in $domain1groups)
{ 
    #get the ad members from the acl group 
    $domain1groupmembers = Get-ADGroupMember $group.name -Server dc01.domain1.com 
    foreach ($groupmember in $domain1groupmembers) 
    { 
        #if the member of the group matches someone in the inboth variable
        if ($inboth.inputobject -contains $groupmember.name) 
        { 
        
        $domain2userobject = Get-ADUser -Filter {name -like $groupmember.name} 
        
        # add that domain 1 person to the domain 2 ad group
        Add-ADGroupMember -Identity $group -Members $domain2userobject -server dc01.domain1.com -WhatIf
        } 
        
        }
        
}

 

 

 

Tags: , , , ,

Take Ownership of paths from PowerShell

Posted by robd on April 25, 2023
powershell / No Comments

Hello,

Had a requirement to take ownership of a long list of windows file paths which were conviently in a csv file like this:

path

\\domain.local\site\users\User.Name\

So I used the following PowerShell and NTFSSecurity module.

#import this first (run powershell as Admin)
#Install-Module -Name NTFSSecurity

#Fill out the csv with all the paths you want to change

Import-CSV "C:\Temp\scripts\permissions.csv" |
    ForEach-Object{
    Add-NTFSAccess -Path $_.path -Account jacob.admin@kil.kingspan.net -AccessRights FullControl
    Set-NTFSOwner -Path $_.path -Account  jacob.admin@kil.kingspan.net

    }

 

Tags: , ,

Azure – Restore a VM from your Az Recovery Services Vault

Posted by robd on September 09, 2022
Azure, powershell / No Comments

Hello,

More DR stuff for me, I needed to restore a VM from Recovery Vault, heres how I did it:

Open PowerShell and connect to Azure:

Connect-AzAccount

Lets get started, as before, theres lots to change so READ it carefully:

#Find your vault and resouce Group, CHANGE FOR YOUR ENVIRONMENT
$vault = get-AzRecoveryServicesVault -Name "LinuxVault" -ResourceGroupName "LinuxRG"
Set-AzRecoveryServicesAsrVaultContext -Vault $vault

#Set the fabric of your vault, CHANGE FOR YOUR ENVIRONMENT
$PrimaryFabric = Get-AzRecoveryServicesAsrFabric -name asr-a2a-default-northeurope

#Set these
$PrimaryProtContainer = Get-AzRecoveryServicesAsrProtectionContainer -Fabric $PrimaryFabric -Name "asr-a2a-default-northeurope-container"

#set your network, CHANGE FOR YOUR ENVIRONMEN
$TFOVNet = Get-AzVirtualNetwork -Name uks-kil-dr-test-vnet
$TFONetwork= $TFOVnet.Id

#Here we get the VM and start the recovery, CHANGE FOR YOUR ENVIRONMENT
$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer -FriendlyName "Linux-Server-1"
$TFOJob1 = Start-AzRecoveryServicesAsrTestFailoverJob -ReplicationProtectedItem $ReplicationProtectedItem -AzureVMNetworkId $TFONetwork -Direction PrimaryToRecovery

#Same but a different VM
$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer -FriendlyName "Linux-Server-2"
$TFOJob2 = Start-AzRecoveryServicesAsrTestFailoverJob -ReplicationProtectedItem $ReplicationProtectedItem -AzureVMNetworkId $TFONetwork -Direction PrimaryToRecovery

#Same but a different VM
$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer -FriendlyName "Linux-Server-3"
$TFOJob3 = Start-AzRecoveryServicesAsrTestFailoverJob -ReplicationProtectedItem $ReplicationProtectedItem -AzureVMNetworkId $TFONetwork -Direction PrimaryToRecovery

#Same but a different VM
$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer -FriendlyName "Linux-Server-4"
$TFOJob4 = Start-AzRecoveryServicesAsrTestFailoverJob -ReplicationProtectedItem $ReplicationProtectedItem -AzureVMNetworkId $TFONetwork -Direction PrimaryToRecovery

#Same but a different VM
$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer -FriendlyName "DC-Server-1"
$TFOJob5 = Start-AzRecoveryServicesAsrTestFailoverJob -ReplicationProtectedItem $ReplicationProtectedItem -AzureVMNetworkId $TFONetwork -Direction PrimaryToRecovery

 

Once you’re done with you’re restored VMs should clean up your work if you need too (I was using them to test DR so wanted to deleted them after):

#Get teh VM you cloned and bin it off, CHANGE the VM name FOR YOUR ENVIRONMENT
$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer -FriendlyName "Linux-Server-1"
$Job_TFOCleanup = Start-AzRecoveryServicesAsrTestFailoverCleanupJob -ReplicationProtectedItem $ReplicationProtectedItem

$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer -FriendlyName "Linux-Server-2"
$Job_TFOCleanup = Start-AzRecoveryServicesAsrTestFailoverCleanupJob -ReplicationProtectedItem $ReplicationProtectedItem

$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer -FriendlyName "Linux-Server-3"
$Job_TFOCleanup = Start-AzRecoveryServicesAsrTestFailoverCleanupJob -ReplicationProtectedItem $ReplicationProtectedItem

$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer -FriendlyName "Linux-Server-4"
$Job_TFOCleanup = Start-AzRecoveryServicesAsrTestFailoverCleanupJob -ReplicationProtectedItem $ReplicationProtectedItem

$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer -FriendlyName "DC-Server-1"
$Job_TFOCleanup = Start-AzRecoveryServicesAsrTestFailoverCleanupJob -ReplicationProtectedItem $ReplicationProtectedItem

 

 

Tags: , , ,

Azure – Clone a VM from a Snapshot

Posted by robd on September 09, 2022
Azure, powershell / No Comments

Hello,

So something fun I’ve been working on recently is cloning a Linux Azure VM from a snapshot, for my case so I can test it for DR.

To do this you basically need to:

  1. Create a vnet for the clone if you need too (I reference it in the script)
  2. Create a snapshot of the VM
  3. Create a managed disk for the snapshot
  4. Create a VM with different name using the managed disk
  5. If needed rename the VM on the OS level to match the VM name.

Or you could use some PowerShell:

First open PowerShell and run:

Connect-AzAccount

The you need to change some of the below (look for “CHANGE THIS FOR YOUR ENVIRONMENT”):

#Existing virtual network where new virtual machine will be created, CHANGE THIS FOR YOUR ENVIRONMENT
$virtualNetworkName = 'uks-dr-test-vnet'  
  
#Resource group of the VM to be clonned from, CHANGE THIS FOR YOUR ENVIRONMENT
$oldresourceGroupName = 'UKS-VM1-DR'  
$newresourceGroupName = 'UKS-VM1-DR-TEST'  

#Region where managed disk will be created, CHANGE THIS FOR YOUR ENVIRONMENT
$location = 'UK South'  
  
#Names of source and target (new) VMs,CHANGE THIS FOR YOUR ENVIRONMENT
$sourceVirtualMachineName = 'Linux-VM1'  
$targetVirtualMachineName = 'Linux-VM1-DR'  

#Set the subscription for the current session where the commands wil execute,CHANGE THIS FOR YOUR ENVIRONMENT
Select-azSubscription -SubscriptionId '111111111-1111-1111-1111-111111111111'  
  
#Get the existing VM from which to clone from  
$sourceVirtualMachine = Get-AzVM -ResourceGroupName $oldresourceGroupName -Name $sourceVirtualMachineName  

$osdisk = Get-AzDisk -DiskName $($sourceVirtualMachine.StorageProfile.OsDisk.name) 
#Create new VM Disk Snapshot  
$snapshotconfig = New-AzSnapshotConfig -Sourceresourceid $osdisk.Id -Location $osdisk.Location -CreateOption copy  
$snapshot = New-AzSnapshot -Snapshot $snapshotconfig -SnapshotName "$($osdisk.name)-snapshot" -ResourceGroupName $oldresourceGroupName   

#Create a new OS Managed Disk from the Snapshot  
$disk = New-azDiskConfig -AccountType $osdisk.sku.Name -DiskSizeGB $($osdisk.DiskSizeGB) -Location $location -CreateOption Copy -SourceResourceId $snapshot.Id  
$disk = New-azDisk -Disk $disk -ResourceGroupName $newresourceGroupName -DiskName "$($osdisk.name)-DR"
  
#Initialize virtual machine configuration  
$targetVirtualMachine = New-azVMConfig -VMName $targetVirtualMachineName -VMSize $($sourceVirtualMachine.HardwareProfile.VmSize)
  
#Attach Managed Disk to target virtual machine. OS type depends OS present in the disk (Windows/Linux)  
$targetVirtualMachine = Set-azVMOSDisk -VM $targetVirtualMachine -ManagedDiskId $disk.Id -CreateOption Attach -linux 

$disks = $sourceVirtualMachine.StorageProfile.DataDisks
#$disks = Get-AzDisk -ResourceGroupName $oldresourceGroupName | where {$_.managedby -like "*$sourceVirtualMachineName" -and $_.Name -like "*Datadisk*"} 
foreach ($disk in $disks){
    #Create new VM Disk Snapshot
    $datadisk = Get-AzDisk -DiskName $disk.name   
    $snapshotconfig = New-AzSnapshotConfig -SourceUri $($disk.manageddisk.id) -Location $datadisk.Location -CreateOption copy  
    $snapshot = New-AzSnapshot -Snapshot $snapshotconfig -SnapshotName "$($disk.name)_snapshot" -ResourceGroupName $oldresourceGroupName 

    #Create a new Managed Disk from the Snapshot  
    $diskconfig = New-azDiskConfig -SkuName $datadisk.sku.name -DiskSizeGB $($disk.DiskSizeGB) -Location $location -CreateOption Copy -SourceResourceId $snapshot.Id  
    $newdisk = New-azDisk -Disk $diskconfig -ResourceGroupName $newresourceGroupName -DiskName "$($datadisk.Name)-dr"   
    $targetVirtualMachine = add-AzVMDataDisk -VM $targetVirtualMachine -ManagedDiskId $newdisk.Id -lun $disk.lun -CreateOption attach 

} 

#Get Virtual Network information,CHANGE THIS FOR YOUR ENVIRONMENT
$vnet = Get-azVirtualNetwork -Name $virtualNetworkName
$subnetid = $($vnet.Subnets | where {$_.Name -like "DR_Sunet"}).id

# Create Network Interface for the VM, CHANGE THIS FOR YOUR ENVIRONMENT
$nic = New-azNetworkInterface -Name ($targetVirtualMachineName.ToLower() + '_nic') -ResourceGroupName $newresourceGroupName -Location $location -SubnetId $subnetid -PrivateIpAddress 172.45.1.252
$targetVirtualMachine = Add-azVMNetworkInterface -VM $targetVirtualMachine -Id $nic.Id  
  
#Create the virtual machine with Managed Disk attached  
New-azVM -VM $targetVirtualMachine -ResourceGroupName $newresourceGroupName -Location $location  
  
#Remove the snapshot  
Get-AzSnapshot -ResourceGroupName $oldresourceGroupName | Remove-AzSnapshot -Force

This chap does something similar too:

https://www.techmanyu.com/how-to-quickly-clone-a-vm-in-azure-c5299ff82496

Tags: , , ,

dbatools

Posted by robd on January 06, 2022
powershell, SQL / No Comments

Hello,

Been a while since I posted but here I am!

I recently needed to copy SQL users from one DB to another without changing SIDs etc, while googling how best to do this a colleague just told me to use dbatools.

Well I’m glad I did, they are amazing! If you’re not sure what dbatools is, its PowerShell for SQL!!

Here’s what I did:

Install the tools on my device:

Install-Module dbatools -Scope CurrentUser

Then I simply ran:

Copy-DbaLogin -Source SourceDB -Destination DestDB -force

and thats it.

 

 

Tags: , ,

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 / 1 Comment

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 / 1 Comment

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: , ,