├── 2Pint
└── README.md
├── AD-Delegation
├── ACLforOU
│ ├── Create-ACLStrings.ps1
│ ├── Get-ACLForOU.ps1
│ └── Set-ACLForOU.ps1
├── AD-Delegation - Delete-PrivilegedAccounts
│ └── Delete-PrivilegedAccounts.ps1
├── AD-Delegation - DisableInactivePrivilegedUsers
│ └── DisableInactivePrivilegedUsers.ps1
├── AD-Delegation - Report-ADDelegation
│ ├── Report-AllPrivilegedUsers.ps1
│ ├── Report-PrivilegedRoles.ps1
│ ├── Report-PrivilegedUsers.ps1
│ └── Send-Reports.ps1
├── AD-Delegation - Send-ExpiringPasswordMail
│ └── Send-ExpiringPasswordMail.ps1
├── AD-Delegation - SetPrivilegedAccountInformation
│ └── SetPrivilegedAccountInformation.ps1
├── ADDelegationManager.ps1
├── Check-DenyLogon-Group.ps1
├── Create Least Privilegies Model
│ ├── Add-GroupsToRoles
│ │ ├── Add-GroupsToRoles.ps1
│ │ └── Groups.txt
│ ├── Add-TasksToRoles
│ │ ├── Add-TasksToRoles.ps1
│ │ └── Tasks.txt
│ ├── Add-UsersToRoles
│ │ └── Add-UsersToRoles.ps1
│ ├── Create-Everything.ps1
│ ├── Create-LocalRightsGPOs
│ │ └── Create-LocalRightsGPOs.ps1
│ ├── Create-OUAdminTasks
│ │ └── Create-OUAdminTasks.ps1
│ ├── DelegatedTasks_Domain1_1.0.csv
│ ├── Get-GPTINI
│ │ └── Get-GPTINI.ps1
│ ├── POPADD
│ │ ├── EPPlus.dll
│ │ ├── Export-Excel.ps1
│ │ ├── ImportExel_License.txt
│ │ ├── POPADD.psd1
│ │ ├── POPADD.psm1
│ │ └── TaskID_2.6.xml
│ └── SharedCode.psm1
├── Get-PrivilegedRolesManagers.ps1
├── Get-RolesWithZeroActiveMembers.ps1
├── Get-SensitiveGroupMembers.ps1
├── Get-Tier2UsersWithoutRole.ps1
├── Get-UsersPWExpiryDate.ps1
├── Manage-PrivilegedUser.ps1
├── Set-RolesDescription.ps1
├── Set-RolesInfo.ps1
├── Set-SetResetPWRightOnPrivilegedAccounts.ps1
└── Verify-ServerOUsHaveLocalAdminTasks.ps1
├── ADMXViewer
├── ADMXViewer.ps1
├── MainWindow.xaml
├── README.md
├── admx
│ ├── CredUI.admx
│ ├── GoogleUpdate.admx
│ ├── appv.admx
│ ├── chrome.admx
│ ├── en-US
│ │ ├── GoogleUpdate.adml
│ │ ├── Windows.adml
│ │ ├── appv.adml
│ │ ├── chrome.adml
│ │ └── msedge.adml
│ ├── msedge.admx
│ └── sv-SE
│ │ ├── Windows.adml
│ │ ├── appv.adml
│ │ ├── chrome.adml
│ │ └── msedge.adml
└── images
│ ├── ExampleView.jpg
│ └── icon.png
├── Active Directory
├── ACL
│ └── ACLHistory
│ │ ├── Get-ADACLModifications.ps1
│ │ ├── Modules
│ │ ├── ACLHistoryManagement.psm1
│ │ └── ActiveDirectoryRightsModule.psm1
│ │ ├── Readme.md
│ │ ├── SQL Database
│ │ └── BuildSQLDependencies.txt
│ │ ├── SSRS Report
│ │ └── ACLHistory.rdl
│ │ ├── Scheduled Tasks
│ │ ├── Get-ADACLModifications.xml
│ │ └── Send-ADACLModifications.xml
│ │ └── Send-ADACLModifications.ps1
├── Get-BlockedInheritanceUsers.ps1
├── Get-DeletedObjects.ps1
├── Remove-ADObjectFromACL
│ └── Remove-ADObjectFromACL.ps1
├── SecBaselinePrep
│ ├── Get-RegData_For_SecBaseline.ps1
│ ├── Get-SummaryResult.ps1
│ ├── Get-UserLogonRights.ps1
│ ├── MemberServers-RegistrySummary.csv
│ ├── MemberServers-URASummary.csv
│ ├── README.MD
│ └── SecBaselinesToCompare.csv
└── Set-ADOwnerToDA
│ └── Set-ADOwnerToDA.ps1
├── Azure
└── ConnectToAzure.ps1
├── DNS and DHCP
├── Get-DHCPLog.ps1
├── Get-DNSRecordOwner.ps1
└── Get-FaultyReverseLookupClients.ps1
├── FirewallLogAnalyzer
└── FirewallLogAnalyzer.ps1
├── Get-RadiusLogFile
└── Get-RadiusLogFile.ps1
├── InstallServer
├── InstallServer.ps1
├── img
│ ├── InstallServer_GUI.jpg
│ ├── TS_step_1_-_Start_InstallServer_script.jpg
│ ├── TS_step_2_-_Konfigurera_natverksinstallningar.jpg
│ ├── TS_step_3_-_Satt_lokal_datorbeskrivning.jpg
│ ├── TS_step_4_-_Satt_beskrivning_på_AD-objekt.jpg
│ ├── TS_step_5_-_Lagger_till_servicefonstergrupper.jpg
│ └── TS_step_6_-_Satter_angiven_konfiguration_på_natverkskort.jpg
└── readme.MD
├── LAPS
└── Get-LAPSCompliance.ps1
├── LICENSE
├── Misc Maintenance
└── Handle_Old_Computer_Objects.ps1
├── NTLM
└── Get-AuthenticatedNTLMSessions.ps1
├── New-CustomControl.ps1
├── PSsyslog
├── Get-PSSyslog.ps1
├── Send-TCPUDP.ps1
├── Start-PSSyslog.ps1
├── img
│ └── PSSyslog.gif
└── readme.MD
├── README.md
├── SCCM
├── Add-SiteSystemServer_To_BoundaryGroup.ps1
├── ConfigMgrClientHealthPSReport.ps1
├── Create-MaintenanceCollection.ps1
├── Create-MaintenanceGroup.ps1
├── Create-SoftwareUpdateDeployments.ps1
├── Get-CMBoundariesWithoutDP.ps1
├── Get-MaintenanceWindows.ps1
├── QuickScanScheduler
│ └── QuickScanScheduler.ps1
├── RefreshServerComplianceState
│ ├── Computers.txt
│ ├── RefreshServerComplianceState - Multiple machines.ps1
│ └── RefreshServerComplianceState - Single machine.ps1
├── Remove-DuplicateUsersFromCMDevice.ps1
└── Set-Boundaries_To_Peer-BoundaryGroup.ps1
├── SharedCode.psm1
└── Windows
├── Convert-CSVToExcel.ps1
├── Open-ClientDrive.ps1
├── StartMenuCustomizer.ps1
└── StartMenuCustomizer
├── StartLayout.xml
├── StartLayout2.xml
├── StartMenuCustomizer.ps1
└── Untitled1.xml
/2Pint/README.md:
--------------------------------------------------------------------------------
1 | This module is moved to https://github.com/froxxon/StifleRScripting
2 |
--------------------------------------------------------------------------------
/AD-Delegation/ACLforOU/Create-ACLStrings.ps1:
--------------------------------------------------------------------------------
1 | import-module "C:\temp\sharedcode.psm1"
2 | $ACLs = get-content "C:\temp\Get-ACLForOU\Get-ACLForOU.log"
3 | $Logfile = "C:\temp\set-aclforou\Created ACL strings.txt"
4 |
5 | ForEach ( $ACL in $ACLs ) {
6 | $Group = $($ACL -split ";")[0]
7 | $OU = $($ACL -split ";")[1]
8 | $ACL = $ACL.TrimStart("$Group;$OU;")
9 | Write-Log "Set-ACLForOU -Group ""$Group"" -OU ""$OU"" -AccessRights ""$ACL""" -WritePrefix No
10 | }
--------------------------------------------------------------------------------
/AD-Delegation/ACLforOU/Get-ACLForOU.ps1:
--------------------------------------------------------------------------------
1 | Import-Module -Name ActiveDirectory
2 | Import-Module "C:\Temp\SharedCode.psm1" -Force
3 | $LogFile = "C:\temp\Get-ACLForOU\Get-ACLForOU.log"
4 | $DomainDN = $( Get-ADDomain ).DistinguishedName
5 | Dir AD: | out-null
6 |
7 | Function Get-ACLForOU ($OU,$Group) {
8 | $ShortOU = $OU
9 | $OU = "$OU,$DomainDN"
10 | $OU_ACL = Get-Acl -Path "AD:\$OU"
11 | $OU_SDDL = $OU_ACL.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)
12 | If ( $Group -ne $null ) {
13 | $Group_SID = $(Get-ADGroup "$Group").SID.value
14 | $OU_SDDL = $OU_SDDL.Split('()',[System.StringSplitOptions]::RemoveEmptyEntries)
15 | $Group_ACLs = @()
16 | ForEach ( $Line in $OU_SDDL ) {
17 | If ( $Line -like "*$Group_SID*" ) {
18 | $Line = $Line -replace "$Group_SID",""
19 | $Group_ACLs += $Line
20 | }
21 | }
22 | }
23 | Else {
24 | $OU_SDDL.Split('()',[System.StringSplitOptions]::RemoveEmptyEntries) | Out-GridView
25 | }
26 | }
27 |
28 | Get-ACLForOU -OU "OU=Admin" -Group "Task-OU-FullControl-Admin"
29 |
30 | exit
31 | Get-ACLForOU -OU "OU=Clients" -Group "Task-Computer-Modify_Enabled_Disabled-Clients"
32 | Get-ACLForOU -OU "OU=MaintenanceGroups" -Group "Task-Group-Modify_Members-MaintenanceGroups"
33 | Get-ACLForOU -OU "OU=MaintenanceGroups" -Group "Task-OU-FullControl-MaintenanceGroups"
34 | Get-ACLForOU -OU "OU=Servers" -Group "Task-Computer-Create-Servers"
35 | Get-ACLForOU -OU "OU=Servers" -Group "Task-Computer-Delete-Servers"
36 | Get-ACLForOU -OU "OU=Servers" -Group "Task-OU-Create-Servers"
37 | Get-ACLForOU -OU "OU=Servers" -Group "Task-OU-Delete-Servers"
38 | Get-ACLForOU -OU "OU=Servers" -Group "Task-OU-FullControl-Servers"
39 | Get-ACLForOU -OU "OU=ServiceAccounts" -Group "Task-User-Manage-ServiceAccounts"
40 | Get-ACLForOU -OU "OU=T1-Accounts,OU=Tier 1,OU=Admin" -Group "Task-User-Manage-T1-Accounts"
41 | Get-ACLForOU -OU "OU=T1-Accounts,OU=Tier 1,OU=Admin" -Group "Task-User-Reset_Passwords-T1-Accounts"
42 | Get-ACLForOU -OU "OU=T1-Accounts,OU=Tier 1,OU=Admin" -Group "Task-User-Unlock-T1-Accounts"
43 | Get-ACLForOU -OU "OU=T1-Roles,OU=Tier 1,OU=Admin" -Group "Task-Group-Modify_Members-T1-Roles"
44 | Get-ACLForOU -OU "OU=T2-Accounts,OU=Tier 2,OU=Admin" -Group "Task-User-Manage-T2-Accounts"
45 | Get-ACLForOU -OU "OU=T2-Accounts,OU=Tier 2,OU=Admin" -Group "Task-User-Reset_Passwords-T2-Accounts"
46 | Get-ACLForOU -OU "OU=T2-Accounts,OU=Tier 2,OU=Admin" -Group "Task-User-Unlock-T2-Accounts"
47 | Get-ACLForOU -OU "OU=T2-Roles,OU=Tier 2,OU=Admin" -Group "Task-Group-Modify_Members-T2-Roles"
--------------------------------------------------------------------------------
/AD-Delegation/ACLforOU/Set-ACLForOU.ps1:
--------------------------------------------------------------------------------
1 | Import-Module -Name ActiveDirectory
2 | Import-Module "C:\Temp\SharedCode.psm1"
3 | $Logfile = "C:\Temp\Set-ACLForOU\Set-ACLForOU.log"
4 | $DomainDN = $( Get-ADDomain ).DistinguishedName
5 | Dir AD: | out-null
6 |
7 | Function Set-ACLForOU ($Group,$OU,$AccessRights) {
8 | $OU = "$OU,$DomainDN"
9 | $Group_SID = $(Get-ADGroup "$Group").SID.value
10 | $OU_ACL = Get-Acl -Path "AD:\$OU"
11 | $OU_SDDL = $OU_ACL.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)
12 | $New_SDDL = $OU_SDDL
13 | $New_SDDL += @("($AccessRights$Group_SID)")
14 | Try {
15 | $OU_ACL.SetSecurityDescriptorSddlForm($New_SDDL)
16 | Set-ACL -Path "AD:\$OU" -AclObject $OU_ACL
17 | Write-Log "Added new ACL for the group ""$Group"":"
18 | Write-Log "Applied to OU: $OU"
19 | Write-Log "Group SID: $Group_SID"
20 | Write-Log "Accessrights: $AccessRights"
21 | Write-Log " "
22 | }
23 | Catch {
24 | Write-Log "Couldn't add new ACL for the group ""$Group"":" -LogType ERROR
25 | Write-Log "Applied to OU: $OU" -LogType ERROR
26 | Write-Log "Group SID: $Group_SID" -LogType ERROR
27 | Write-Log "Accessrights: $AccessRights" -LogType ERROR
28 | Write-Log " " -LogType ERROR
29 | }
30 | }
31 |
32 | ### Examples ###
33 | Set-ACLForOU -Group "Task-OU-FullControl-Admin" -OU "OU=Admin" -AccessRights "I;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;"
34 | Set-ACLForOU -Group "Task-Computer-Modify_Enabled_Disabled-Clients" -OU "OU=Clients" -AccessRights "A;CIIO;RPWP;4c164200-20c0-11d0-a768-00aa006e0529;bf967a86-0de6-11d0-a285-00aa003049e2;"
35 | Set-ACLForOU -Group "Task-OU-FullControl-Domain Computers" -OU "OU=Domain Computers" -AccessRights "A;CI;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;"
36 | Set-ACLForOU -Group "Task-Group-Modify_Members-MaintenanceGroups" -OU "OU=MaintenanceGroups" -AccessRights "A;CIIO;RPWP;bf9679c0-0de6-11d0-a285-00aa003049e2;bf967a9c-0de6-11d0-a285-00aa003049e2;"
37 | Set-ACLForOU -Group "Task-OU-FullControl-MaintenanceGroups" -OU "OU=MaintenanceGroups" -AccessRights "A;CI;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;"
38 | Set-ACLForOU -Group "Task-Computer-Create-Servers" -OU "OU=Servers" -AccessRights "A;CI;CC;bf967a86-0de6-11d0-a285-00aa003049e2;;"
39 | Set-ACLForOU -Group "Task-Computer-Delete-Servers" -OU "OU=Servers" -AccessRights "A;CI;DC;bf967a86-0de6-11d0-a285-00aa003049e2;;"
40 | Set-ACLForOU -Group "Task-OU-Create-Servers" -OU "OU=Servers" -AccessRights "A;CIIO;CC;bf967aa5-0de6-11d0-a285-00aa003049e2;bf967aa5-0de6-11d0-a285-00aa003049e2;"
41 | Set-ACLForOU -Group "Task-OU-Delete-Servers" -OU "OU=Servers" -AccessRights "A;CIIO;DT;;bf967aa5-0de6-11d0-a285-00aa003049e2;"
42 | Set-ACLForOU -Group "Task-OU-FullControl-Servers" -OU "OU=Servers" -AccessRights "A;CI;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;"
43 | Set-ACLForOU -Group "Task-User-Manage-T1-Accounts" -OU "OU=T1-Accounts,OU=Tier 1,OU=Admin" -AccessRights "CIIO;CCDCLCSWRPWPDTLOCRSDRCWDWO;;bf967aba-0de6-11d0-a285-00aa003049e2;"
44 | Set-ACLForOU -Group "Task-User-Manage-T1-Accounts" -OU "OU=T1-Accounts,OU=Tier 1,OU=Admin" -AccessRights "CI;CCDC;bf967aba-0de6-11d0-a285-00aa003049e2;;"
45 | Set-ACLForOU -Group "Task-User-Manage-T1-Accounts" -OU "OU=T1-Accounts,OU=Tier 1,OU=Admin" -AccessRights "CIIO;RPWP;bf967a68-0de6-11d0-a285-00aa003049e2;bf967aba-0de6-11d0-a285-00aa003049e2;"
46 | Set-ACLForOU -Group "Task-User-Reset_Passwords-T1-Accounts" -OU "OU=T1-Accounts,OU=Tier 1,OU=Admin" -AccessRights "CIIO;RPWP;bf967a0a-0de6-11d0-a285-00aa003049e2;bf967aba-0de6-11d0-a285-00aa003049e2;"
47 | Set-ACLForOU -Group "Task-User-Reset_Passwords-T1-Accounts" -OU "OU=T1-Accounts,OU=Tier 1,OU=Admin" -AccessRights "CIIO;CR;00299570-246d-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;"
48 | Set-ACLForOU -Group "Task-User-Unlock-T1-Accounts" -OU "OU=T1-Accounts,OU=Tier 1,OU=Admin" -AccessRights "CIIO;RPWP;28630ebf-41d5-11d1-a9c1-0000f80367c1;bf967aba-0de6-11d0-a285-00aa003049e2;"
49 | Set-ACLForOU -Group "Task-Group-Modify_Members-T1-Roles" -OU "OU=T1-Roles,OU=Tier 1,OU=Admin" -AccessRights "CIIO;RPWP;bf9679c0-0de6-11d0-a285-00aa003049e2;bf967a9c-0de6-11d0-a285-00aa003049e2;"
50 | Set-ACLForOU -Group "Task-User-Manage-T2-Accounts" -OU "OU=T2-Accounts,OU=Tier 2,OU=Admin" -AccessRights "CIIO;CCDCLCSWRPWPDTLOCRSDRCWDWO;;bf967aba-0de6-11d0-a285-00aa003049e2;"
51 | Set-ACLForOU -Group "Task-User-Manage-T2-Accounts" -OU "OU=T2-Accounts,OU=Tier 2,OU=Admin" -AccessRights "CI;CCDC;bf967aba-0de6-11d0-a285-00aa003049e2;;"
52 | Set-ACLForOU -Group "Task-User-Manage-T2-Accounts" -OU "OU=T2-Accounts,OU=Tier 2,OU=Admin" -AccessRights "CIIO;RPWP;bf967a68-0de6-11d0-a285-00aa003049e2;bf967aba-0de6-11d0-a285-00aa003049e2;"
53 | Set-ACLForOU -Group "Task-User-Reset_Passwords-T2-Accounts" -OU "OU=T2-Accounts,OU=Tier 2,OU=Admin" -AccessRights "CIIO;RPWP;bf967a0a-0de6-11d0-a285-00aa003049e2;bf967aba-0de6-11d0-a285-00aa003049e2;"
54 | Set-ACLForOU -Group "Task-User-Reset_Passwords-T2-Accounts" -OU "OU=T2-Accounts,OU=Tier 2,OU=Admin" -AccessRights "CIIO;CR;00299570-246d-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;"
55 | Set-ACLForOU -Group "Task-User-Unlock-T2-Accounts" -OU "OU=T2-Accounts,OU=Tier 2,OU=Admin" -AccessRights "CIIO;RPWP;28630ebf-41d5-11d1-a9c1-0000f80367c1;bf967aba-0de6-11d0-a285-00aa003049e2;"
56 | Set-ACLForOU -Group "Task-Group-Modify_Members-T2-Roles" -OU "OU=T2-Roles,OU=Tier 2,OU=Admin" -AccessRights "CIIO;RPWP;bf9679c0-0de6-11d0-a285-00aa003049e2;bf967a9c-0de6-11d0-a285-00aa003049e2;"
--------------------------------------------------------------------------------
/AD-Delegation/AD-Delegation - Delete-PrivilegedAccounts/Delete-PrivilegedAccounts.ps1:
--------------------------------------------------------------------------------
1 | Function Write-Log {
2 | [CmdletBinding()]
3 | param (
4 | [Parameter(Position=0)]
5 | [string]$Message,
6 | [Parameter(Position=1)]
7 | [ValidateSet('INFO','WARN','ERROR')][string]$LogType = 'INFO',
8 | [Parameter(Position=2)]
9 | [ValidateSet('Yes','No')][string]$WritePrefix = 'Yes'
10 | )
11 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
12 | if($Message -eq $null){ $Message = "" }
13 | If ( $WritePrefix -eq "YES" ) {
14 | $LogEntry = "$LogType $CurrentDateTime - $Message"
15 | }
16 | Else {
17 | $LogEntry = "$Message"
18 | }
19 | Add-Content -Value $LogEntry -Path $LogFile -Encoding UTF8
20 | Write-Verbose $LogEntry
21 | }
22 |
23 | $ProdServer = "domain1"
24 | $LookupDomains = @("domain1","domain2")
25 | $ProdStdUsers = "OU=StandardUsers,DC=domain1,DC=local"
26 |
27 | $LogFile = "C:\Program Files (x86)\AMSPgm\Logs\AD-Delegation - Delete-PrivilegedAccounts.log"
28 | Try {
29 | $ProdUsers = $(Get-ADUser -filter * -SearchBase $ProdStdUsers -SearchScope OneLevel -Server $ProdServer).samAccountName
30 | If ( $ProdUsers.Count -gt 14000 ) {
31 | ForEach ( $LookupDomain in $LookupDomains ) {
32 | Write-host "Checking domain: $LookupDomain"
33 | $Domain = $(Get-ADDomain -Server $LookupDomain).Name.ToUpper()
34 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).DistinguishedName
35 | $PrivilegedUsers = $(Get-ADUser -filter 'Enabled -eq $False' -SearchBase "OU=Admin,$DomainDN" -SearchScope Subtree -Server $LookupDomain).samAccountName | Sort samAccountName
36 | ForEach ( $User in $PrivilegedUsers ) {
37 | If ( $User -notlike "Tl0*") {
38 | If ( $ProdUsers -notcontains $($User.Substring(2,5))) {
39 | Try {
40 | Remove-ADUser $User -Server $LookupDomain -Confirm:$false
41 | Write-Log "Removed user: $Domain\$User" -LogType INFO
42 | }
43 | Catch {
44 | Write-Log "Failed to remove user: $Domain\$User" -LogType ERROR
45 | }
46 | }
47 | }
48 | }
49 | }
50 | }
51 | }
52 | Catch {}
--------------------------------------------------------------------------------
/AD-Delegation/AD-Delegation - DisableInactivePrivilegedUsers/DisableInactivePrivilegedUsers.ps1:
--------------------------------------------------------------------------------
1 | Function Write-Log {
2 | [CmdletBinding()]
3 | param (
4 | [Parameter(Position=0)]
5 | [string]$Message,
6 | [Parameter(Position=1)]
7 | [ValidateSet('INFO','WARN','ERROR')][string]$LogType = 'INFO',
8 | [Parameter(Position=2)]
9 | [ValidateSet('Yes','No')][string]$WritePrefix = 'Yes'
10 | )
11 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
12 | if($Message -eq $null){ $Message = "" }
13 | If ( $WritePrefix -eq "YES" ) {
14 | $LogEntry = "$LogType $CurrentDateTime - $Message"
15 | }
16 | Else {
17 | $LogEntry = "$Message"
18 | }
19 | Add-Content -Value $LogEntry -Path $LogFile -Encoding UTF8
20 | Write-Verbose $LogEntry
21 | }
22 |
23 | $ProdServer = "domain1.local"
24 | $LookupDomains = @("domain1","domain2")
25 | $ProdStdUsers = "OU=StandardUsers,DC=domain1,DC=local"
26 |
27 | $LogFile = "C:\Program Files (x86)\AMSPgm\Logs\AD-Delegation - DisableInactiveProdUsers.log"
28 | $DisabledStandardUsers = $(Get-ADUser -filter 'Enabled -eq $False' -SearchBase $ProdStdUsers | Sort ).samAccountName
29 |
30 | ForEach ( $LookupDomain in $LookupDomains ) {
31 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).DistinguishedName
32 | $PrivilegedUsers = $(Get-ADUser -filter 'Enabled -eq $True' -SearchBase "OU=Admin,$DomainDN" -Server $LookupDomain | Sort ).samAccountName
33 | #$DAs = $(Get-ADGroupMember "Domain Admins" -Recursive -Server $LookupDomain).samAccountName
34 | ForEach ( $User in $PrivilegedUsers ) {
35 | If ( $User -notlike "l0*" ) {
36 | #If ( $DAs -notcontains $User ) {
37 | If ( $DisabledStandardUsers -contains $($User.SubString(2,5)) ) {
38 | Try {
39 | Disable-ADAccount $User -Server $LookupDomain
40 | write-Log "$DomainDN\$User disabled because standard account is disabled in Prod" -LogType INFO
41 | }
42 | Catch {
43 | write-Log "$DomainDN\$User disabled unsuccessfully (1)" -LogType ERROR
44 | }
45 | }
46 | }
47 | }
48 | $InactiveUsers = $(Get-ADUser -filter "LastLogonTimestamp -lt $((Get-Date).AddDays(-194).ToFileTimeUTC()) -and Enabled -eq 'True'" -SearchBase "OU=Admin,$DomainDN" -SearchScope Subtree -Server $LookupDomain).samAccountName
49 | ForEach ( $User in $InactiveUsers ) {
50 | If ( $User -notlike "T0*" ) {
51 | Try {
52 | Disable-ADAccount $User -Server $LookupDomain
53 | write-Log "Disabled $DomainDN\$User due to inactivity for 194 days" -LogType INFO
54 | }
55 | Catch {
56 | write-Log "$DomainDN\$User disabled unsuccessfully (2)" -LogType ERROR
57 | }
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/AD-Delegation/AD-Delegation - Report-ADDelegation/Send-Reports.ps1:
--------------------------------------------------------------------------------
1 | Function Write-Log {
2 | [CmdletBinding()]
3 | param (
4 | [Parameter(Position=0)]
5 | [string]$Message,
6 | [Parameter(Position=1)]
7 | [ValidateSet('INFO','WARN','ERROR')][string]$LogType = 'INFO',
8 | [Parameter(Position=2)]
9 | [ValidateSet('Yes','No')][string]$WritePrefix = 'Yes'
10 | )
11 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
12 | if($Message -eq $null){ $Message = "" }
13 | If ( $WritePrefix -eq "YES" ) {
14 | $LogEntry = "$LogType $CurrentDateTime - $Message"
15 | }
16 | Else {
17 | $LogEntry = "$Message"
18 | }
19 | Add-Content -Value $LogEntry -Path $LogFile -Encoding UTF8
20 | Write-Verbose $LogEntry
21 | }
22 |
23 | $LogFile = "C:\Program Files (x86)\Logs\AD-Delegation - Send-AD-Delegation-reports.log"
24 | $ReportSource = "C:\Program Files (x86)\Logs\AD-Delegation - Report-ADDelegation\Temp"
25 | $Reports = $(Get-Childitem $ReportSource).Name.Replace(".html","")
26 |
27 | ForEach ( $Report in $Reports ) {
28 | $Manager = $Null
29 | $MailAddress = $Null
30 | If ( $Report -notlike "*AllDomains" ) {
31 | $Manager = $Report.Substring($($Report.Length)-5)
32 | Try {
33 | $MailAddress = $(Get-ADUser $Manager -Properties mail).mail
34 | }
35 | Catch {
36 | }
37 | }
38 | If ( $Report -like "*AllDomains" ) { $MailAddress = "security@domain1.local" }
39 | If ( $Report -like "*AllDomains" ) {
40 | $Type = "summary"
41 | $Subject = "AD-Delegation - Summary of privileged accounts"
42 | $MailBody = @"
43 | Hi!
44 | "@
45 | }
46 | If ( $Report -like "*Your employed privileged users*" ) {
47 | $Type = "users"
48 | $Subject = "AD-Delegation - Your employed privileged users"
49 | $MailBody = @"
50 | Hi!
51 | "@
52 | }
53 | If ( $Report -like "*Your privileged roles*" ) {
54 | $Type = "roles"
55 | $Subject = "AD-Delegation - Your privileged roles"
56 | $MailBody = @"
57 | Hi!
58 | "@
59 | }
60 | If ( $MailAddress -ne $Null ) {
61 | Try {
62 | Send-MailMessage -Encoding utf8 -Priority High -Body $MailBody -To $MailAddress -from "noreply@domain1.local" -SmtpServer "smtp.domain1.local" -subject $Subject -Attachments "$ReportSource\$($Report).html"
63 | sleep -Seconds 10
64 | Write-Log "Sent $Type report to $MailAddress"
65 | Remove-Item "$ReportSource\$($Report).html"
66 | }
67 | Catch {
68 | Write-Log "Failed to send report to $MailAddress"
69 | }
70 | #}
71 | }
72 | }
--------------------------------------------------------------------------------
/AD-Delegation/AD-Delegation - Send-ExpiringPasswordMail/Send-ExpiringPasswordMail.ps1:
--------------------------------------------------------------------------------
1 | Function Write-Log {
2 | [CmdletBinding()]
3 | param (
4 | [Parameter(Position=0)]
5 | [string]$Message,
6 | [Parameter(Position=1)]
7 | [ValidateSet('INFO','WARN','ERROR')][string]$LogType = 'INFO',
8 | [Parameter(Position=2)]
9 | [ValidateSet('Yes','No')][string]$WritePrefix = 'Yes'
10 | )
11 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
12 | if($Message -eq $null){ $Message = "" }
13 | If ( $WritePrefix -eq "YES" ) {
14 | $LogEntry = "$LogType $CurrentDateTime - $Message"
15 | }
16 | Else {
17 | $LogEntry = "$Message"
18 | }
19 | Add-Content -Value $LogEntry -Path $LogFile -Encoding UTF8
20 | Write-Verbose $LogEntry
21 | }
22 |
23 | $LogFile = "C:\Program Files (x86)\AMSPgm\Logs\AD-Delegation - Report Expiring Password.log"
24 |
25 | $LookupDomains = @("domain1","domain2")
26 | $Users = @()
27 | $UserProperties = @{}
28 | $ProdServer = "domain1.local"
29 |
30 | ForEach ( $LookupDomain in $LookupDomains ) {
31 | $DomainName = $($( Get-ADDomain -Server $LookupDomain).Name).ToUpper()
32 | $DomainDN = $( Get-ADDomain -Server $LookupDomain).DistinguishedName
33 |
34 | $ExpiringPWUsers = Get-ADUser -Filter "name -like ""t*adm"" -and Enabled -eq 'true'" -SearchBase "OU=Admin,$DomainDN" -SearchScope Subtree –Properties “samAccountName”, “msDS-UserPasswordExpiryTimeComputed” -Server $LookupDomain | Select-Object -Property “samAccountName”,@{Name=“ExpiryDate”;Expression={[datetime]::FromFileTime($_.“msDS-UserPasswordExpiryTimeComputed”)}}
35 | $Today = (get-date)
36 | ForEach ( $User in $ExpiringPWUsers ) {
37 | If ( $User.ExpiryDate -ne $Null ) {
38 | $DaysToExpire = (New-TimeSpan -Start $Today -End ($User.ExpiryDate)).Days
39 | If (($DaysToExpire -eq 3) -or ($DaysToExpire -eq 10) ) {
40 | $UserProperties.samAccountName = $User.samAccountName
41 | $UserProperties.shortName = $($User.samAccountName).Substring(2,5)
42 | Try {
43 | $MailExists = $($($Users | Where { $_.shortName -like $UserProperties.shortName } | Select MailAddress)[0]).MailAddress
44 | }
45 | Catch { $MailExists = $Null }
46 | If ( $MailExists -eq $Null ) {
47 | $UserAttributes = Get-ADUser $($User.samAccountName).Substring(2,5) -properties mail, givenName -Server $ProdServer | Select mail, givenName
48 | $UserProperties.MailAddress = $UserAttributes.mail
49 | $UserProperties.givenName = $UserAttributes.givenName
50 | $UserProperties.DaysToExpire = $DaysToExpire
51 | $UserProperties.Domain = $DomainName
52 | }
53 | Else {
54 | $UserProperties.MailAddress = $($($Users | Where { $_.shortName -like $UserProperties.shortName } | Select MailAddress)[0]).MailAddress
55 | $UserProperties.givenName = $($($Users | Where { $_.shortName -like $UserProperties.shortName } | Select givenName)[0]).givenName
56 | $UserProperties.DaysToExpire = $DaysToExpire
57 | $UserProperties.Domain = $DomainName
58 | }
59 | $Users += $(New-Object PSobject -Property $UserProperties)
60 | }
61 | }
62 | }
63 | }
64 |
65 | ForEach ( $User in $($Users | where { $_.DaysToExpire -eq 3 -or $_.DaysToExpire -eq 10 } ) ) {
66 | $HowToChange = "Change password by logging into a machine and press Ctrl+Alt+Delete (End if remote) and choose ""Change password...""."
67 | }
68 |
69 | $MailBody =""
70 |
71 | Try {
72 | Send-MailMessage -Encoding utf8 -Priority High -Body $MailBody -To $User.MailAddress -from "mail@domain1.local" -SmtpServer "smtp.domain1.local" -subject "One of your passwords are about to expire."
73 | Write-log "Successfully sent mail to $($User.MailAddress) that the password for $($User.Domain)\$($User.samAccountName) will expire in $($UserProperties.DaysToExpire) days"
74 | }
75 | Catch {
76 | Write-Log "Failed to send mail to $($User.MailAddress) that the password for $($User.Domain)\$($User.samAccountName) will expire in $($UserProperties.DaysToExpire) days" -LogType ERROR
77 | }
78 | }
--------------------------------------------------------------------------------
/AD-Delegation/AD-Delegation - SetPrivilegedAccountInformation/SetPrivilegedAccountInformation.ps1:
--------------------------------------------------------------------------------
1 | Function Write-Log {
2 | [CmdletBinding()]
3 | param (
4 | [Parameter(Position=0)]
5 | [string]$Message,
6 | [Parameter(Position=1)]
7 | [ValidateSet('INFO','WARN','ERROR')][string]$LogType = 'INFO',
8 | [Parameter(Position=2)]
9 | [ValidateSet('Yes','No')][string]$WritePrefix = 'Yes'
10 | )
11 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
12 | if($Message -eq $null){ $Message = "" }
13 | If ( $WritePrefix -eq "YES" ) {
14 | $LogEntry = "$LogType $CurrentDateTime - $Message"
15 | }
16 | Else {
17 | $LogEntry = "$Message"
18 | }
19 | Add-Content -Value $LogEntry -Path $LogFile -Encoding UTF8
20 | Write-Verbose $LogEntry
21 | }
22 |
23 | $ProdServer = "domain1"
24 | $LookupDomains = @("domain1","domain2")
25 | $ProdStdUsers = "OU=StandardUsers,DC=domain1,DC=local"
26 |
27 | # Sets information on the privileged accounts based on attributes from standard user in wp.ams.se
28 | Function SetInformation () {
29 | $LogFile = "C:\Program Files (x86)\AMSPgm\Logs\AD-Delegation - SetPrivilegedAccountInformation.log"
30 | $Counter = 0
31 | ForEach ( $LookupDomain in $LookupDomains ) {
32 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).DistinguishedName
33 | $Domain = $(Get-ADDomain -Server $LookupDomain).Name.ToUpper()
34 | $PrivilegedUsers = $(Get-ADUser -filter 'Enabled -eq $True' -SearchBase "OU=Admin,$DomainDN" -Server $LookupDomain -Properties samAccountName, info, title, department, streetAddress, postalAddress, postalCode, l | Sort samAccountName)
35 | ForEach ( $User in $PrivilegedUsers ) {
36 | If ( $User.samAccountName -notlike "T0*" ) {
37 | $UserAttributes = $(Get-ADUser -LDAPFilter "(name=$($User.samAccountName.Substring(2,5)))" -SearchBase $ProdStdUsers -Server $ProdServer -Properties Manager,department,postalAddress,postalCode,streetAddress,l,title,extensionAttribute2)
38 | If ( $UserAttributes.Title -ne $Null ) {
39 | If ( $UserAttributes.Title -ne $User.Title ) {
40 | Try {
41 | Set-ADUSer $User.samAccountName -Server $LookupDomain -Replace @{title="$($UserAttributes.Title)"}
42 | Write-Log "$Domain\$($User.samAccountName) - Changes where made to the attribute ""title"", from ""$($User.Title)"" to ""$($UserAttributes.Title)""" -LogType INFO
43 | }
44 | Catch {
45 | Write-Log "$Domain\$($User.samAccountName) - Couldn't apply changes to the attribute ""title"", from ""$($User.Title)"" to ""$($UserAttributes.Title)""" -LogType ERROR
46 | }
47 | }
48 | }
49 | If ( $UserAttributes.Department -ne $Null ) {
50 | If ( $UserAttributes.Department -ne $User.Department ) {
51 | Try {
52 | Set-ADUSer $User.samAccountName -Server $LookupDomain -Replace @{department="$($UserAttributes.Department)"}
53 | Write-Log "$Domain\$($User.samAccountName) - Changes where made to the attribute ""department"", from ""$($User.Department)"" to ""$($UserAttributes.Department)""" -LogType INFO
54 | }
55 | Catch {
56 | Write-Log "$Domain\$($User.samAccountName) - Couldn't apply changes to the attribute ""department"", from ""$($User.Department)"" to ""$($UserAttributes.Department)""" -LogType ERROR
57 | }
58 | }
59 | }
60 | If ( $UserAttributes.StreetAddress -ne $Null ) {
61 | If ( $UserAttributes.StreetAddress -ne $User.StreetAddress ) {
62 | Try {
63 | Set-ADUSer $User.samAccountName -Server $LookupDomain -Replace @{streetAddress="$($UserAttributes.StreetAddress)"}
64 | Write-Log "$Domain\$($User.samAccountName) - Changes where made to the attribute ""streetAddress"", from ""$($User.StreetAddress)"" to ""$($UserAttributes.StreetAddress)""" -LogType INFO
65 | }
66 | Catch {
67 | Write-Log "$Domain\$($User.samAccountName) - Couldn't apply changes to the attribute ""steetAddress"", from ""$($User.StreetAddress)"" to ""$($UserAttributes.StreetAddress)""" -LogType ERROR
68 | }
69 | }
70 | }
71 | If ( $UserAttributes.PostalAddress -ne $Null ) {
72 | If ( $UserAttributes.PostalAddress -ne $User.PostalAddress ) {
73 | Try {
74 | Set-ADUSer $User.samAccountName -Server $LookupDomain -Replace @{postalAddress="$($UserAttributes.postalAddress)"}
75 | Write-Log "$Domain\$($User.samAccountName) - Changes where made to the attribute ""postalAddress"", from ""$($User.postalAddress)"" to ""$($UserAttributes.postalAddress)""" -LogType INFO
76 | }
77 | Catch {
78 | Write-Log "$Domain\$($User.samAccountName) - Couldn't apply changes to the attribute ""postalAddress"", from ""$($User.postalAddress)"" to ""$($UserAttributes.postalAddress)""" -LogType ERROR
79 | }
80 | }
81 | }
82 | If ( $UserAttributes.PostalCode -ne $Null ) {
83 | If ( $UserAttributes.PostalCode -ne $User.PostalCode) {
84 | Try {
85 | Set-ADUSer $User.samAccountName -Server $LookupDomain -Replace @{postalCode="$($UserAttributes.PostalCode)"}
86 | Write-Log "$Domain\$($User.samAccountName) - Changes where made to the attribute ""postalCode"", from ""$($User.postalCode)"" to ""$($UserAttributes.postalCode)""" -LogType INFO
87 | }
88 | Catch {
89 | Write-Log "$Domain\$($User.samAccountName) - Couldn't apply changes to the attribute ""postalCode"", from ""$($User.postalCode)"" to ""$($UserAttributes.postalCode)""" -LogType ERROR
90 | }
91 | }
92 | }
93 | If ( $UserAttributes.l -ne $Null ) {
94 | If ( $UserAttributes.l -ne $User.l) {
95 | Try {
96 | Set-ADUSer $User.samAccountName -Server $LookupDomain -Replace @{l="$($UserAttributes.l)"}
97 | Write-Log "$Domain\$($User.samAccountName) - Changes where made to the attribute ""l (location)"", from ""$($User.l)"" to ""$($UserAttributes.l)""" -LogType INFO
98 | }
99 | Catch {
100 | Write-Log "$Domain\$($User.samAccountName) - Couldn't apply changes to the attribute ""l (location)"", from ""$($User.l)"" to ""$($UserAttributes.l)""" -LogType ERROR
101 | }
102 | }
103 | }
104 | If ( $UserAttributes.Manager -ne $Null -or $UserAttributes.extensionAttribute2 -ne $Null ) {
105 | If ( $UserAttributes.Manager -ne $Null ) {
106 | $Manager = $UserAttributes.Manager.SubString(3,5)
107 | }
108 | Else {
109 | $Manager = ""
110 | }
111 | $ExtensionAttribute2 = $UserAttributes.extensionAttribute2
112 | $NewInfo = "Manager: $Manager`r`n`extensionAttribute2: $ExtensionAttribute2"
113 | If ( $NewInfo -ne $($User.info) ) {
114 | Try {
115 | Set-ADUSer $User.samAccountName -Server $LookupDomain -Replace @{info="$NewInfo"}
116 | If ( $User.Info -notlike "*$($UserAttributes.Manager.SubString(3,5))*" ) {
117 | If ( $User.Info -like "*Manager:*" ) {
118 | $OldManager = $User.Info.Split()[1]
119 | }
120 | Else {
121 | $OldManager = ""
122 | }
123 | Write-Log "$Domain\$($User.samAccountName) - Changes where made to the attribute ""info (manager)"", from ""$OldManager"" to ""$Manager""" -LogType INFO
124 | }
125 | If ( $User.Info -notlike "*$($UserAttributes.extensionAttribute2)*" ) {
126 | If ( $User.Info -like "*extensionAttribute2:*" ) {
127 | $OldExtensionAttribute2 = $User.Info.Split()[4]
128 | }
129 | Else {
130 | $OldExtensionAttribute2 = ""
131 | }
132 | Write-Log "$Domain\$($User.samAccountName) - Changes where made to the attribute ""info (extensionAttribute2)"", from ""$OldExtensionAttribute2"" to ""$ExtensionAttribute2""" -LogType INFO
133 | }
134 | }
135 | Catch {
136 | }
137 | }
138 | }
139 | Else {
140 | If ( $UserAttributes.Manager -eq $Null ) {
141 | Write-Log "$Domain\$($User.samAccountName) - The attribute ""manager"" is empty" -LogType ERROR
142 | }
143 | If ( $UserAttributes.extensionAttribute2 ) {
144 | Write-Log "$Domain\$($User.samAccountName) - The attribute ""extensionAttribute2"" is empty" -LogType ERROR
145 | }
146 | }
147 | }
148 | }
149 | }
150 | }
151 |
152 | SetInformation
--------------------------------------------------------------------------------
/AD-Delegation/Check-DenyLogon-Group.ps1:
--------------------------------------------------------------------------------
1 | $LookupDomains = @("domain1","domain2")
2 | $TaskName = "Task-Computer-DenyLogon-T1"
3 |
4 | ForEach ( $LookupDomain in $LookupDomains ) {
5 | $DomainDN = $(Get-ADDOmain -Server $LookupDomain).DistinguishedName
6 | $Roles = $(Get-ADGroup -filter * -SearchBase "OU=T1-Roles,OU=Tier 1,OU=Admin,$DomainDN" -Properties memberOf -Server $LookupDomain | Where memberOf -notcontains "CN=$TaskName,OU=T0-Tasks,OU=Tier 0,OU=Admin,$DomainDN").Name
7 | ForEach ( $Role in $Roles ) {
8 | Add-ADGroupMember -Identity $TaskName -Members $Role -Server $LookupDomain
9 | }
10 | Write-host "Domain: $LookupDomain"
11 | $Roles
12 | $Roles.Count
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/Add-GroupsToRoles/Add-GroupsToRoles.ps1:
--------------------------------------------------------------------------------
1 | Import-module 'C:\temp\SharedCode.psm1'
2 | $LogFile = "C:\temp\Add-GroupsToRoles\Add-GroupsToRoles.log"
3 |
4 | $Data = Get-Content "C:\temp\Add-GroupsToRoles\Groups.txt"
5 |
6 | ForEach( $AllGroups in $Data ) {
7 | $Groups = $AllGroups -split ";"
8 | $DestGroup = $Groups[0]
9 | $DestGroup = get-adgroup $DestGroup
10 | Write-Log
11 | Write-Log "Destinationgroup is $Destgroup"
12 | $GroupCount = $Groups.Count - 1
13 | Write-Log "Antal grupper som ska läggas till: $GroupCount"
14 | $i = 0
15 | ForEach ( $Group in $Groups ) {
16 | # Går igenom samtliga grupper i listan förutom den första kolumnen som är gruppen de resterande ska adderas till
17 | If( $i -ne 0 ) {
18 | $Group = get-adgroup $Group
19 | $GroupName = $Group.Name
20 | Try {
21 | Add-ADPrincipalGroupMembership -identity:$DestGroup -memberof:$Group
22 | Write-Log "($i) Addded $GroupName"
23 | }
24 | Catch {
25 | Write-Log "($i) Couldn't add $GroupName" -LogType ERROR
26 | }
27 | }
28 | $i++
29 | }
30 | }
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/Add-GroupsToRoles/Groups.txt:
--------------------------------------------------------------------------------
1 | Role-T1-Operations;AGPMReviewers
2 | Role-T1-COM;DNSAdmins;DHCP Administrators;Task-Server-LocalUser-Adminservers
3 | Role-T1-SharePoint;Task-Server-LocalAdmin-Sharepoint;Task-Server-LocalUser-Adminservers
4 | Role-T1-Storage;Task-Server-LocalAdmin-StorageServers
5 | Role-T2-Messaging;RemoteAssistanceAdmin
6 | Role-T2-Operations;RemoteAssistanceAdmin
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/Add-TasksToRoles/Add-TasksToRoles.ps1:
--------------------------------------------------------------------------------
1 | Import-module 'C:\temp\SharedCode.psm1'
2 | $LogFile = "C:\temp\Add-TasksToRoles\Add-TasksToRoles.log"
3 |
4 | $Data = Get-Content "C:\temp\Add-TasksToRoles\Tasks.txt"
5 |
6 | ForEach( $AllTasks in $Data ) {
7 | If ( $AllTasks -like '#*') { continue }
8 | $Groups = $AllTasks -split ";"
9 | $DestGroup = $Groups[0]
10 | $DestGroup = get-adgroup $DestGroup
11 | Write-Log
12 | Write-Log "Destinationgroup is $Destgroup"
13 | $GroupCount = $Groups.Count - 1
14 | Write-Log "Antal grupper som ska läggas till: $GroupCount"
15 | $i = 0
16 | ForEach ( $Group in $Groups ) {
17 | # Går igenom samtliga tasks i listan förutom den första kolumnen som är gruppen de resterande ska adderas till
18 | If( $i -ne 0 ) {
19 | $Group = get-adgroup $Group
20 | $GroupName = $Group.Name
21 | Try {
22 | Add-ADPrincipalGroupMembership -identity:$Group -memberof:$DestGroup
23 | Write-Log "($i) Addded $GroupName"
24 | }
25 | Catch {
26 | Write-Log "($i) Couldn't add $GroupName" -LogType ERROR
27 | }
28 | }
29 | $i++
30 | }
31 | }
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/Add-TasksToRoles/Tasks.txt:
--------------------------------------------------------------------------------
1 | Task-Server-LocalAdmin-Exchange;Role-T1-Messaging
2 | Task-Server-LocalAdmin-Network Adminservers;Role-T1-COM
3 | Task-Server-LocalAdmin-Radius;Role-T1-COM
4 | Task-Server-LocalAdmin-SCOM;Role-T1-Monitoring
5 | Task-Server-LocalAdmin-Sharepoint;Role-T1-SharePoint
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/Add-UsersToRoles/Add-UsersToRoles.ps1:
--------------------------------------------------------------------------------
1 | Function AddUserToGroup ($User,$Tier,$Role) {
2 | $UserExist = Get-ADUser -LDAPFilter "(sAMAccountName=l$Tier$User)"
3 | If ($UserExist -ne $Null) {
4 | Try {
5 | Add-ADPrincipalGroupMembership -identity:"l$Tier$User" -memberof:"Role-T$Tier-$Role"
6 | Write-Log "Added l$Tier$User to Role-T$Tier-$Role"
7 | }
8 | Catch {
9 | Write-Log "Couldn't add l$Tier$User to Role-T$Tier-$Role" -LogType ERROR
10 | }
11 | }
12 | }
13 |
14 | Import-module 'C:\temp\SharedCode.psm1'
15 | $LogFile = "C:\temp\LeastPrivilegies\Add-UsersToRoles\Add-UsersToRoles.log"
16 |
17 | $Users = $(Get-ADUser -LDAPFilter "(name=*adm)" -SearchBase "OU=AdminUsers,$DomainDN").Name
18 | ForEach ( $User in $Users ) {
19 |
20 | $Groups = Get-ADPrincipalGroupMembership $User | select name
21 | ForEach ( $Group in $Groups ){
22 | # If ( $Group.Name -eq "ITAApplikationAdmins" ) {
23 | # AddUserToGroup -User $User -Tier "1" -Role "Application"
24 | # AddUserToGroup -User $User -Tier "2" -Role "Application"
25 | # }
26 | # If ( $Group.Name -eq "ITAInfraAdmins" ) {
27 | # AddUserToGroup -User $User -Tier "0" -Role "Infrastructure"
28 | # AddUserToGroup -User $User -Tier "1" -Role "Infrastructure"
29 | # AddUserToGroup -User $User -Tier "2" -Role "Infrastructure"
30 | # }
31 | # If ( $Group.Name -eq "ITADriftAdmins" ) {
32 | # AddUserToGroup -User $User -Tier "1" -Role "Operations"
33 | # AddUserToGroup -User $User -Tier "2" -Role "Operations"
34 | # }
35 | # If ( $Group.Name -eq "ITAMessagingAdmins" ) {
36 | # AddUserToGroup -User $User -Tier "1" -Role "Messaging"
37 | # AddUserToGroup -User $User -Tier "2" -Role "Messaging"
38 | # }
39 | # If ( $Group.Name -eq "ITAPrintAdmins" ) {
40 | # AddUserToGroup -User $User -Tier "1" -Role "Print"
41 | # AddUserToGroup -User $User -Tier "2" -Role "Print"
42 | # }
43 | # If ( $Group.Name -eq "PISASSOAdmins" ) {
44 | # AddUserToGroup -User $User -Tier "1" -Role "IAM"
45 | # }
46 | # If ( $Group.Name -eq "SANAdmins" ) {
47 | # AddUserToGroup -User $User -Tier "1" -Role "Storage"
48 | # }
49 | If ( $Group.Name -eq "ServicedeskAdmins" ) {
50 | AddUserToGroup -User $User -Tier "1" -Role "Servicedesk"
51 | AddUserToGroup -User $User -Tier "2" -Role "Servicedesk"
52 | }
53 | If ( $Group.Name -eq "ServicedeskAdminAdmins" ) {
54 | AddUserToGroup -User $User -Tier "1" -Role "Administration"
55 | }
56 | If ( $Group.Name -eq "ServicedeskOfficeAdmins" ) {
57 | AddUserToGroup -User $User -Tier "1" -Role "Office"
58 | AddUserToGroup -User $User -Tier "2" -Role "Servicedesk"
59 | }
60 | If ( $Group.Name -eq "ServicedeskPCAdmins" ) {
61 | AddUserToGroup -User $User -Tier "1" -Role "PC"
62 | AddUserToGroup -User $User -Tier "2" -Role "PC"
63 | }
64 | # If ( $Group.Name -eq "SharepointAdmins" ) {
65 | # AddUserToGroup -User $User -Tier "1" -Role "Sharepoint"
66 | # }
67 | # If ( $Group.Name -eq "VMWareAdmins" ) {
68 | # AddUserToGroup -User $User -Tier "1" -Role "VIP"
69 | # }
70 | }
71 |
72 | }
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/Create-Everything.ps1:
--------------------------------------------------------------------------------
1 | $SourcePath = "C:\Temp\Create least Privilege Model"
2 | Import-module "$SourcePath\SharedCode.psm1"
3 | $LogFile = "$SourcePath\Create-Everything.log"
4 | CD C:\Temp\CM2012Scripts
5 |
6 | $Template = "$SourcePath\DelegatedTasks_Domain1_1.0.csv"
7 |
8 | Write-Log "--- Start of log ---"
9 | Write-Log
10 |
11 | Import-module "$SourcePath\POPADD\POPADD.psd1"
12 | Write-Log "Imported the module POPADD"
13 |
14 | Add-DelegationOUs
15 | Write-Log "Created the OU-structure for least privilegies"
16 |
17 | Add-RolesAndTasks -template $Template
18 | Write-Log "Added the roles and tasks in the templatefile"
19 |
20 | Add-TaskPermissions -template $Template
21 | Write-Log "Added permissions to tasks"
22 |
23 | Write-Log "Creating tasks for LocalRights on Server-OU:s"
24 | .\Create-OUAdminTasks\Create-OUAdminTasks.ps1
25 | $Log = Get-Content .\Create-OUAdminTasks\Create-OUAdminTasks.log
26 | If ( $Log -like "*Error*" ) {
27 | Write-Log "Created tasks for LocalRights on Server-OU:s, but the log contains errormessages" -LogType ERROR
28 | }
29 | Else {
30 | Write-Log "Created tasks for LocalRights on Server-OU:s"
31 | }
32 |
33 | Write-Log "Adding groups to roles"
34 | .\Add-GroupsToRoles\Add-GroupsToRoles.ps1
35 | $Log = Get-Content .\Add-GroupsToRoles\Add-GroupsToRoles.log
36 | If ( $Log -like "*Error*" ) {
37 | Write-Log "Added groups to roles, but the log contains errormessages" -LogType ERROR
38 | }
39 | Else {
40 | Write-Log "Added groups to roles"
41 | }
42 |
43 | Write-Log "Adding tasks to roles"
44 | .\Add-TasksToRoles\Add-TasksToRoles.ps1
45 | $Log = Get-Content .\Add-TasksToRoles\Add-TasksToRoles.log
46 | If ( $Log -like "*Error*" ) {
47 | Write-Log "Added tasks to roles, but the log contains errormessages" -LogType ERROR
48 | }
49 | Else {
50 | Write-Log "Added tasks to roles"
51 | }
52 |
53 | .\Create-ADMAccounts\Create-ADMAccounts.ps1
54 | $Log = Get-Content .\Create-ADMAccounts\Create-ADMAccounts.log
55 | If ( $Log -like "*Error*" ) {
56 | Write-Log "Created adminaccounts, but the log contains errormessages" -LogType ERROR
57 | }
58 | Else {
59 | Write-Log "Created adminaccounts"
60 | }
61 |
62 | Write-Log "Creating GPO:s for LocalRights on Server-OU:s"
63 | .\Create-LocalRightsGPOs\Create-LocalRightsGPOs.ps1
64 | $Log = Get-Content .\Create-LocalRightsGPOs\Create-LocalRightsGPOs.log
65 | If ( $Log -like "*Error*" ) {
66 | Write-Log "Created GPO:s for LocalRights on Server-OU:s, but the log contains errormessages" -LogType ERROR
67 | }
68 | Else {
69 | Write-Log "Created GPO:s for LocalRights on Server-OU:s"
70 | }
71 |
72 | Write-Log "Adding users to roles"
73 | .\Add-UsersToRoles\Add-UsersToRoles.ps1
74 | $Log = Get-Content .\Add-UsersToRoles\Add-UsersToRoles.log
75 | If ( $Log -like "*Error*" ) {
76 | Write-Log "Added users to roles, but the log contains errormessages" -LogType ERROR
77 | }
78 | Else {
79 | Write-Log "Added users to roles"
80 | }
81 |
82 | Write-Log
83 | Write-Log "--- End of log ---"
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/Create-LocalRightsGPOs/Create-LocalRightsGPOs.ps1:
--------------------------------------------------------------------------------
1 | Import-module 'C:\temp\SharedCode.psm1'
2 | $LogFile = "C:\temp\Create-LocalRightsGPOs\Create-LocalRightsGPOs.log"
3 |
4 | $DC = Get-ADDomainController -Discover -Domain $Domain
5 | $QueryGroups = "Task-Server-Local*"
6 | $GPOs = $(Get-ADGroup -Server $DC -Filter {name -like $QueryGroups}).Name
7 |
8 | Write-Log "Will try to create $($GPOs.Count) group policies on the following domain controller $DC"
9 | Write-Log
10 |
11 | ForEach ( $GPO in $GPOs ) {
12 |
13 | # Creating GPO
14 | Try {
15 | New-GPO -Server $DC -Name $GPO | out-null
16 | Write-Log "Created the GPO $GPO"
17 | }
18 | Catch {
19 | Write-Log "Couldn't create the GPO $GPO" -LogType ERROR
20 | }
21 |
22 | # Set the GPOStatus
23 | Try {
24 | If ( (get-gpo $GPO -Server $DC).gpostatus -ne "UserSettingsDisabled" ) {
25 | (get-gpo $GPO -server $DC).gpostatus = "UserSettingsDisabled"
26 | Write-Log "Changed GPOStatus to UserSettingsDisabled for $GPO"
27 | }
28 | Write-Log "The GPOStatus for $GPO is already set to UserSettingsDisabled"
29 | }
30 | Catch {
31 | Write-Log "Couldn't change GPOStatus to UserSettingsDisabled" -LogType ERROR
32 | }
33 |
34 | # Create the GptTmp.inf file
35 | Try {
36 | $GPOGuid = $(Get-GPO $GPO -Server $DC).id
37 | $GPOGuid = "{" + $GPOGuid + "}"
38 | Write-Log "Group policy GUID to create the GptTmp.inf file for: $GPOGuid"
39 | $SecGroupSid = (Get-ADGroup $GPO -Server $DC).SID.Value
40 | Write-Log "The SID is $SecGroupSid for the group $GPO"
41 | Write-Log "Creating the folderstructure for \\$DC\SYSVOL\$Domain\Policies\$GPOGuid\Machine\Microsoft\Windows NT\SecEdit"
42 | If (!(Test-Path "\\$DC\SYSVOL\$Domain\Policies\$GPOGuid\Machine\Microsoft")) { New-Item "\\$DC\SYSVOL\$Domain\Policies\$GPOGuid\Machine\Microsoft\" -type Directory | out-null }
43 | If (!(Test-Path "\\$DC\SYSVOL\$Domain\Policies\$GPOGuid\Machine\Microsoft\Windows NT")) { New-Item "\\$DC\SYSVOL\$Domain\Policies\$GPOGuid\Machine\Microsoft\Windows NT\" -type Directory | out-null }
44 | If (!(Test-Path "\\$DC\SYSVOL\$Domain\Policies\$GPOGuid\Machine\Microsoft\Windows NT\SecEdit")) { New-Item "\\$DC\SYSVOL\$Domain\Policies\$GPOGuid\Machine\Microsoft\Windows NT\SecEdit" -type Directory | out-null }
45 | $infFile="\\$DC\SYSVOL\$Domain\Policies\$GPOGuid\Machine\Microsoft\Windows NT\SecEdit\GptTmpl.inf"
46 | New-Item $infFile -ItemType File | out-null
47 | Write-Log "Created the GptTmp.inf in the folderstructure above"
48 | }
49 | Catch {
50 | Write-Log "Something didn't work when creating GptTmp.inf in the folderstructure above" -LogType ERROR
51 | }
52 |
53 | # Adding information to the GptTmp.inf file
54 | Try {
55 | $MemberOf = "*$($SecGroupSid)__Memberof = *S-1-5-32-544"
56 | If ( $GPO -like "*LocalUser*" ) {
57 | $MemberOf = "*$($SecGroupSid)__Memberof = *S-1-5-32-555"
58 | }
59 | $Members = "*$($SecGroupSid)__Members ="
60 | $fileContents = "[Unicode]","Unicode=yes","[Version]",'signature="$CHICAGO$"',"Revision=1","[Group Membership]",$MemberOf,$Members
61 | Set-Content $infFile $fileContents
62 | Write-Log "Added content for Restricted groups to GptTmp.inf"
63 | }
64 | Catch {
65 | Write-Log "Couldn't add content for Restricted groups to GptTmp.inf" -LogType ERROR
66 | }
67 |
68 | # Increasing the version in GPT.INI
69 | Try {
70 | $GPTINI= "\\$DC\SYSVOL\$Domain\Policies\$GPOGuid\GPT.INI"
71 | $GPTINIContent = Get-Content $GPTINI
72 | ForEach ( $GPTINIRow in $GPTINIContent ) {
73 | If ( $GPTINIRow -like "Version=*" ) {
74 | $TempNumber = $GPTINIRow.Substring(8,1)
75 | [int]$VersionNumber = $TempNumber
76 | Write-Log "The current version in GPT.INI is $VersionNumber"
77 | $VersionNumber++
78 | Break
79 | }
80 | }
81 | $Version = "Version=$VersionNumber"
82 | $DisplayName = "displayName=$GPO"
83 | $fileContents="[General]",$Version,$DisplayName
84 | Set-Content $GPTINI $fileContents
85 | Write-Log "Increased the version in GPT.INI to $VersionNumber"
86 | }
87 | Catch {
88 | Write-Log "Failed to Increase the version in GPT.INI to $VersionNumber" -LogType ERROR
89 | }
90 |
91 | # Sets the gPCMachineExtensionNames to include Restricted groups
92 | Try {
93 | Set-ADObject -Server $DC "CN=$GPOGuid,CN=Policies,CN=System,$DomainDN" -Replace @{gPCMachineExtensionNames="[{827D319E-6EAC-11D2-A4EA-00C04F79F83A}{803E14A0-B4FB-11D0-A0D0-00A0C90F574B}]"}
94 | Write-Log "Replaced the attribute gPCMachineExtensionNames for the policy CN=$GPOGuid,CN=Policies,CN=System,$DomainDN"
95 | }
96 | Catch {
97 | Write-Log "Couldn't replace the attribute gPCMachineExtensionNames" -LogType ERROR
98 | }
99 |
100 | # Sets versionNumber to same as GPT.INI
101 | Try {
102 | Set-ADObject -Server $DC "CN=$GPOGuid,CN=Policies,CN=System,$DomainDN" -Replace @{versionNumber=$VersionNumber}
103 | Write-Log "Replaced the attribute versionNumber for the policy CN=$GPOGuid,CN=Policies,CN=System,$DomainDN to match GPT.INI"
104 | }
105 | Catch {
106 | Write-Log "Couldn't replace the attribute versionNumber" -LogType ERROR
107 | }
108 |
109 | # Linking GPO to OU
110 | If ( $GPO -like "*LocalUser*" ) {
111 | $OUName = $GPO -Replace "Task-Server-LocalUser-",""
112 | }
113 | If ( $GPO -like "*LocalAdmin*" ) {
114 | $OUName = $GPO -Replace "Task-Server-LocalAdmin-",""
115 | }
116 | $OU = $(Get-ADOrganizationalUnit -Server $DC -LDAPFilter "(name=$OUName)" -SearchBase "OU=Servers,OU=Domain Computers,$DOmainDN" -SearchScope Subtree).DistinguishedName
117 | If ( $GPO -like "Task-Server-LocalAdmin-All" ) {
118 | $OU = "OU=Servers,OU=Domain Computers,$DOmainDN"
119 | }
120 | Try {
121 | New-GPLink -Server $DC -Name $GPO -Target $OU | out-null
122 | Write-Log "Linked $GPO to $OU"
123 | }
124 | Catch {
125 | Write-Log "Couldn't link $GPO to $OU" -LogType ERROR
126 | }
127 |
128 | Write-Log
129 | }
130 |
131 | Write-Log "--- End of log ---"
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/Create-OUAdminTasks/Create-OUAdminTasks.ps1:
--------------------------------------------------------------------------------
1 | Import-module 'C:\temp\SharedCode.psm1'
2 | $LogFile = "C:\temp\Create-OUAdminTasks\Create-OUAdminTasks.log"
3 |
4 | Function CreateGroup ($GroupName,$Description) {
5 | Try {
6 | New-ADGroup -Path "OU=T0-Tasks,OU=Tier 0,OU=Admin,$DomainDN" -Name $GroupName -GroupScope DomainLocal -GroupCategory Security -Description $Description
7 | Write-Log "Created $GroupName in OU=T0-Tasks,OU=Tier 0,OU=Admin,$DomainDN"
8 | }
9 | Catch {
10 | Write-Log "Couldn't create $GroupName in OU=T0-Tasks,OU=Tier 0,OU=Admin,$DomainDN" -LogType ERROR
11 | }
12 | }
13 |
14 | $OUs = $(Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase "OU=Servers,$DOmainDN" -SearchScope Subtree).Name
15 | $Description = "Local Server Administrator"
16 | ForEach ( $OU in $OUs ) {
17 | $GroupName = "Task-Server-LocalAdmin-$OU"
18 | If ( $OU -ne "Servers" ) {
19 | CreateGroup -GroupName $GroupName -Description $Description
20 | }
21 | }
22 |
23 | $Description = "Local Server User"
24 | CreateGroup -GroupName "Task-Server-LocalUser-Adminservers" -Description $Description
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/DelegatedTasks_Domain1_1.0.csv:
--------------------------------------------------------------------------------
1 | "TaskID,""Task"",""GroupName"",""SACL"",""Target"",""ShortName"",""Type"",""Role-T0-Infrastructure"",""Role-T1-Administration"",""Role-T1-Application"",""Role-T1-Citrix"",""Role-T1-COM"",""Role-T1-DBA"",""Role-T1-DigitalMeeting"",""Role-T1-IAM"",""Role-T1-Infrastructure"",""Role-T1-Messaging"",""Role-T1-Monitoring"",""Role-T1-Office"",""Role-T1-Operations"",""Role-T1-PC"",""Role-T1-Print"",""Role-T1-ServiceDesk"",""Role-T1-SharePoint"",""Role-T1-Storage"",""Role-T1-VIP"",""Role-T2-Application"",""Role-T2-DigitalMeeting"",""Role-T2-Infrastructure"",""Role-T2-Messaging"",""Role-T2-Operations"",""Role-T2-Print"",""Role-T2-ServiceDesk"""
2 | "AD7016,""Manage Organizational Unit (Full Control)"",""Task-OU-FullControl"",""False"",""OU=Admin,dc=domain1,dc=local"",""Admin"",""ACE"",""X"","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""""
3 | "AD7016,""Manage Organizational Unit (Full Control)"",""Task-OU-FullControl-ApplicationGroups"","""",""OU=ApplicationGroups,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""""
4 | "AD0015,""Add/Remove Members to Group"",""Task-Group-Modify_Members-ApplicationGroups"","""",""OU=ApplicationGroups,dc=domain1,dc=local"","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""""
5 | "AD0032,""Disable/Enable a Computer Account"",""Task-Computer-Modify_Enabled_Disabled-Clients"","""",""OU=Clients,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""""
6 | "AD7054,""Read Bitlocker Recovery Key"",""Task-Computer-Read_BitlockerRecovery-Clients"","""",""OU=Clients,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""","""","""","""","""",""x"","""","""",""x"","""","""","""","""","""","""","""","""","""","""""
7 | "AD0011,""Reset User Account Password"",""Task-User-Reset_Passwords-Lockdown User"","""",""OU=Lockdown User,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""""
8 | "AD7016,""Manage Organizational Unit (Full Control)"",""Task-OU-FullControl-Lockdown User"","""",""OU=Lockdown User,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""""
9 | "AD0012,""Unlock User Accounts"",""Task-User-Unlock-Lockdown User"","""",""OU=Lockdown User,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""""
10 | "AD7016,""Manage Organizational Unit (Full Control)"",""Task-OU-FullControl-MaintenanceGroups"","""",""OU=MaintenanceGroups,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""""
11 | "AD0027,""Delete Computer Accounts"",""Task-Computer-Delete-NewComputers"","""",""OU=NewComputers,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""""
12 | "AD0030,""Move a Computer Account From OU"",""Task-Computer-Move_FromOu-NewComputers"","""",""OU=NewComputers,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""""
13 | "AD0025,""Create Computer Accounts"",""Task-Computer-Create-NewComputers"","""",""OU=NewComputers,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""""
14 | "AD7016,""Manage Organizational Unit (Full Control)"",""Task-OU-FullControl-Servers"","""",""OU=Servers,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""""
15 | "AD7016,""Manage Organizational Unit (Full Control)"",""Task-OU-FullControl"",""False"",""OU=Servers,dc=domain1,dc=local"",""Servers"",""ACE"","""","""","""","""","""","""","""","""","""","""","""","""",""X"","""","""","""","""","""","""","""","""","""","""","""","""","""""
16 | "AD0166,""Deleting an Organizational Unit"",""Task-OU-Delete"",""False"",""OU=Servers,dc=domain1,dc=local"",""Servers"",""ACE"","""","""","""","""","""","""","""","""","""","""","""","""",""X"","""","""","""","""","""","""","""","""","""","""","""","""","""""
17 | "AD0027,""Delete Computer Accounts"",""Task-Computer-Delete-Servers"","""",""OU=Servers,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""""
18 | "AD0165,""Creating an Organizational Unit"",""Task-OU-Create-Servers"","""",""OU=Servers,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""""
19 | "AD0025,""Create Computer Accounts"",""Task-Computer-Create"",""False"",""OU=Servers,dc=domain1,dc=local"",""Servers"",""ACE"","""","""","""","""","""","""","""","""","""","""","""","""",""X"","""","""","""","""","""","""","""","""","""","""","""","""","""""
20 | "AD7021,""Manage User Account (Full Control)"",""Task-User-Manage-ServiceAccounts"","""",""OU=ServiceAccounts,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""""
21 | "AD0012,""Unlock User Accounts"",""Task-User-Unlock"",""False"",""OU=T1-Accounts,OU=Tier 1,OU=Admin,dc=domain1,dc=local"",""T1-Accounts"",""ACE"","""","""","""","""","""","""","""","""","""","""","""","""",""X"","""","""","""","""","""","""","""","""","""","""","""","""","""""
22 | "AD0011,""Reset User Account Password"",""Task-User-Reset_Passwords"",""False"",""OU=T1-Accounts,OU=Tier 1,OU=Admin,dc=domain1,dc=local"",""T1-Accounts"",""ACE"","""","""","""","""","""","""","""","""","""","""","""","""",""X"","""","""","""","""","""","""","""","""","""","""","""","""","""""
23 | "AD0012,""Unlock User Accounts"",""Task-User-Unlock"",""False"",""OU=T2-Accounts,OU=Tier 2,OU=Admin,dc=domain1,dc=local"",""T2-Accounts"",""ACE"","""","""","""","""","""","""","""","""","""","""","""","""",""X"","""","""","""","""","""","""","""","""","""","""","""","""","""""
24 | "AD0011,""Reset User Account Password"",""Task-User-Reset_Passwords"",""False"",""OU=T2-Accounts,OU=Tier 2,OU=Admin,dc=domain1,dc=local"",""T2-Accounts"",""ACE"","""","""","""","""","""","""","""","""","""","""","""","""",""X"","""","""","""","""","""","""","""","""","""","""","""","""","""""
25 | "AD7016,""Manage Organizational Unit (Full Control)"",""Task-OU-FullControl-ToBeDeleted"","""",""OU=ToBeDeleted,dc=domain1,dc=local"","""","""","""","""","""","""","""","""","""","""",""x"","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""","""""
26 |
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/Get-GPTINI/Get-GPTINI.ps1:
--------------------------------------------------------------------------------
1 | $DC = Get-ADDomainController -Discover -Domain $Domain
2 | $global:Domain = $( Get-ADDomain ).DNSRoot # domain.domain.com
3 | $QueryGPOs = "Task-Server-Local*"
4 | $GPOs = get-gpo -all | where { $_.DisplayName -like $QueryGPOs }
5 | ForEach ( $GPO in $GPOs ) {
6 | $GPTINI= "\\$DC\SYSVOL\$Domain\Policies\{$($GPO.ID)}\GPT.INI"
7 | $GPTINIContent = Get-Content $GPTINI
8 | If ( $GPTINIContent -like "*New*" ) {
9 | "$($GPO.Displayname) - " | out-file C:\temp\LocalRightsGPOs.log -Append
10 | $GPTINI | out-file C:\temp\LocalRightsGPOs.log -Append
11 | }
12 | }
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/POPADD/EPPlus.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/AD-Delegation/Create Least Privilegies Model/POPADD/EPPlus.dll
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/POPADD/POPADD.psd1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/AD-Delegation/Create Least Privilegies Model/POPADD/POPADD.psd1
--------------------------------------------------------------------------------
/AD-Delegation/Create Least Privilegies Model/SharedCode.psm1:
--------------------------------------------------------------------------------
1 | Function Write-Log {
2 | [CmdletBinding()]
3 | param (
4 | [Parameter(Position=0)]
5 | [string]$Message,
6 | [Parameter(Position=1)]
7 | [ValidateSet('INFO','WARN','ERROR')][string]$LogType = 'INFO'
8 | )
9 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
10 | if($Message -eq $null){ $Message = "" }
11 | $LogEntry = "$LogType $CurrentDateTime - $Message"
12 | Add-Content -Value $LogEntry -Path $LogFile -Encoding UTF8
13 | Write-Verbose $LogEntry
14 | }
15 |
16 | $global:Domain = $( Get-ADDomain ).DNSRoot # domain.domain.com
17 | $global:DomainName = $( Get-ADDomain ).Name # domain
18 | $global:DomainDN = $( Get-ADDomain ).DistinguishedName # DC=domain,DC=domain,DC=com
--------------------------------------------------------------------------------
/AD-Delegation/Get-PrivilegedRolesManagers.ps1:
--------------------------------------------------------------------------------
1 | $LookupDomains = @("domain1","domain2")
2 | $global:Roles = @()
3 | $global:ObsoleteManagers = @()
4 | $global:TempObsoleteManagers = @()
5 | $SMTPServer = "" # <- Put SMTP server here
6 |
7 | # Get information about Roles
8 | Function GetRoles {
9 | ForEach ( $LookupDomain in $LookupDomains ) {
10 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).DistinguishedName
11 | $global:Roles += Get-ADGroup -Filter 'Name -like "Role-T*"' -Properties Name, Description, Info -SearchScope Subtree -SearchBase "OU=Admin,$DomainDN" -Server $LookupDomain | Select Name, @{Name='Manager'; Expression = {"$($_.'Info'.Substring(9,5))"}}, Description | Add-Member -NotePropertyName Domain -NotePropertyValue $LookupDomain -Passthru #-Force
12 | }
13 | }
14 |
15 | # Check if Managers exist in Production as standard users
16 | Function CheckForManagersInProd {
17 | $Managers = $global:Roles.Manager | select -Unique | sort
18 | ForEach ( $Manager in $Managers ) {
19 | $Filter = 'samAccountName -eq "' + $Manager + '" -and Enabled -eq "True"'
20 | $UserExist = Get-ADUser -filter $Filter -Properties samAccountName -SearchBase "OU=x500Users,DC=wp,DC=ams,DC=se" -SearchScope OneLevel
21 | If ( $UserExist.Count -eq 0 ) {
22 | $global:TempObsoleteManagers += $Manager
23 | }
24 | }
25 | ForEach ( $Manager in $global:TempObsoleteManagers ) {
26 | $global:ObsoleteManagers += $global:Roles | Where Manager -eq $Manager
27 | }
28 | }
29 |
30 | GetRoles
31 | CheckForManagersInProd
32 |
33 | #Lists Roles missing Manager
34 | $RolesMissingManager = $global:Roles | Where Manager -eq $Null
35 |
36 | #Lists Roles with obsolete Managers that doesn't exist in Production
37 | $RolesWithObsoleteManagers = $global:ObsoleteManagers | select Name, Manager, Domain, Description
38 |
39 | #Lists all Roles to get different Managers for same Role
40 | #$global:Roles | select Name, Manager, Domain, Description | sort Name
41 |
42 | If ( $RolesWithObsoleteManagers -ne $Null -or $RolesMissingManager -ne $Null ) {
43 | $MailBody ="Hi!
44 |
45 | This is a list of roles that are missing or not existing managers connected to them.
46 |
47 | "
48 | If ( $RolesWithObsoleteManagers -ne $Null ) {
49 | $MailBody += "Those roles has Managers that no longer exists:`n`n"
50 | ForEach ( $Role in $RolesWithObsoleteManagers ) {
51 | $MailBody += "$($Role.Name)`t$($Role.Manager)`t$($Role.Domain)`n"
52 | }
53 | }
54 | If ( $RolesMissingManager -ne $Null ) {
55 | If ( $RolesWithObsoleteManagers -ne $Null ) {
56 | $MailBody += "`n"
57 | }
58 | $MailBody += "Those roles are missing a manager:`n`n"
59 | ForEach ( $Role in $RolesMissingManager ) {
60 | $MailBody += "$($Role.Name)`t$($Role.Domain)`n"
61 | }
62 | }
63 | $MailBody += "`nBest regards"
64 | }
65 |
66 | $Recipients = @("mail@mail.com")
67 | Send-MailMessage -Encoding utf8 -Body $MailBody -From noreply@domain.local -To $Recipients -Subject "AD-Delegation Roles needs attention!" -SmtpServer $SMTPServer
--------------------------------------------------------------------------------
/AD-Delegation/Get-RolesWithZeroActiveMembers.ps1:
--------------------------------------------------------------------------------
1 | Clear-Host
2 | $LookupDomains = @("domain1","domain2")
3 | $ActiveMembers = @()
4 | $RolesInfo = @()
5 |
6 | ForEach ($LookupDomain in $LookupDomains ) {
7 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).DistinguishedName
8 | $Roles = Get-ADGroup -Filter 'Name -like "Role-T*"' -SearchBase "OU=Admin,$DomainDN" -Server $LookupDomain
9 | ForEach ( $Role in $Roles ) {
10 | $ActiveMembers = @(Get-ADGroup $Role -Server $LookupDomain | Get-ADGroupMember -Server $LookupDomain | Get-ADUser -Properties samAccountName, Enabled -Server $LookupDomain | Where Enabled -eq $True).Count
11 | If ( $ActiveMembers[0] -eq 0 ) {
12 | $TempObject = New-Object System.Object
13 | $TempObject | Add-Member -MemberType NoteProperty -Name "Role" -Value $Role.Name -Force
14 | $TempObject | Add-Member -MemberType NoteProperty -Name "Domain" -Value $LookupDomain -Force
15 | $RolesInfo += $TempObject
16 | }
17 | }
18 | }
19 |
20 | $RolesInfo
21 |
22 | Function GetUsersWihtoutRoles {
23 | $LookupDomains = @("domain1","domain2")
24 |
25 | ForEach ($LookupDomain in $LookupDomains ) {
26 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).DistinguishedName
27 | $Users = Get-ADUser -Filter 'Enabled -eq "True"' -SearchBase "OU=Admin,$DomainDN" -SearchScope Subtree -Properties samAccountName, memberof -Server $LookupDomain
28 | ForEach ( $User in $Users ) {
29 | If ( $($User.MemberOf).Count -eq 0 ) {
30 | write-host "$LookupDomain\$($User.samAccountName)"
31 | }
32 | }
33 | }
34 | }
35 | GetUsersWihtoutRoles
--------------------------------------------------------------------------------
/AD-Delegation/Get-SensitiveGroupMembers.ps1:
--------------------------------------------------------------------------------
1 | Clear-Host
2 |
3 | Function GetRowColor {
4 | $global:RowBGColor = $OddRowBGColor
5 | If ( $global:OddRow -eq $False ) {
6 | $global:OddRow = $True
7 | $global:RowBGColor = "#ffffff"
8 | }
9 | Else { $global:OddRow = $False }
10 | }
11 |
12 | $LookupDomains = @("domain1","domain2")
13 | $SensitiveGroups = @("Domain Admins","Enterprise Admins","Schema Admins","Role-T0-Infrastructure")
14 |
15 | $Users = @()
16 | $HTML = @"
17 |
18 |
19 |
20 | Sensitive groups in all AD-domains
21 |
22 | "@
23 |
24 | ForEach ( $LookupDomain in $LookupDomains ) {
25 |
26 | If ( $LookupDomain -eq "domain1" ) { $DomainBGColor = "#c2d4ff" ; $TypeBGColor = "#dbe6ff" ; $OddRowBGColor = "#f5f8ff" }
27 | If ( $LookupDomain -eq "domain2" ) { $DomainBGColor = "#cbffc2" ; $TypeBGColor = "#dcffd6" ; $OddRowBGColor = "#f6fff5" }
28 |
29 | $HTML += "`n"
30 | $HTML += "`nDomain: $($LookupDomain.ToUpper()) |
"
31 | $HTML += "`nUser | Group | Enabled |
"
32 | ForEach ( $SensitiveGroup in $SensitiveGroups ) {
33 | $Users = Get-ADGroupMember $SensitiveGroup -Server $LookupDomain | Sort samAccountName | Add-Member @{ADGroup="$SensitiveGroup"} -PassThru -Force
34 | ForEach ( $User in $Users ) {
35 | If ( $SensitiveGroups -notcontains $User.name ) {
36 | $Enabled = $(Get-ADUser $User.distinguishedName -Properties Enabled -Server $LookupDomain -ErrorAction SilentlyContinue).Enabled
37 | $EnabledColor = "Green"
38 | If ( $Enabled -ne "True" ) { $Enabled = "False" ; $EnabledColor = "Red" }
39 | GetRowColor
40 | $HTML += "`n$($User.samAccountName) | $($User.ADGroup) | $($Enabled) |
"
41 | }
42 | }
43 | }
44 | $HTML += "`n
"
45 | $HTML += "`n
"
46 | }
47 | $HTML += "`n"
48 | $HTML | Out-File "C:\Temp\SensitiveGroupMembers.html"
--------------------------------------------------------------------------------
/AD-Delegation/Get-Tier2UsersWithoutRole.ps1:
--------------------------------------------------------------------------------
1 | $DomainDN = $(Get-ADDomain).DistinguishedName
2 | $Tier2Users = $(Get-ADUser -filter * -SearchBase "OU=T2-Accounts,OU=Tier 2,OU=Admin,$DomainDN" -SearchScope OneLevel).Name
3 |
4 | ForEach ( $User in $L2Users ) {
5 | $ConnectedToRule = $False
6 | $memberOf = $(Get-ADPrincipalGroupMembership $User).Name
7 | ForEach ( $Member in $MemberOf ) {
8 | If ( $Member -like "Role-*" ) {
9 | $ConnectedToRule = $True
10 | Continue
11 | }
12 | }
13 | If ( $ConnectedToRule -eq $False ) {
14 | Write-host "$User"
15 | }
16 | }
--------------------------------------------------------------------------------
/AD-Delegation/Get-UsersPWExpiryDate.ps1:
--------------------------------------------------------------------------------
1 | Clear-Host
2 | $LookupDomains = @("domain1","domain2")
3 |
4 | ForEach ( $LookupDomain in $LookupDomains ) {
5 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).DistinguishedName
6 |
7 | # Check for privileged users password expiration time
8 | #Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} -SearchBase "OU=Admin,$DomainDN" –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" -Server $LookupDomain | Select-Object -Property samAccountName,@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} | Sort ExpiryDate -Descending
9 |
10 | # Check for privileged users with Password Never Expires set, should not be many at all!
11 | $Users = Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $True} -SearchBase "OU=Admin,$DomainDN" –Properties "DisplayName" -Server $LookupDomain | Select-Object -Property samAccountName
12 | $ExcludedUsers = @("user1","user2","user3")
13 | ForEach ( $User in $Users ) {
14 | If ( $ExcludedUsers -notcontains $User.samAccountName ) {
15 | Write-host "$LookupDomain\$($User.samAccountName)"
16 | Set-ADUser -Identity $User.samAccountName -PasswordNeverExpires:$FALSE -Server $LookupDomain
17 | }
18 | }
19 | }
20 |
21 | Disable-ADAccount user3 -Server $LookupDomain
--------------------------------------------------------------------------------
/AD-Delegation/Manage-PrivilegedUser.ps1:
--------------------------------------------------------------------------------
1 | Function VerifyComplexPassword ($Password) # Verify that atleast three out of four conditions for a complex password is reached
2 | {
3 | $Password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
4 | If ($Password –cmatch "[^a-zA-Z0-9]") { $PWContainSpecial = $True } Else { $PWContainSpecial = $False } # Checks if any (special) characters exists in the string, that is other (^) characters than a-z, A-Z or 0-9
5 | If ($Password –cmatch "[a-z]") { $PWContainLower = $True } Else { $PWContainLower = $False } # Checks that the password contains atleast one lowercase alpabethical letter
6 | If ($Password –cmatch "[A-Z]") { $PWContainUpper = $True } Else { $PWContainUpper = $False } # Checks that the password contains atleast one uppercase alpabethical letter
7 | If ($Password –cmatch "[0-9]") { $PWContainDigit = $True } Else { $PWContainDigit = $False } # Checks that the password contains atleast one digit
8 | If ( $PWContainSpecial + $PWContainLower + $PWContainUpper + $PWContainDigit -ge 3 ) { # Verifies how many of the above conditions was reached and it returns $True if its greater or equal to three
9 | Return $True
10 | }
11 | Else {
12 | Return $False # Returns $False if atleast three out of four conditions wasn't reached
13 | }
14 | }
15 |
16 | Function VerifyMatchingPassword ($Password, $Password2) # Verify that the two passwords entered match
17 | {
18 | $Password_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
19 | $Password2_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password2))
20 | If ( $Password_text -ceq $Password2_text ) {
21 | Return $True
22 | }
23 | Else {
24 | Return $False
25 | }
26 | }
27 |
28 | $LookupDomains = @("domain1","domain2")
29 | $UserPrefix = "T"
30 | $UserSuffix = "adm"
31 | $FoundUsers = @()
32 |
33 | Do {
34 | Clear-Host
35 | Write-Host "Manage Privileged Users"
36 | Write-Host "-----------------------"
37 | Write-Host ""
38 | Write-Host "Use this script to set password, enable or unlock`nprivileged account(s) for a specific user."
39 | Write-Host "Enter the standard username (5 letters, ex: berfe)`nto find its related privileged account(s)."
40 | Write-Host ""
41 | Write-Host "When the window with the different accounts shows up,`npress Ctrl to select specific rows while clicking or Shift`nto select multiple in a row, or just select a single one..."
42 | Write-Host ""
43 | $Username = Read-host "Username"
44 | }
45 | While ($Username -notmatch "^[a-zA-Z]{5}$")
46 |
47 | Write-Host ""
48 | Write-Host "- Searching for privileged account(s) related to $Username"
49 |
50 | ForEach ( $LookupDOmain in $LookupDomains ) {
51 | Write-host "- Querying domain: $LookupDomain"
52 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).DistinguishedName
53 | If ( $env:UserName.ToUpper() -notlike "L0*" ) {
54 | $FoundUsers += Get-ADUser -Filter "samAccountName -like '$("$UserPrefix`1$Username$UserSuffix")' -or samAccountName -like '$("$UserPrefix`2$Username$UserSuffix")'" -SearchBase "OU=Admin,$DomainDN" -SearchScope Subtree -Properties samAccountName,LockedOut,Enabled -Server $LookupDomain | Select samAccountName,LockedOut,Enabled | Add-Member @{Domain="$LookupDomain"} -PassThru
55 | }
56 | Else {
57 | $FoundUsers += Get-ADUser -Filter "samAccountName -like '$("$UserPrefix*$Username$UserSuffix")'" -SearchBase "OU=Admin,$DomainDN" -SearchScope Subtree -Properties samAccountName,LockedOut,Enabled -Server $LookupDomain | Select samAccountName,LockedOut,Enabled | Add-Member @{Domain="$LookupDomain"} -PassThru
58 | }
59 |
60 | }
61 |
62 | Write-Host "- Found $($FoundUsers.Count) account(s)"
63 |
64 | [array]$SelectedUsers = $FoundUsers | Select samAccountName, Domain, LockedOut, Enabled | Sort Domain, samAccountName | Out-GridView -OutputMode Multiple
65 | Write-Host "- You have selected $($SelectedUsers.Count) account(s)"
66 | $SelectedUsers = $SelectedUsers | Sort samAccountName
67 |
68 | If ( $SelectedUsers.LockedOut -contains $True ) {
69 | $Question = [System.Windows.MessageBox]::Show("Some of the users you have selected are locked, you are about to Unlock them.`n`nAre you sure?",' Unlock users','YesNo')
70 | If ( $Question -eq "Yes" ) {
71 | Write-Host ""
72 | Write-host "Unlocking the selected accounts"
73 | ForEach ( $SelectedUser in $( $SelectedUsers | Where LockedOut -eq $True )) {
74 | Try {
75 | Unlock-ADAccount $SelectedUser.samAccountName -Server $SelectedUser.Domain
76 | Write-host "- " -NoNewLine ; Write-Host "Successfully" -ForegroundColor Green -NoNewline ; Write-host " unlocked: $($SelectedUser.Domain)\$($SelectedUser.samAccountName)"
77 | }
78 | Catch {
79 | Write-host "- " -NoNewline ; Write-Host "Failed" -ForegroundColor Red -NoNewline ; Write-host " to unlock: $($SelectedUser.Domain)\$($SelectedUser.samAccountName)"
80 | }
81 | }
82 | }
83 | }
84 |
85 | If ( $SelectedUsers.Enabled -contains $False ) {
86 | $Question = [System.Windows.MessageBox]::Show("Some of the users you have selected are disabled, you are about to Enable them.`n`nAre you sure?",' Enable users','YesNo')
87 | If ( $Question -eq "Yes" ) {
88 | Write-Host ""
89 | Write-host "Enabling the selected accounts"
90 | ForEach ( $SelectedUser in $( $SelectedUsers | Where Enabled -eq $False )) {
91 | Try {
92 | Enable-ADAccount $SelectedUser.samAccountName -Server $SelectedUser.Domain
93 | Write-host "- " -NoNewLine ; Write-Host "Successfully" -ForegroundColor Green -NoNewline ; Write-host " enabled: $($SelectedUser.Domain)\$($SelectedUser.samAccountName)"
94 | }
95 | Catch {
96 | Write-host "- " -NoNewline ; Write-Host "Failed" -ForegroundColor Red -NoNewline ; Write-host " to enable: $($SelectedUser.Domain)\$($SelectedUser.samAccountName)"
97 | }
98 | }
99 | }
100 | }
101 |
102 | If ( $SelectedUsers.Count -gt 0 ) {
103 | $Question = [System.Windows.MessageBox]::Show("Do you want to set a new password for all the selected users?",' Set new password for users','YesNo')
104 | If ( $Question -eq "Yes" ) {
105 | Write-host ""
106 | Write-Host "Provide New Password.`n`nRemember that you have to use at least 3 out of 4 of the requirements below:`n`n- Minimum length of 8 characters (14 for Tier 0-accounts)`n- 1 lower case character (a-z)`n- 1 upper case character (A-Z)`n- 1 numeric or special character (0-9, !#¤%_ etc.)"
107 | $Userlevels = @()
108 | ForEach ( $SelectedUser in $SelectedUsers ) {
109 | If ( $UserLevels -notcontains $($SelectedUser.samAccountName.Substring(1,1)) ) { $UserLevels += $SelectedUser.samAccountName.Substring(1,1) }
110 | }
111 | ForEach ( $UserLevel in $UserLevels ) {
112 | Do {
113 | Write-Host ""
114 | Write-Host "Enter the new password for the selected $UserPrefix$UserLevel-accounts"
115 | $NewPassword = Read-Host -Prompt "Password" -AsSecureString
116 | $NewPassword2 = Read-Host -Prompt "Re-enter passowrd" -AsSecureString
117 | $PWComplexTest = VerifyComplexPassword -Password $NewPassword
118 | If ( $PWComplexTest -eq $False ) { Write-Host "The password is not complex, try again!" }
119 | $PWMatchTest = VerifyMatchingPassword $NewPassword $NewPassword2
120 | If ( $PWMatchTest -eq $False ) { Write-Host "The passwords entered does not match, try again!" }
121 | }
122 | Until ( $PWComplexTest -eq $True -and $PWMatchTest -eq $True )
123 | If ( $UserLevel -eq 0 ) { $NewPasswordT0 = $NewPassword ; $NewPassword2T0 = $NewPassword2 }
124 | If ( $UserLevel -eq 1 ) { $NewPasswordT1 = $NewPassword ; $NewPassword2T1 = $NewPassword2 }
125 | If ( $UserLevel -eq 2 ) { $NewPasswordT2 = $NewPassword ; $NewPassword2T2 = $NewPassword2 }
126 | }
127 |
128 | Write-host ""
129 | Write-host "Sets the new password for the selected accounts"
130 | $SelectedUsers = $SelectedUsers | Sort Domain, samAccountName
131 | ForEach ( $SelectedUser in $SelectedUsers ) {
132 | Try {
133 | If ( $SelectedUser.samAccountName.Substring(1,1) -eq 0 ) { $NewPassword = $NewPasswordT0 }
134 | If ( $SelectedUser.samAccountName.Substring(1,1) -eq 1 ) { $NewPassword = $NewPasswordT1 }
135 | If ( $SelectedUser.samAccountName.Substring(1,1) -eq 2 ) { $NewPassword = $NewPasswordT2 }
136 | Set-ADAccountPassword $SelectedUser.samAccountName -NewPassword $NewPassword -Reset -Server $SelectedUser.Domain
137 | Write-host "- " -NoNewLine ; Write-Host "Successfully" -ForegroundColor Green -NoNewline ; Write-host " set password for: $($SelectedUser.Domain)\$($SelectedUser.samAccountName)"
138 | }
139 | Catch {
140 | Write-host "- " -NoNewline ; Write-Host "Failed" -ForegroundColor Red -NoNewline ; Write-host " to set password for: $($SelectedUser.Domain)\$($SelectedUser.samAccountName)"
141 | }
142 | }
143 | }
144 | }
145 |
146 | If ( $(Test-Path variable:global:psISE) -eq $False ) { # This hides the Powershellwindow in the background if ISE isn't running
147 | Write-host ""
148 | Read-host "Press Enter to exit..."
149 | }
--------------------------------------------------------------------------------
/AD-Delegation/Set-RolesDescription.ps1:
--------------------------------------------------------------------------------
1 | $LookupDomains = @("domain1","domain2")
2 |
3 | $AllRoles = @()
4 | ForEach ( $LookupDomain in $LookupDomains ) {
5 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).Distinguishedname
6 | $Roles = Get-ADGroup -filter 'Name -like "Role-T*"' -SearchBase "OU=Admin,$DomainDN" -SearchScope Subtree -Server $LookupDomain -Properties Name, Description | Select Name, Description
7 | ForEach ( $Role in $Roles ) {
8 | If ( $AllRoles.Name -notcontains $Role.Name ) { $AllRoles += $Role }
9 | }
10 | }
11 | $AllRoles = $AllRoles | Sort Name
12 | $AllRoles | where { $_.Description -eq $Null }
13 |
14 | ForEach ( $LookupDomain in $LookupDomains ) {
15 | If ( $LookupDomain -ne "domain3" ) {
16 | ForEach ( $Role in $AllRoles ) {
17 | Try{
18 | $GroupDescription = "Users in this group manages System servers as administrators"
19 | Try {
20 | Set-ADGroup $Role.Name -Description $GroupDescription -Server $LookupDomain
21 | Write-host "Sets description of group: $($Role.Name) in domain: $LookupDOmain"
22 | }
23 | Catch {}
24 | }
25 | Catch {}
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/AD-Delegation/Set-RolesInfo.ps1:
--------------------------------------------------------------------------------
1 | $LookupDomains = @("domain1","domain2")
2 |
3 | $AllRoles = @()
4 | ForEach ( $LookupDomain in $LookupDomains ) {
5 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).Distinguishedname
6 | $Roles = Get-ADGroup -filter 'Name -like "Role-T*"' -SearchBase "OU=Admin,$DomainDN" -SearchScope Subtree -Server $LookupDomain -Properties Name, Info | Select Name, Info
7 | ForEach ( $Role in $Roles ) {
8 | If ( $AllRoles.Name -notcontains $Role.Name ) { $AllRoles += $Role }
9 | }
10 | }
11 | $AllRoles = $AllRoles | Sort Name
12 |
13 | ForEach ( $LookupDomain in $LookupDomains ) {
14 | If ( $LookupDomain -ne "domain3" ) {
15 | ForEach ( $Role in $AllRoles ) {
16 | Try{
17 | Try {
18 | Set-ADGroup $Role.Name -replace @{info="Manager: $Manager"} -Server $LookupDomain
19 | Write-host "Sets Info for group: $($Role.Name) in domain: $LookupDOmain"
20 | }
21 | Catch {}
22 | }
23 | Catch {}
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/AD-Delegation/Set-SetResetPWRightOnPrivilegedAccounts.ps1:
--------------------------------------------------------------------------------
1 | $DomainDN = $(Get-ADDomain).DistinguishedName
2 | ForEach ( $Tier2User in $(Get-ADUser -filter * -SearchBase "OU=T1-Accounts,OU=Tier 1,OU=Admin,$DomainDN" | Sort samAccountName ) ) {
3 | $Tier1UserPath = "AD:\CN=$($Tier2User.Name),OU=T1-Accounts,OU=Tier 1,OU=Admin,$DomainDN"
4 | $Tier2UserSID = $(Get-ADUser $($Tier2User.Name)).SID
5 | $ACL = Get-ACL -Path $Tier1UserPath
6 | If ( $($ACL.Access | Where { $_.IdentityReference -like "*$($Tier2User.Name)*" -and $_.ActiveDirectoryRights -eq "ExtendedRight" }).Count -eq 0 ) {
7 | $ACL.AddAccessRule((New-Object System.DirectoryServices.ActiveDirectoryAccessRule $Tier2UserSID,"ExtendedRight","Allow",([GUID]("00299570-246d-11d0-a768-00aa006e0529")).guid,"None",([GUID]("bf967aba-0de6-11d0-a285-00aa003049e2")).guid))
8 | Write-host "Added permissions to $($Tier2User.Name)"
9 | Set-ACL -Path $Tier1UserPath -ACLObject $ACL
10 | }
11 | }
12 | ForEach ( $Tier2User in $(Get-ADUser -filter * -SearchBase "OU=T2-Accounts,OU=Tier 2,OU=Admin,$DomainDN" | Sort samAccountName ) ) {
13 | If ( Get-ADUser -LDAPFilter "(name=*$($Tier2User.Name -replace "l2","l1")*)" -SearchBase "OU=Admin,$DomainDN" -SearchScope Subtree ) {
14 | $Tier2UserPath = "AD:\CN=$($Tier2User.Name),OU=T2-Accounts,OU=Tier 2,OU=Admin,$DomainDN"
15 | $Tier2UserSID = $(Get-ADUser $($Tier2User.Name -replace "l2","l1")).SID
16 | $ACL = Get-ACL -Path $Tier2UserPath
17 | If ( $($ACL.Access | Where { $_.IdentityReference -like "*$($Tier2User.Name -replace "l2","l1")*" -and $_.ActiveDirectoryRights -eq "ExtendedRight" }).Count -eq 0 ) {
18 | $ACL.AddAccessRule((New-Object System.DirectoryServices.ActiveDirectoryAccessRule $Tier2UserSID,"ExtendedRight","Allow",([GUID]("00299570-246d-11d0-a768-00aa006e0529")).guid,"None",([GUID]("bf967aba-0de6-11d0-a285-00aa003049e2")).guid))
19 | Write-host "Added permissions to $($Tier2User.Name)"
20 | Set-ACL -Path $Tier2UserPath -ACLObject $ACL
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/AD-Delegation/Verify-ServerOUsHaveLocalAdminTasks.ps1:
--------------------------------------------------------------------------------
1 | clear-host
2 | $LookupDomains = @("domain1","domain2")
3 |
4 | ForEach ( $LookupDomain in $LookupDomains ) {
5 | $DomainDN = $(Get-ADDOmain -Server $LookupDomain).DistinguishedName
6 | $OUs = $(Get-ADOrganizationalUnit -Filter * -SearchBase "OU=Servers,$DomainDN" -SearchScope OneLevel -Server $LookupDomain).Name
7 | $LocalAdminTasks = $(Get-ADGroup -Filter "Name -like 'Task-Server-LocalAdmin-*'" -SearchBase "OU=T0-Tasks,OU=Tier 0,OU=Admin,$DomainDN" -Server $LookupDomain).Name
8 | ForEach ( $OU in $OUs ) {
9 | If ( $LocalAdminTasks -notcontains "Task-Server-LocalAdmin-$OU" ) {write-host "$LookupDOmain - $OU" }
10 | }
11 | }
--------------------------------------------------------------------------------
/ADMXViewer/README.md:
--------------------------------------------------------------------------------
1 | ## Description
2 |
3 | Want to view the settings available in an ADMX file without importing it into the local or central store and open *'Group Policy Management Console'* or *'gpdit.msc'*, then this PSGUI could come in handy.
4 |
5 | Or if you want to know the specific registry values that each setting applies this simplifies the view of that setting....
6 |
7 | ## Configure file association
8 |
9 | Added possibility to open an ADMX file directly by association, use below registry setting to achieve this:
10 |
11 | HKEY_CURRENT_USER\Software\Classes\.admx_auto_file\shell\open\command
12 |
13 | (Default)
14 |
15 | powershell.exe -file "[PATH TO FILE]\ADMXViewer.ps1" "%1"
16 |
17 | (if you open an ADMX file with many settings it might take a while to open, no progress bar at this point showing anything until the window pops up)
18 |
19 | ## Example
20 | 
21 |
--------------------------------------------------------------------------------
/ADMXViewer/admx/CredUI.admx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/ADMXViewer/admx/en-US/msedge.adml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/ADMXViewer/admx/en-US/msedge.adml
--------------------------------------------------------------------------------
/ADMXViewer/admx/msedge.admx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/ADMXViewer/admx/msedge.admx
--------------------------------------------------------------------------------
/ADMXViewer/admx/sv-SE/msedge.adml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/ADMXViewer/admx/sv-SE/msedge.adml
--------------------------------------------------------------------------------
/ADMXViewer/images/ExampleView.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/ADMXViewer/images/ExampleView.jpg
--------------------------------------------------------------------------------
/ADMXViewer/images/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/ADMXViewer/images/icon.png
--------------------------------------------------------------------------------
/Active Directory/ACL/ACLHistory/Modules/ACLHistoryManagement.psm1:
--------------------------------------------------------------------------------
1 | $Global:ACLHistorySQLValues = @{
2 | "ACLSQLServer" = "W008012.froxxen.com"
3 | "ACLDatabase" = "ACLHistory"
4 | }
5 |
6 | function Start-SQLCommand {
7 | <#
8 | .SYNOPSIS
9 | Used to query SQL databases
10 | .DESCRIPTION
11 | Use this function to query SQL databases. The function uses the credentials of the account
12 | that runs the script (Integrated Security).
13 | .PARAMETER SQLServer
14 | The name of the SQL Server
15 | .PARAMETER Database
16 | The name of the database on the SQL Server
17 | .PARAMETER SQLQuery
18 | The Query to run against the database on the SQL Server
19 | .EXAMPLE
20 | Get all Employees from HRSystem
21 |
22 | Start-SQLCommand -SQLServer SQLSERVER1 -Database HRDatabase -SQLQuery 'SELECT Name,EmployeeID FROM HRSystem'
23 | .EXAMPLE
24 | Get all Employees from HRSystem with Titles joined in from HRSystemTitles with a
25 | multiline SQL Query and stores the result in the variable $HRPersonelContent.
26 |
27 | $SQLQueryToExecute = @'
28 | SELECT HR.EmployeeName,Titles.Title
29 | FROM
30 | HRSystemTable AS HR
31 | INNER JOIN HRSystemTitles AS Titles ON Titles.ID = HR.ID
32 | WHERE Titles.Title = 'Manager'
33 | ORDER BY HR.EmployeeName
34 | '@
35 |
36 | $HRPersonelContent = Start-SQLCommand -SQLServer SQLSERVER1 -Database HRDatabase -SQLQuery $SQLQueryToExecute
37 | .NOTES
38 | Script name: Start-SQLCommand
39 | Author: maekee
40 | Github: https://github.com/maekee/Powershell
41 | #>
42 | [CmdletBinding()]
43 | param (
44 | [parameter(Mandatory=$false)][string]$SQLServer = $ACLHistorySQLValues.ACLSQLServer,
45 | [parameter(Mandatory=$false)][string]$Database = $ACLHistorySQLValues.ACLDataBase,
46 | [parameter(Mandatory=$true)][string]$SQLQuery
47 | )
48 |
49 | try{
50 | $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
51 | $SqlConnection.ConnectionString = "Server=$SQLServer;Database=$Database;Integrated Security=True;"
52 | $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
53 | $SqlCmd.CommandText = $SQLQuery
54 | $SqlCmd.Connection = $SqlConnection
55 | $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
56 | $SqlAdapter.SelectCommand = $SqlCmd
57 | $DataSet = New-Object System.Data.DataSet
58 | $nSet = $SqlAdapter.Fill($DataSet)
59 | $OutputTable = $DataSet.Tables[0]
60 | $SqlConnection.Close();
61 | Return $OutputTable
62 | }
63 | catch{ Write-Warning $_.Exception.Message }
64 | }
65 |
66 | function Get-ACLHistoryLogs {
67 | [CmdletBinding()]
68 | param (
69 | [datetime]$EndDate = (Get-Date).AddDays(-1),
70 | [datetime]$StartDate = $(Get-Date)
71 | )
72 | $returnData = Start-SQLCommand -SQLQuery "EXEC dbo.GetACLRecordsWithinDates @EndDate='$($EndDate)', @StartDate='$($StartDate)'"
73 | $returnData
74 | }
75 |
76 | function Add-ACLEventRecord {
77 | [CmdletBinding()]
78 | param(
79 | [Parameter(Mandatory=$true)][string]$Timestamp,
80 | [Parameter(Mandatory=$true)][string]$OpCorrelationID,
81 | [Parameter(Mandatory=$true)][string]$Modifier,
82 | [Parameter(Mandatory=$true)][string]$ModifierSAM,
83 | [Parameter(Mandatory=$true)][string]$TargetObject,
84 | [Parameter(Mandatory=$true)][string]$TargetDN,
85 | [Parameter(Mandatory=$true)][string]$TargetType
86 | )
87 |
88 | try{
89 | #Mandatory: [Timestamp],[OpCorrelationID],[Modifier],[TargetObject]
90 | $returnData = Start-SQLCommand -SQLQuery @"
91 | EXEC AddEventRecord '$Timestamp','$OpCorrelationID','$Modifier','$ModifierSAM','$TargetObject','$TargetDN','$TargetType'
92 | "@
93 | Write-Verbose "Successfully added ACL-history Event record $($OpCorrelationID)"
94 | }
95 | catch{
96 | Write-Warning "Failed when adding ACL-history Event record to database"
97 | }
98 | }
99 |
100 | function Add-ACLModificationRecord {
101 | [CmdletBinding()]
102 | param(
103 | [Parameter(Mandatory=$true)][string]$Timestamp,
104 | [Parameter(Mandatory=$true)][string]$OpCorrelationID,
105 | [Parameter(Mandatory=$true)][string]$SDDLType,
106 | [Parameter(Mandatory=$false)][string]$Type = $null,
107 | [Parameter(Mandatory=$false)][string]$Principal = $null,
108 | [Parameter(Mandatory=$true)][string]$Access,
109 | [Parameter(Mandatory=$false)][string]$AppliesTo = $null,
110 | [Parameter(Mandatory=$true)][string]$Operation,
111 | [Parameter(Mandatory=$true)][string]$Checksum
112 | )
113 |
114 | try{
115 | #Mandatory: [Timestamp],[OpCorrelationID],[SDDLType],[Type],[Principal],[Access],[AppliesTo],[Operation],[Checksum]
116 | $returnData = Start-SQLCommand -SQLQuery @"
117 | EXEC AddModificationRecord '$Timestamp','$OpCorrelationID','$SDDLType','$Type','$Principal','$Access','$AppliesTo','$Operation','$Checksum'
118 | "@
119 | Write-Verbose "Successfully added ACL-history Modification record $($OpCorrelationID)"
120 | }
121 | catch{
122 | Write-Warning "Failed when adding ACL-history Modification record to database"
123 | }
124 | }
125 |
126 | function Get-StringHash {
127 | param (
128 | [String]$String,
129 | $HashName = "MD5"
130 | )
131 | $bytes = [System.Text.Encoding]::UTF8.GetBytes($String)
132 | $algorithm = [System.Security.Cryptography.HashAlgorithm]::Create('MD5')
133 | $StringBuilder = New-Object System.Text.StringBuilder
134 | $algorithm.ComputeHash($bytes) |
135 | ForEach-Object { $null = $StringBuilder.Append($_.ToString("x2")) }
136 | $StringBuilder.ToString()
137 | }
--------------------------------------------------------------------------------
/Active Directory/ACL/ACLHistory/Readme.md:
--------------------------------------------------------------------------------
1 | https://www.froxxen.com/2020/11/23/the-access-control-lottery-or-list/
2 |
--------------------------------------------------------------------------------
/Active Directory/ACL/ACLHistory/SQL Database/BuildSQLDependencies.txt:
--------------------------------------------------------------------------------
1 | -- Create tables
2 |
3 | CREATE TABLE Events
4 | (
5 | [Timestamp] datetime NOT NULL,
6 | [OpCorrelationID] nvarchar(64) NOT NULL PRIMARY KEY,
7 | [Modifier] nvarchar(128) NOT NULL,
8 | [ModifierSAM] nvarchar(128) NOT NULL,
9 | [TargetObject] nvarchar(256) NOT NULL,
10 | [TargetDN] nvarchar(256) NULL,
11 | [TargetType] nvarchar(256) NOT NULL
12 | );
13 |
14 | CREATE TABLE Modifications
15 | (
16 | [Timestamp] datetime NOT NULL,
17 | [OpCorrelationID] nvarchar(64) NOT NULL,
18 | [SDDLType] nvarchar(16) NOT NULL,
19 | [Type] nvarchar(16) NULL,
20 | [Principal] nvarchar(128) NULL,
21 | [Access] nvarchar(256) NOT NULL,
22 | [AppliesTo] nvarchar(128) NULL,
23 | [Operation] nvarchar(16) NOT NULL,
24 | [Checksum] nvarchar(48) NOT NULL PRIMARY KEY
25 | );
26 |
27 | -- Create stored procedures
28 |
29 | CREATE PROCEDURE AddEventRecord
30 | @Timestamp datetime,
31 | @OpCorrelationID nvarchar(64),
32 | @Modifier nvarchar(128),
33 | @ModifierSAM nvarchar(64),
34 | @TargetObject nvarchar(256),
35 | @TargetDN nvarchar(256),
36 | @TargetType nvarchar(128)
37 | AS
38 | BEGIN
39 | INSERT INTO Events(
40 | [Timestamp],[OpCorrelationID],[Modifier],[ModifierSAM],[TargetObject],[TargetDN],[TargetType]
41 | )
42 | VALUES (@Timestamp,@OpCorrelationID,@Modifier,@ModifierSAM,@TargetObject,@TargetDN,@TargetType);
43 | END
44 | GO
45 |
46 | CREATE PROCEDURE AddModificationRecord
47 | @Timestamp datetime,
48 | @OpCorrelationID nvarchar(64),
49 | @SDDLType nvarchar(16) = NULL,
50 | @Type nvarchar(16) = NULL,
51 | @Principal nvarchar(128),
52 | @Access nvarchar(256),
53 | @AppliesTo nvarchar(128) = NULL,
54 | @Operation nvarchar(16),
55 | @Checksum nvarchar(48)
56 | AS
57 | BEGIN
58 | INSERT INTO Modifications(
59 | [Timestamp],[OpCorrelationID],[SDDLType],[Type],[Principal],[Access],[AppliesTo],[Operation],[Checksum]
60 | )
61 | VALUES (@Timestamp,@OpCorrelationID,@SDDLType,@Type,@Principal,@Access,@AppliesTo,@Operation,@Checksum)
62 | END
63 | GO
64 |
65 | CREATE PROCEDURE GetAllACLRecords
66 | AS
67 | BEGIN
68 | SELECT
69 | Events.[Timestamp],
70 | Events.[OpCorrelationID],
71 | [Modifier],
72 | [ModifierSAM],
73 | [TargetObject],
74 | [TargetDN],
75 | [TargetType],
76 | [SDDLType],
77 | [Type],
78 | [Principal],
79 | [Access],
80 | [AppliesTo],
81 | [Operation]
82 | FROM Events
83 | RIGHT JOIN Modifications
84 | ON Events.OpCorrelationID = Modifications.OpCorrelationID
85 | ORDER BY Timestamp DESC
86 | END
87 | GO
88 |
89 | CREATE PROCEDURE GetACLRecordsWithinDates
90 | @EndDate datetime,
91 | @StartDate datetime
92 | AS
93 | BEGIN
94 | SELECT
95 | Events.[Timestamp],
96 | Events.[OpCorrelationID],
97 | [Modifier],
98 | [ModifierSAM],
99 | [TargetObject],
100 | [TargetDN],
101 | [TargetType],
102 | [SDDLType],
103 | [Type],
104 | [Principal],
105 | [Access],
106 | [AppliesTo],
107 | [Operation]
108 | FROM Events
109 | RIGHT JOIN Modifications
110 | ON Events.OpCorrelationID = Modifications.OpCorrelationID
111 | WHERE Events.Timestamp BETWEEN @EndDate and @StartDate
112 | ORDER BY Timestamp DESC
113 | END
114 | GO
115 |
116 | CREATE PROCEDURE GetTargetTypes
117 | @EndDate datetime,
118 | @StartDate datetime
119 | AS
120 | BEGIN
121 | SELECT DISTINCT [TargetType] FROM Events
122 | WHERE Timestamp BETWEEN @EndDate and @StartDate
123 | ORDER BY TargetType
124 | END
125 | GO
126 |
127 | CREATE PROCEDURE GetSDDLTypes
128 | @EndDate datetime,
129 | @StartDate datetime
130 | AS
131 | BEGIN
132 | SELECT DISTINCT [SDDLType] FROM Modifications
133 | WHERE Timestamp BETWEEN @EndDate and @StartDate
134 | ORDER BY SDDLType
135 | END
136 | GO
137 |
138 | CREATE PROCEDURE GetModifiers
139 | @EndDate datetime,
140 | @StartDate datetime
141 | AS
142 | BEGIN
143 | SELECT DISTINCT [Modifier] FROM Events
144 | WHERE Timestamp BETWEEN @EndDate and @StartDate
145 | ORDER BY Modifier
146 | END
147 | GO
148 |
149 | CREATE PROCEDURE GetOperations
150 | @EndDate datetime,
151 | @StartDate datetime
152 | AS
153 | BEGIN
154 | SELECT DISTINCT [Operation] FROM Modifications
155 | WHERE Timestamp BETWEEN @EndDate and @StartDate
156 | ORDER BY Operation
157 | END
158 | GO
159 |
160 | CREATE PROCEDURE GetTargetObjects
161 | @EndDate datetime,
162 | @StartDate datetime
163 | AS
164 | BEGIN
165 | SELECT DISTINCT [TargetObject] FROM Events
166 | WHERE Timestamp BETWEEN @EndDate and @StartDate
167 | ORDER BY TargetObject
168 | END
169 | GO
170 |
171 | CREATE PROCEDURE GetPrincipals
172 | @EndDate datetime,
173 | @StartDate datetime
174 | AS
175 | BEGIN
176 | SELECT DISTINCT [Principal] FROM Modifications
177 | WHERE Timestamp BETWEEN @EndDate and @StartDate
178 | ORDER BY Principal
179 | END
180 | GO
181 |
182 | CREATE PROCEDURE GetAccesses
183 | @EndDate datetime,
184 | @StartDate datetime
185 | AS
186 | BEGIN
187 | SELECT DISTINCT [Access] FROM Modifications
188 | WHERE Timestamp BETWEEN @EndDate and @StartDate
189 | ORDER BY Access
190 | END
191 | GO
192 |
193 | CREATE PROCEDURE GetAppliesTos
194 | @EndDate datetime,
195 | @StartDate datetime
196 | AS
197 | BEGIN
198 | SELECT DISTINCT [AppliesTo] FROM Modifications
199 | WHERE Timestamp BETWEEN @EndDate and @StartDate
200 | ORDER BY AppliesTo
201 | END
202 | GO
203 |
204 | CREATE PROCEDURE GetGrantedTypes
205 | @EndDate datetime,
206 | @StartDate datetime
207 | AS
208 | BEGIN
209 | SELECT DISTINCT [Type] FROM Modifications
210 | WHERE Timestamp BETWEEN @EndDate and @StartDate
211 | ORDER BY Type
212 | END
213 | GO
214 |
215 | CREATE PROCEDURE GetStartDate
216 | AS
217 | BEGIN
218 | SELECT TOP 1 [Timestamp] FROM Events ORDER BY Timestamp DESC
219 | END
220 | GO
221 |
222 | CREATE PROCEDURE GetEndDate
223 | AS
224 | BEGIN
225 | SELECT TOP 1 [Timestamp] FROM Events ORDER BY Timestamp
226 | END
227 | GO
228 |
229 | -- Add permission for AD group to stored procedures
230 |
231 | -- Grant permissions to Read-group
232 |
233 | GRANT EXECUTE ON OBJECT::GetACLRecordsWithinDates TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
234 | GRANT EXECUTE ON OBJECT::GetStartDate TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
235 | GRANT EXECUTE ON OBJECT::GetEndDate TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
236 | GRANT EXECUTE ON OBJECT::GetGrantedTypes TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
237 | GRANT EXECUTE ON OBJECT::GetOperations TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
238 | GRANT EXECUTE ON OBJECT::GetTargetObjects TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
239 | GRANT EXECUTE ON OBJECT::GetPrincipals TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
240 | GRANT EXECUTE ON OBJECT::GetAccesses TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
241 | GRANT EXECUTE ON OBJECT::GetAppliesTos TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
242 | GRANT EXECUTE ON OBJECT::GetAllACLRecords TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
243 | GRANT EXECUTE ON OBJECT::GetTargetTypes TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
244 | GRANT EXECUTE ON OBJECT::GetSDDLTypes TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
245 | GRANT EXECUTE ON OBJECT::GetModifiers TO [FROXXEN\Res_SQL_DB-ACLHistory_Read]
246 |
247 | -- Grant permissions to Write-group
248 | GRANT EXECUTE ON OBJECT::GetACLRecordsWithinDates TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
249 | GRANT EXECUTE ON OBJECT::GetStartDate TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
250 | GRANT EXECUTE ON OBJECT::GetEndDate TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
251 | GRANT EXECUTE ON OBJECT::GetGrantedTypes TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
252 | GRANT EXECUTE ON OBJECT::GetOperations TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
253 | GRANT EXECUTE ON OBJECT::GetTargetObjects TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
254 | GRANT EXECUTE ON OBJECT::GetPrincipals TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
255 | GRANT EXECUTE ON OBJECT::GetAccesses TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
256 | GRANT EXECUTE ON OBJECT::GetAppliesTos TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
257 | GRANT EXECUTE ON OBJECT::GetAllACLRecords TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
258 | GRANT EXECUTE ON OBJECT::GetTargetTypes TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
259 | GRANT EXECUTE ON OBJECT::GetSDDLTypes TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
260 | GRANT EXECUTE ON OBJECT::GetModifiers TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
261 | GRANT EXECUTE ON OBJECT::AddEventRecord TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
262 | GRANT EXECUTE ON OBJECT::AddModificationRecord TO [FROXXEN\Res_SQL_DB-ACLHistory_Write]
263 |
--------------------------------------------------------------------------------
/Active Directory/ACL/ACLHistory/Scheduled Tasks/Get-ADACLModifications.xml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/Active Directory/ACL/ACLHistory/Scheduled Tasks/Get-ADACLModifications.xml
--------------------------------------------------------------------------------
/Active Directory/ACL/ACLHistory/Scheduled Tasks/Send-ADACLModifications.xml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/Active Directory/ACL/ACLHistory/Scheduled Tasks/Send-ADACLModifications.xml
--------------------------------------------------------------------------------
/Active Directory/ACL/ACLHistory/Send-ADACLModifications.ps1:
--------------------------------------------------------------------------------
1 | ## This scripts queries the database ACLHistory and sends a mail notifications with changes
2 | ##
3 | ## Author: Fredrik Bergman, 2020-11-20
4 | ## Version 1.0.0 - First version //Fredrik Bergman 2020-11-20
5 | ##
6 |
7 | #region DECLARE SCRIPT DEPENDENCIES
8 | $ScriptVariables = @{
9 | "ScriptFolder" = "C:\PowerShell\TaskScheduler\Get-ADACLModifications"
10 | "LastMinutes" = 60
11 | "MailFrom" = 'noreply@froxxen.com'
12 | "MailTo" = 'froxxen@froxxen.com'
13 | "MailSubject" = 'Recent Active Directory ACL Modifications'
14 | "SMTPServer" = 'mail.froxxen.com'
15 | "SSRSReport" = 'https://reports.froxxen.com/reports/report/ACLHistory/ACLHistory'
16 | "ACLHistoryManagement" = "C:\PowerShell\TaskScheduler\Get-ADACLModifications\Modules\ACLHistoryManagement.psm1"
17 | "ADRightsModulePath" = "C:\PowerShell\TaskScheduler\ActiveDirectoryRightsModule\ActiveDirectoryRightsModule.psm1"
18 | "Colors" = @{
19 | "Added" = "#3f82b0"
20 | "Changed" = "#a52869"
21 | "Critical" = "#b8812e"
22 | "Error" = "#a52869"
23 | "Removed" = "#db3f28"
24 | }
25 | "CriticalPermissions" = @('FullControl','Full Control','All Extended Rights','ExtendedRight ')
26 | }
27 |
28 | Import-Module $ScriptVariables.ACLHistoryManagement
29 | Import-Module $ScriptVariables.ADRightsModulePath
30 |
31 |
32 | function Get-RowColor {
33 | param (
34 | [Parameter(Mandatory=$true)]
35 | [int]$Counter
36 | )
37 | if ( $Counter % 2 -eq 0 ) {
38 | $color = '#ffffff'
39 | }
40 | else {
41 | $color = '#eeeeee'
42 | }
43 | $color
44 | }
45 |
46 | # CSS for HTML
47 | $Style = @"
48 |
121 | "@
122 |
123 | # Get all ACL-modifications since...
124 | if ( !$ModifiedACLs ) {
125 | [array]$ModifiedACLs = Get-ACLHistoryLogs -EndDate $((get-date).AddMinutes(-$($ScriptVariables.LastMinutes)))
126 | }
127 |
128 | if ( $ModifiedACLs ) {
129 | #region Main table
130 | $HTMLTableForEmail = "$Style`r`n"
131 | $HTMLTableForEmail += "Summary of Access Control List (ACL) Modifications |
"
132 | $HTMLTableForEmail += "Report created: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") |
"
133 | if ( $ScriptVariables.SSRSReport -ne '' ) {
134 | $HTMLTableForEmail += "Link to SSRS report |
"
135 | }
136 | #region Summary table
137 | [int]$TotalModifications = $($ModifiedACLs | Group OpCorrelationID).Count
138 | [int]$TotalACEAdditions = @($($ModifiedACLs | Where Operation -eq 'Added' )).Count
139 | [int]$TotalACERemovals = @($($ModifiedACLs | Where Operation -eq 'Removed' )).Count
140 | [int]$TotalCriticals = @($($ModifiedACLs | where { $_.Access -match "$($ScriptVariables.CriticalPermissions -join '|')" -and $_.Operation -eq 'Added' })).count
141 | $HTMLTableForEmail += "Total Modifications: | Added ACEs: | Removed ACEs | Potentially Critical events | $($TotalModifications) | $TotalACEAdditions | $TotalACERemovals | $TotalCriticals |
|
"
142 | #endregion
143 | #region Top Modifier table
144 | $HTMLTableForEmail += "Top 5 modifiers |
"
145 | $HTMLTableForEmail += "Modified by | Count | "
146 | $Counter = 0
147 | foreach ( $TopModifier in $ModifiedACLs | Group Modifier | Select -First 5 | Sort-Object Count -Descending) {
148 | $color = Get-RowColor $Counter
149 | $HTMLTableForEmail += "$($TopModifier.Name)$($TopModifier.Group[0].ModifierSAM) | $($TopModifier.Count) |
"
150 | $Counter++
151 | }
152 | $HTMLTableForEmail += "
"
153 | #endregion
154 | #region Modifications table
155 | $HTMLTableForEmail += "List of ACL modifications |
"
156 | $HTMLTableForEmail += "Timestamp | Modified by | Target Object | Modifications | "
157 | foreach ( $ACL in $ModifiedACLs | Group OpCorrelationId ) {
158 | $Counter++
159 | $color = Get-RowColor $Counter
160 | $ACLMeta = $ACL.Group[0]
161 | $HTMLTableForEmail += "$($ACLMeta.Timestamp) | $($ACLMeta.Modifier)$($ACLMeta.ModifierSAM) | $($ACLMeta.TargetType):$($ACLMeta.TargetObject) | "
162 | foreach ( $ACE in $ACL.Group ) {
163 | $textcolor = $ScriptVariables.Colors.$($ACE.Operation)
164 | if ( $ACE.Access -match "$($ScriptVariables.CriticalPermissions -join '|')" -and $ACE.Operation -eq 'Added' ) {
165 | $CriticalEvent = "class=`"Critical`""
166 | $Access = "$($ACE.Access)"
167 | }
168 | else {
169 | $CriticalEvent = $null
170 | $Access = $ACE.Access
171 | }
172 | $HTMLTableForEmail += "$($ACE.SDDLType) | $($ACE.Operation) | Type | $($ACE.Type) | Principal | $($ACE.Principal) | Access | $($Access) | Applies to | $($ACE.AppliesTo) | "
173 | }
174 | $HTMLTableForEmail += "$($ACL.Group[0].OpCorrelationId)"
175 | }
176 | #endregion
177 | $HTMLTableForEmail += " |
|
"
178 | #endregion Main table
179 |
180 | #region SEND NOTIFICATION VIA EMAIL
181 | $mail = New-Object System.Net.Mail.MailMessage -Property @{
182 | From = $ScriptVariables.MailFrom
183 | Subject = $ScriptVariables.MailSubject
184 | Body = $HTMLTableForEmail
185 | IsBodyHtml = $true
186 | }
187 | $mail.To.Add($ScriptVariables.MailTo)
188 | $SMTPClient = New-Object -TypeName System.Net.Mail.SmtpClient( $ScriptVariables.SMTPServer )
189 | $SMTPClient.Send( $Mail )
190 | #endregion
191 | }
--------------------------------------------------------------------------------
/Active Directory/Get-BlockedInheritanceUsers.ps1:
--------------------------------------------------------------------------------
1 | $Containers = @()
2 | $UserStatuses = @()
3 |
4 | "Reading OU List ..."
5 | $Containers = Get-ADOrganizationalUnit -Filter * -Properties * | sort canonicalname | select distinguishedname, canonicalname
6 |
7 | "Reading Container List ..."
8 | $Containers += Get-ADObject -SearchBase (Get-ADDomain).distinguishedname -SearchScope OneLevel -LDAPFilter '(objectClass=container)' -Properties * | sort canonicalname | select distinguishedname, canonicalname
9 |
10 | foreach($Cntr in $Containers)
11 | {
12 | "Evaluating - " + $Cntr.distinguishedname + " ..."
13 |
14 | $UserStatuses += Get-ADUser -Filter * -SearchBase $Cntr.distinguishedname -SearchScope OneLevel -Properties * | where {($_.nTSecurityDescriptor.AreAccessRulesProtected -eq $true) -and ($_.enabled -eq $true)} | select @{n='OU';e={$Cntr.distinguishedname}}, displayname, userprincipalname,samAccountName, @{n='Inheritance Broken';e={$_.nTSecurityDescriptor.AreAccessRulesProtected}}
15 | }
16 |
17 | $UserStatuses | export-csv -path C:\temp\UsersWithInheritanceBroken.csv
--------------------------------------------------------------------------------
/Active Directory/Get-DeletedObjects.ps1:
--------------------------------------------------------------------------------
1 | $date = New-Object System.DateTime(2017,2,20)
2 | $Users = get-adobject -filter {(createTimeStamp -gt $date) -and (deleted -eq $True)} -IncludeDeletedObjects -properties *
3 | Clear-Host
4 | samAccountName
5 | ForEach ( $User in $Users ) {
6 | If ( $User.objectClass -eq "groupPolicyContainer" ) { "$($User.DisplayName)`n$($User.objectClass)`n$($User.Modified)`n" ; Continue }
7 | "$($User."msDS-LastKnownRDN")`n$($User.objectClass)`n$($User.Modified)`n"
8 | }
--------------------------------------------------------------------------------
/Active Directory/Remove-ADObjectFromACL/Remove-ADObjectFromACL.ps1:
--------------------------------------------------------------------------------
1 | ## This script removes an objects access in a specified ACL
2 | ##
3 | ## Logs can be found in .\Logs folder
4 | ##
5 | ## Version 1.0.0 - First release // 2020-11-05
6 | ## Version 1.0.1 - Changed the parameter IdentityReference to array with corresponding funcitonality // 2020-11-06
7 | ## Version 1.0.2 - Added functionality so only objects with one or more matching IdentityReferences will be added to $ADObjects // 2020-11-06
8 |
9 | #region Variables and functions
10 | $ScriptVariables = @{
11 | ScriptFolder = "C:\Scripts\Remove-ADObjectFromACL"
12 | Threshold = 1
13 | SearchBase = "OU=Domain Computers,DC=domain,DC=local"
14 | IdentityReferences = @('BUILTIN\Account Operators','BUILTIN\Print Operators')
15 | }
16 |
17 | Set-Location $ScriptVariables.ScriptFolder -ErrorAction SilentlyContinue
18 | $logsFolder = Join-Path $ScriptVariables.ScriptFolder "Logs"
19 |
20 | function Remove-ADObjectFromACL {
21 | <#
22 | .SYNOPSIS
23 | Removes an entire object from a specified Access Control List (ACL)
24 |
25 | .DESCRIPTION
26 | Removes an entire object from a specified ACL
27 |
28 | .PARAMETER IdentityReference
29 | Specify the IdentityReference (array) that will be removed from the target object
30 |
31 | .PARAMETER TargetDN
32 | Specify the DistinguishedName of one object that should get the IdentityReference(s) removed from the ACL
33 |
34 | .EXAMPLE
35 | Remove-ADObjectFromACL -IdentityReference "BUILTIN\Print Operators" -TargetDN "CN=TestComputer,DC=domain,DC=local"
36 | Removes 'BUILTIN\Print Operators' from the ACL of 'TestComputer'
37 |
38 | .EXAMPLE
39 | Remove-ADObjectFromACL -IdentityReference "BUILTIN\Print Operators","BUILTIN\Account Operators" -TargetDN "CN=TestComputer,DC=domain,DC=local"
40 | Removes 'BUILTIN\Print Operators' and 'BUILTIN\Account Operators' from the ACL of 'TestComputer'
41 |
42 | .FUNCTIONALITY
43 | ACL Management
44 | #>
45 |
46 | param(
47 | [parameter(mandatory=$true)][ValidateNotNullOrEmpty()]
48 | [array]$IdentityReference,
49 | [parameter(mandatory=$true)][ValidateNotNullOrEmpty()]
50 | [string]$TargetDN
51 | )
52 |
53 | try {
54 | Import-Module ActiveDirectory -ErrorAction Stop
55 | }
56 | catch {
57 | Write-Error $_.Exception.Message
58 | break
59 | }
60 |
61 | $TargetDistinguishedName = [ADSI]("LDAP://$TargetDN")
62 | if ( $TargetDistinguishedName.distinguishedName ) {
63 | $CurrentACEinACL = @()
64 | $GetCurrentACEinACL = @()
65 | $IdentitiesFound = @()
66 | foreach ( $identity in $IdentityReference ) {
67 | [array]$GetCurrentACEinACL = $(Get-Acl -Path "AD:$($TargetDistinguishedName.distinguishedName)" ).Access | Where { $_.IdentityReference -eq "$Identity" -and $_.IsInherited -eq $false}
68 | if ( $GetCurrentACEinACL.Count -gt 0 ) {
69 | Write-Log "Found $($GetCurrentACEinACL.Count) ACE(s) for `'$Identity`' to remove from `'$($TargetDistinguishedName.distinguishedName)`'"
70 | $IdentitiesFound += $Identity
71 | [array]$CurrentACEinACL += $GetCurrentACEinACL
72 | }
73 | }
74 | if ( $CurrentACEinACL.Count -gt 0 ) {
75 | foreach ( $RemoveACE in $CurrentACEinACL ) {
76 | [void]$TargetDistinguishedName.PSBase.ObjectSecurity.RemoveAccessRule($RemoveACE)
77 | }
78 | try {
79 | $TargetDistinguishedName.PSBase.CommitChanges()
80 | Write-Log "Successfully removed ACE(s) for `'$($IdentitiesFound -join "`',`'")`' from `'$($TargetDistinguishedName.distinguishedName)`'"
81 | }
82 | catch {
83 | Write-Log "Failed to remove ACE(s) for `'$($IdentitiesFound -join "`',`'")`' from `'$($TargetDistinguishedName.distinguishedName)`', error: $($_.Exception.Message)"
84 | }
85 | }
86 | }
87 | else {
88 | Write-Warning "The object `'$TargetDN`' could not be found in Active Directory"
89 | }
90 | }
91 |
92 | Function Write-Log {
93 | param([Parameter(Mandatory=$true, Position=0)][string]$Message)
94 | $logdate = (Get-Date -format "yyyy-MM-dd")
95 | $logtime = (Get-Date -format "yyyy-MM-dd HH:mm:ss") + " >>"
96 | $logfile = "Logfile_" + $logdate + ".log"
97 | $logfilepath = Join-Path $logsFolder $logfile
98 | if( (test-path $logfilepath) ) {
99 | "$logtime $Message" | Out-File -Append $logfilepath -Encoding utf8
100 | Write-Verbose "$logtime $Message" -Verbose
101 | }
102 | else {
103 | Write-Verbose "$logtime $Message" -Verbose
104 | }
105 | }
106 | #endregion
107 |
108 | if ( !$ADObjects ) {
109 | $ADObjects = @()
110 | $TempADObjects = Get-ADComputer -Filter * -SearchBase $ScriptVariables.SearchBase -properties ntSecurityDescriptor | Select Name, distinguishedName, ntSecurityDescriptor
111 | foreach ( $ADObject in $TempADObjects ) {
112 | foreach ( $Identity in $ScriptVariables.IdentityReferences ) {
113 | if ( $ADObject.distinguishedName -notin $ADObjects ) {
114 | if ( $identity -in $ADObject.ntSecurityDescriptor.Access.IdentityReference ) {
115 | $ADObjects += ($ADObject).DistinguishedName
116 | }
117 | }
118 | }
119 | }
120 | }
121 |
122 | foreach ( $ADObject in $ADObjects | Select -First $ScriptVariables.Threshold ) {
123 | Remove-ADObjectFromACL -TargetDN $ADObject -IdentityReference $ScriptVariables.IdentityReferences
124 | }
125 |
126 | # Run below to see specific IdentityReferences for an object
127 | # ($(Get-Acl -Path "AD:$($ADObject)" ).Access | Where { $_.IsInherited -eq $false}).IdentityReference | Select -Unique | Sort
128 |
--------------------------------------------------------------------------------
/Active Directory/SecBaselinePrep/Get-RegData_For_SecBaseline.ps1:
--------------------------------------------------------------------------------
1 | $content = get-content C:\temp\SecBaselinesToCompare.csv | convertfrom-csv -Delimiter ';' | where RegPath -ne $null
2 | $ServerOU = ""
3 | [array]$servers = get-adcomputer -ldapfilter '(name=*)' -Properties Name, distinguishedName, Description, OperatingSystem -SearchBase $ServerOU -SearchScope Subtree | where { $_.operatingSystem -like '*Windows*'}
4 | $OutFile = "C:\Temp\MemberServers-RegistrySummary.csv"
5 | $failedsessions = 0
6 | $successessions = 0
7 | $counter = 1
8 | $objects = @()
9 | foreach ( $server in $servers ) {
10 | $Hostname = $server.Name
11 | write-host "Processing $Counter / $($Servers.Count) - $Hostname" -NoNewline
12 | try {
13 | $Session = New-PSSession -ComputerName $hostname -ErrorAction SilentlyContinue
14 | $localobj = $null
15 | $localobj = Invoke-Command -Session $Session -ArgumentList (,$content) -ScriptBlock {
16 | param ( [array]$content )
17 | $remoteobjects = @()
18 | foreach ( $item in $content | where RegPath -ne $null ) {
19 | try {
20 | $data = $(Get-ItemProperty $item.RegPath -Name $item.RegValue -ErrorAction SilentlyContinue).$($item.RegValue)
21 | if ( $item.RegData -ne $data ) { $Status = 'Different' }
22 | if ( $item.RegData -eq $data ) { $Status = 'Match' }
23 | $props = @{
24 | DisplayName = $item.DisplayName
25 | RegPath = $item.RegPath
26 | RegValue = $item.RegValue
27 | RegData = $Data
28 | Hostname = $env:ComputerName
29 | Status = $Status
30 | }
31 | $remoteobj = new-object psobject -Property $props
32 | $remoteobjects += $remoteobj
33 | }
34 | catch {}
35 | }
36 | return $remoteobjects
37 | }
38 | if ( $localobj ) {
39 | $objects += $localobj
40 | }
41 | write-host " - " -NoNewline
42 | write-host "succeeded" -ForegroundColor Green
43 | $successessions++
44 | }
45 | catch {
46 | write-host " - " -NoNewline
47 | write-host "failed" -ForegroundColor Red
48 | $failedsessions++
49 | }
50 | finally {
51 | if ( $Session ) {
52 | Remove-PSSession $Session -ErrorAction SilentlyContinue
53 | }
54 | }
55 | $Counter++
56 | }
57 | # Output the result to CSV-file
58 | $objects | select HostName, DisplayName, Status, RegData, RegValue, RegPath | convertto-csv -Delimiter ';' | % {$_ -replace '"',''} | out-file $outFile -Encoding utf8
59 |
60 | # Show compliance per DisplayName
61 | $objects | Group-Object DisplayName |
62 | Select @{Name="Display";Expression={$_.Name}},
63 | @{Name="Match";Expression={ ($_.Group | Where {$_.Status -match "Match"}).Count }},
64 | @{Name="Diff";Expression={ ($_.Group | Where {$_.Status -match "Different"}).Count }},
65 | @{Name="Percentage";Expression={ "$((($_.Group | Where {$_.Status -match "Match"}).Count / ($_.Group).Count)*100)%" }} | sort Percentage | ft -AutoSize
66 |
67 | # Show summary
68 | write-output ""
69 | "Successful sessions : $successessions"
70 | "Failed sessions : $failedsessions"
71 | "Total : $($objects.count)"
72 | "Matches : $(($objects | where status -eq 'Match').count)"
--------------------------------------------------------------------------------
/Active Directory/SecBaselinePrep/Get-SummaryResult.ps1:
--------------------------------------------------------------------------------
1 | function Get-RegSummary {
2 | param ( $file )
3 | $results = get-content $file | convertfrom-csv -Delimiter ';'
4 | $results | Group-Object DisplayName |
5 | Select @{Name="Display";Expression={$_.Name}},
6 | @{Name="Match";Expression={ ($_.Group | Where {$_.Status -match "Match"}).Count }},
7 | @{Name="Diff";Expression={ ($_.Group | Where {$_.Status -match "Different"}).Count }},
8 | @{Name="Percentage";Expression={ "$((($_.Group | Where {$_.Status -match "Match"}).Count / ($_.Group).Count)*100)%" }} | sort Percentage | ft -AutoSize
9 | }
10 |
11 | function Get-URASummary {
12 | param ( $file )
13 | $results = get-content $file | convertfrom-csv -Delimiter ';'
14 | $results | Group-Object DisplayName |
15 | Select @{Name="Display";Expression={$_.Name}},
16 | @{Name="Match";Expression={ ($_.Group | Where {$_.Status -match "Match"}).Count }},
17 | @{Name="Diff";Expression={ ($_.Group | Where {$_.Status -match "Different"}).Count }},
18 | @{Name="Percentage";Expression={ "$((($_.Group | Where {$_.Status -match "Match"}).Count / ($_.Group).Count)*100)%" }} | sort Percentage | ft -AutoSize
19 | }
20 |
21 | get-regsummary "C:\Users\froxxon\Desktop\SecBaselinePrep\MemberServers-RegSummary.csv"
22 | #get-urasummary "C:\Users\froxxon\Desktop\SecBaselinePrep\MemberServers-URASummary.csv"
23 |
--------------------------------------------------------------------------------
/Active Directory/SecBaselinePrep/README.MD:
--------------------------------------------------------------------------------
1 | Get-RegData_For_SecBaseline.ps1:
2 | Query servers for the registry based values and matches with Microsofts baseline (in SecBaselinesToCompare.csv)
3 |
4 | Get-UserLogonRights.ps1:
5 | Query servers for the User Rights Assigment values and matches with Microsoft baseline (in hash table inside Invoke-Command)
6 |
7 | Get-SummaryResult.ps1:
8 | Shows summary of the above outfiles from the above scripts
9 |
--------------------------------------------------------------------------------
/Active Directory/Set-ADOwnerToDA/Set-ADOwnerToDA.ps1:
--------------------------------------------------------------------------------
1 | $OUDistinguishedName = "OU=Objects,$((Get-ADDomain).DistinguishedName)"
2 | $ClientOwners = Get-ADComputer -Filter * -properties ntSecurityDescriptor -SearchBase "$OUDistinguishedName" | Where { $_.ntSecurityDescriptor.Owner -ne 'DOMAIN\Domain Admins'} | Select Name, distinguishedName, @{name='Owner';e={$_.ntSecurityDescriptor.Owner}} | Sort
3 | $ClientOwners.Count
4 | $UserOwners = Get-ADUser -Filter * -properties ntSecurityDescriptor -SearchBase $OUDistinguishedName | Where { $_.ntSecurityDescriptor.Owner -ne 'DOMAIN\Domain Admins' } | Select Name, distinguishedName, @{name='Owner';e={$_.ntSecurityDescriptor.Owner}} | Sort
5 | $UserOwners.count
6 | $GroupOwners = Get-ADGroup -Filter * -properties ntSecurityDescriptor -SearchBase $OUDistinguishedName | Where { $_.ntSecurityDescriptor.Owner -ne 'DOMAIN\Domain Admins'} | Select Name, distinguishedName, @{name='Owner';e={$_.ntSecurityDescriptor.Owner}} | Sort
7 | $GroupOwners.count
8 |
9 | $objNewOwner = New-Object System.Security.Principal.NTAccount("DOMAIN", "Domain Admins")
10 | # CHANGE FOREACH BELOW TO THE CORRECT ARRAY (ex. $UserOwners) AND THE OUTFILE PATH
11 | foreach ( $object in $GroupOwners ) {
12 | $OutfileOld = "C:\Temp\ACLBackup\Group\$($object.Name)_Old.txt"
13 | $OutfileNew = "C:\Temp\ACLBackup\Group\$($object.Name)_New.txt"
14 | $ACL = Get-ACL -Path "AD:$($object.distinguishedName)"
15 | $ACL.sddl | out-file $OutfileOld -Append
16 | $ACL.SetOwner($objNewOwner)
17 | try {
18 | Set-ACL -Path "AD:$($object.distinguishedName)" -AclObject $ACL
19 | $ACL = Get-ACL -Path "AD:$($object.distinguishedName)"
20 | $ACL.sddl | out-file $OutfileNew -Append
21 | Write-Output "$((get-date -format "yyyy-MM-dd HH:mm:ss")) - Successfully changed Owner from `'$($object.Owner)`' to `'$($objNewOwner)`' for `'$($object.distinguishedName)`'"
22 | }
23 | catch {
24 | Write-Output "$((get-date -format "yyyy-MM-dd HH:mm:ss")) - Failed to change Owner from `'$($object.Owner)`' to `'$($objNewOwner)`' for `'$($object.distinguishedName)`'"
25 | }
26 | }
--------------------------------------------------------------------------------
/Azure/ConnectToAzure.ps1:
--------------------------------------------------------------------------------
1 | import-module msonline
2 | #get-command -module msonline
3 |
4 | $msolcred = get-credential "" # <- Enter username for Azure
5 | connect-msolservice -credential $msolcred
6 |
7 | $SyncedUsers = get-msoluser -MaxResults 10
8 | $AzureUsers = get-msoluser -MaxResults 10
9 |
10 | $SyncedUsers.Count
11 | $AzureUsers.Count
12 |
13 | $SyncedUsers[1] | fl
--------------------------------------------------------------------------------
/DNS and DHCP/Get-DNSRecordOwner.ps1:
--------------------------------------------------------------------------------
1 | Import-Module ActiveDirectory
2 | Clear-Host
3 |
4 | $DomainDN = $(Get-ADDomain).DistinguishedName
5 | $ClientPrefix = "*"
6 | $Domain = $(Get-ADDomain).DNSRoot
7 | $DomainShortName = $(Get-ADDomain).NetBIOSName
8 | $SearchBase = "OU=Clients,$DomainDN"
9 | $ServiceAccount = "" # <- Put the DHCP service account that should be owner of DNS records
10 | $Clients = $(Get-ADComputer -Filter "Name -like '$ClientPrefix-*'" -SearchBase $SearchBase).Name
11 | $WithAccount = @()
12 | $WithoutAccount = @()
13 |
14 | ForEach ( $Client in $($Clients )) {
15 | Try {
16 | $ClientDN = $(Get-DnsServerResourceRecord $Client -ZoneName $Domain -RRType A -ComputerName $Domain -ErrorAction SilentlyContinue ).DistinguishedName
17 | } Catch {}
18 | $Owner = $(Get-Acl -Path "ActiveDirectory:://RootDSE/$($ClientDN)" -ErrorAction SilentlyContinue).Owner
19 | If ( $Owner -ne "$DomainShortName\$ServiceAccount" -and $Owner -ne $Null ) {
20 | $WithoutAccount += $Client
21 | #Write-Host "$Counter. Client: $Client`tOwner: $Owner"
22 | #Remove-DnsServerResourceRecord $Client -ZoneName $Domain -RRType A -ComputerName $Domain -Force
23 | }
24 | ElseIf ( $Owner -eq "$DomainShortName\$ServiceAccount" -and $Owner -ne $Null ) {
25 | $WithAccount += $Client
26 | }
27 | }
28 | Write-host "Objects WIHTOUT $ServiceAccount as Owner: $($WithoutAccount.Count)"
29 | Write-host "Objects WIHT $ServiceAccount as Owner: $($WithAccount.Count)"
--------------------------------------------------------------------------------
/DNS and DHCP/Get-FaultyReverseLookupClients.ps1:
--------------------------------------------------------------------------------
1 | Clear-host
2 | $DNSServer = 'domain.local'
3 | $DNSDomain = ".domain.local."
4 | $OutFile = $false
5 | $OutFilePath = "C:\Scripts\DNS and DHCP"
6 | $Counter = 0
7 | $MatchingRL = @()
8 | $MismatchingRL = @()
9 | $MissingRL = @()
10 | $RZoneFilter = '*.in-addr.arpa'
11 | $FLClients = @()
12 | $RLClients = @{}
13 | $RLZClients = @()
14 | $MultipleRZoneRecords = @()
15 | $InactiveRZoneRecords = @()
16 |
17 | write-host " "
18 | write-host "Querying DNS for objects like " -NoNewline
19 | # Edit the next line to match hostnames you would like to match
20 | write-host "client* or server*" -ForegroundColor Yellow
21 | write-host "This might take about a minute to complete..."
22 | if ( $FLClients.Count -eq 0 ) {
23 | # Edit the end of the next line to match hostnames you would like to match
24 | $FLClients = Get-DnsServerResourceRecord -ZoneName $DNSServer -ComputerName $DNSServer -RRType A | Select @{Name='IPv4';Expression={$($_.RecordData.IPv4Address.IPAddressToString)}}, Hostname # | Where { $_.Hostname -like 'client*' -or $_.Hostname -like 'server*' }
25 | }
26 | write-host "Number of objects found: " -NoNewline ; write-host $FLClients.Count -ForegroundColor Green
27 | write-host " "
28 | write-host "Comparing objects in Forward and Reverse zones"
29 | write-host "This might take a couple of minutes..."
30 | write-host " "
31 |
32 | foreach ( $FLClient in $FLClients ) {
33 | $RLZoneName = "$($FLClient.IPv4.Split('.')[1]).$($FLClient.IPv4.Split('.')[0]).in-addr.arpa"
34 | $RLRecord = "$($FLClient.IPv4.Split('.')[3]).$($FLClient.IPv4.Split('.')[2])"
35 | try {
36 | $RLClient = $(Get-DnsServerResourceRecord $RLRecord -ZoneName $RLZoneName -ComputerName $DNSServer -RRType Ptr -ErrorAction 1 | select @{Name='IPv4';Expression={"$($FLClient.IPv4.Split('.')[0]).$($FLClient.IPv4.Split('.')[1]).$($_.Hostname.SPlit('.')[1]).$($_.Hostname.SPlit('.')[0])"}}, @{Name='Hostname';Expression={$($_.RecordData.PtrDomainName).TrimEnd($DNSDomain)}})
37 | if ( $FLClient.Hostname -eq $RLClient.Hostname ) {
38 | $MatchingRL += $FLClient.Hostname
39 | }
40 | else {
41 | $MismatchingRL += $FLClient.Hostname
42 | }
43 | }
44 | catch {
45 | $MissingRL += $FClient.Hostname
46 | }
47 | }
48 |
49 | write-host "Gather Reverse zones matching filter: " -NoNewline
50 | write-host $RZoneFilter -ForegroundColor Yellow
51 | $RLZones = $(Get-DnsServerZone -ComputerName $DNSServer | Where ZoneName -like $RZoneFilter).ZoneName
52 | write-host "Reverse zones found: " -NoNewline
53 | write-host "$($RLZones.Count)" -ForegroundColor Green
54 | write-host " "
55 |
56 | foreach ( $RLZone in $RLZones ) {
57 | $Counter++
58 | write-host "$Counter / $($RLZones.Count) - Get objects in Reverse zone: $RLZone - " -NoNewline
59 | if ( $RLZone.Split('.')[2] -eq 'in-addr' ) {
60 | $IPAddress = "$($RLZone.SPlit('.')[1]).$($RLZone.SPlit('.')[0])"
61 | # Edit the end of the next line to match hostnames you would like to match
62 | $RLZClients = $(Get-DnsServerResourceRecord -ZoneName $RLZone -ComputerName $DNSServer -RRType Ptr | select @{Name='IPv4';Expression={"$IPAddress.$($_.Hostname.SPlit('.')[1]).$($_.Hostname.SPlit('.')[0])"}}, @{Name='Hostname';Expression={$($_.RecordData.PtrDomainName).TrimEnd($DNSDomain)}}) #| Where { $_.Hostname -like 'client*' -or $_.Hostname -like 'server*' } | Sort IP
63 | }
64 | else {
65 | $IPAddress = "$($RLZone.SPlit('.')[2]).$($RLZone.SPlit('.')[1]).$($RLZone.SPlit('.')[0])"
66 | # Edit the end of the next line to match hostnames you would like to match
67 | $RLZClients = $(Get-DnsServerResourceRecord -ZoneName $RLZone -ComputerName $DNSServer -RRType Ptr | select @{Name='IPv4';Expression={"$IPAddress.$($_.Hostname.SPlit('.')[0])"}}, @{Name='Hostname';Expression={$($_.RecordData.PtrDomainName).TrimEnd($DNSDomain)}}) #| Where { $_.Hostname -like 'client*' -or $_.Hostname -like 'server*' } | Sort IP
68 | }
69 | write-host $RLZClients.Count -ForegroundColor Green
70 | foreach ( $RLClient in $RLZClients ) {
71 | if ( $RLClients.containskey($RLClient.Hostname) ) {
72 | $RLClients.$($RLClient.Hostname) = "$($RLClients.$($RLClient.Hostname));$($RLClient.IPv4)"
73 | }
74 | else {
75 | $RLClients.add($RLClient.Hostname,$RLClient.IPv4)
76 | }
77 | }
78 | }
79 |
80 | write-host " "
81 | write-host "Gather objects having multiple Reverse records"
82 | write-host "This might take a couple of minutes..."
83 | foreach ( $FLClient in $FLClients ) {
84 | try {
85 | $MultipleRecordCheck = $RLClients.$($FLClient.Hostname).Split(';')
86 | }
87 | catch {}
88 | if ( $MultipleRecordCheck.Count -gt 1 ) {
89 | foreach ( $Record in $MultipleRecordCheck ) {
90 | if ( $Record -ne $FLClient.IPv4 ) {
91 | $Object = New-Object PSObject -Property @{
92 | Hostname = $FLClient.Hostname
93 | IPv4 = $Record
94 | }
95 | $InactiveRZoneRecords += $Object
96 | }
97 | }
98 | }
99 | }
100 |
101 | write-host " "
102 | write-host "Matching objects : " -NoNewline ; write-host $($MatchingRL.Count) -ForegroundColor Green
103 | write-host "Mismatching objects : " -NoNewline ; write-host $($MismatchingRL.Count) -ForegroundColor Green
104 | write-host "Missing in Reverse zone : " -NoNewline ; write-host $($MissingRL.Count) -ForegroundColor Green
105 | write-host "Inactive Reverse objects : " -NoNewline ; write-host $($InactiveRZoneRecords.Count) -ForegroundColor Green
106 |
107 | if ( $OutFile -eq $true ) {
108 | $MatchingRL | out-file "$OutFilePath\DNSMatchingObjects.txt"
109 | $MismatchingRL | out-file "$OutFilePath\DNSMismatchingObjects.txt"
110 | $MissingRL | out-file "$OutFilePath\DNSMissingInReverseZone.txt"
111 | $InactiveRZoneRecords | out-file "$OutFilePath\DNSInactiveReverseObjects.txt"
112 | }
--------------------------------------------------------------------------------
/FirewallLogAnalyzer/FirewallLogAnalyzer.ps1:
--------------------------------------------------------------------------------
1 | $Computer = "TestClient"
2 | $LogFile = ".\FirewallLogAnalyzer_Results_$Computer.csv"
3 | $Headers = "Date", "Time", "Action", "Protocol", "SrcIP", "DstIP", "SrcPort", "DstPort", "Size", "TCPFlags", "TCPSyn", "TCPAck", "TCPWin", "ICMPType", "ICMPCode", "Info", "Path"
4 | $FileContent = Get-Content ".\pfirewall.log" | ConvertFrom-Csv -Delim ' ' -Header $Headers
5 |
6 | $List = @()
7 | $SrcHostNameList = @()
8 | $SrcHostNameList += $Computer
9 | $DstHostNameList = @()
10 | $DstHostNameList += $Computer
11 | $SrcHostIPList = @()
12 | $SrcHostIPList += "127.0.0.1"
13 | $DstHostIPList = @()
14 | $DstHostIPList += "127.0.0.1"
15 | $DstHostTypeList = @()
16 | $DstHostTypeList += "Localhost"
17 |
18 | $Counter = 0
19 | $UniqueCounter = 0
20 |
21 | ForEach ( $Line in $FileContent ) {
22 | $Counter++
23 | Write-Progress -Activity "Analyzing Firewall-log" -Status "Analyzing row: $Counter of $($FileContent.Count). Unique rules found: $UniqueCounter" -percentComplete ($Counter / $FileContent.Count * 100)
24 |
25 | If ( $Line.DstIP -Like "*:*" ) { Continue }
26 |
27 | If ( $SrcHostIPList -NotContains $Line.SrcIP ) {
28 | Try { $SrcHostName = $([System.Net.Dns]::gethostentry($Line.SrcIP)).Hostname }
29 | Catch { $SrcHostName = "Unknown" }
30 | $SrcHostIPList += $Line.SrcIP
31 | $SrcHostNameList += $SrcHostName
32 | }
33 | Else { $SrcHostName = $SrcHostNameList[$SrcHostIPList.IndexOf($Line.SrcIP)] }
34 |
35 | If ( $DstHostIPList -NotContains $Line.DstIP ) {
36 | Try { $DstHostName = $([System.Net.Dns]::gethostentry($Line.DstIP)).Hostname }
37 | Catch { $DstHostName = "Unknown" }
38 | $DstHostIPList += $Line.DstIP
39 | $DstHostNameList += $DstHostName
40 |
41 | If ( $DstHostName -Like "W*" ) {
42 | $DstHostNameShort = $DstHostName.Substring(0,$DstHostName.IndexOf("."))
43 | Try {
44 | $OU = $($(Get-ADComputer $DstHostNameShort).DistinguishedName -Replace "CN=$DstHostNameShort,OU=","")
45 | $OU = $OU.Substring(0,$OU.IndexOf(","))
46 | $DstHostTypeList += $OU
47 | }
48 | Catch {
49 | $DstHostTypeList += ""
50 | }
51 | }
52 | Else {
53 | If ( $DstHostName -Like "FILE*" ) {
54 | $DstHostTypeList += "CFS"
55 | }
56 | Else {
57 | $DstHostTypeList += ""
58 | }
59 | }
60 | }
61 | Else { $DstHostName = $DstHostNameList[$DstHostIPList.IndexOf($Line.DstIP)] }
62 |
63 | #region Destinationports
64 | $PortType = ""
65 | If ($Line.'DstPort' -eq "20" -Or $Line.'DstPort' -eq "21") { $PortType = "FTP" }
66 | If ($Line.'DstPort' -eq "22") { $PortType = "SSH" }
67 | If ($Line.'DstPort' -eq "23") { $PortType = "Telnet" }
68 | If ($Line.'DstPort' -eq "25") { $PortType = "SMTP" }
69 | If ($Line.'DstPort' -eq 53 -And $Line.'Protocol' -eq "TCP" ) { $PortType = "DNS Zone transfer" }
70 | If ($Line.'DstPort' -eq 53 -And $Line.'Protocol' -eq "UDP" ) { $PortType = "DNS Name mapping" }
71 | If ($Line.'DstPort' -eq "67" -Or $Line.'DstPort' -eq "68") { $PortType = "DHCP" }
72 | If ($Line.'DstPort' -eq "69") { $PortType = "TFTP" }
73 | If ($Line.'DstPort' -eq "80") { $PortType = "HTTP" }
74 | If ($Line.'DstPort' -eq "88") { $PortType = "Kerberos" }
75 | If ($Line.'DstPort' -eq "110") { $PortType = "POP3" }
76 | If ($Line.'DstPort' -eq "123") { $PortType = "NTP" }
77 | If ($Line.'DstPort' -eq "135") { $PortType = "RPC" }
78 | If ($Line.'DstPort' -eq "137" -Or $Line.'DstPort' -eq "138" -Or $Line.'DstPort' -eq "139") { $PortType = "NetBIOS" }
79 | If ($Line.'DstPort' -eq "143") { $PortType = "IMAP" }
80 | If ($Line.'DstPort' -eq "161" -Or $Line.'DstPort' -eq "162") { $PortType = "SNMP" }
81 | If ($Line.'DstPort' -eq "179") { $PortType = "BGP" }
82 | If ($Line.'DstPort' -eq "389") { $PortType = "LDAP" }
83 | If ($Line.'DstPort' -eq "443") { $PortType = "HTTPS" }
84 | If ($Line.'DstPort' -eq "464") { $PortType = "Kerberos (Change/Set PW)" }
85 | If ($Line.'DstPort' -eq "445") { $PortType = "SMB" }
86 | If ($Line.'DstPort' -eq "636") { $PortType = "LDAPS" }
87 | If ($Line.'DstPort' -eq "989" -Or $Line.'DstPort' -eq "990") { $PortType = "FTPS" }
88 | If ($Line.'DstPort' -eq "1688") { $PortType = "KMS" }
89 | If ($Line.'DstPort' -eq "2535") { $PortType = "MADCAP" }
90 | If ($Line.'DstPort' -eq "3268") { $PortType = "Global Catalog" }
91 | If ($Line.'DstPort' -eq "3269") { $PortType = "Global Catalog SSL" }
92 | If ($Line.'DstPort' -eq "3389") { $PortType = "RDP" }
93 | If ($Line.'DstPort' -eq "5061") { $PortType = "Skype External SIP" }
94 | If ($Line.'DstPort' -eq "5353") { $PortType = "Multicast DNS" }
95 | If ($Line.'DstPort' -eq "5355") { $PortType = "LLMNR" }
96 | If ($Line.'DstPort' -eq "5722") { $PortType = "DFSR" }
97 | If ($Line.'DstPort' -eq "5985") { $PortType = "WinRM" }
98 | If ($Line.'DstPort' -eq "8530" -Or $Line.'DstPort' -eq "8531") { $PortType = "WSUS" }
99 | If ($Line.'DstPort' -eq "9389") { $PortType = "SOAP" }
100 | If ($PortType -eq "" -And ($Line.'DstPort' -ge 49152 -And $Line.'DstPort' -le 65535)) { $PortType = "Dynamic (49152-65535)" }
101 | #endregion
102 |
103 | $Values = "$($Line.DstPort);$PortType;$($Line.Protocol);$SrcHostName;$($Line.SrcIP);$DstHostName;$($Line.DstIP);$($DstHostTypeList[$DstHostIPList.IndexOf($Line.DstIP)]);"
104 | If ( $List -NotContains $Values ) {
105 | $List += "$Values"
106 | $UniqueCounter++
107 | }
108 | }
109 |
110 | "Port;PortType;Protocol;SrcName;SrcIP;DstName;DstIP;OU" | Out-File $LogFile
111 | $List | Sort-Object | Out-File $LogFile -Append
--------------------------------------------------------------------------------
/InstallServer/img/InstallServer_GUI.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/InstallServer/img/InstallServer_GUI.jpg
--------------------------------------------------------------------------------
/InstallServer/img/TS_step_1_-_Start_InstallServer_script.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/InstallServer/img/TS_step_1_-_Start_InstallServer_script.jpg
--------------------------------------------------------------------------------
/InstallServer/img/TS_step_2_-_Konfigurera_natverksinstallningar.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/InstallServer/img/TS_step_2_-_Konfigurera_natverksinstallningar.jpg
--------------------------------------------------------------------------------
/InstallServer/img/TS_step_3_-_Satt_lokal_datorbeskrivning.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/InstallServer/img/TS_step_3_-_Satt_lokal_datorbeskrivning.jpg
--------------------------------------------------------------------------------
/InstallServer/img/TS_step_4_-_Satt_beskrivning_på_AD-objekt.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/InstallServer/img/TS_step_4_-_Satt_beskrivning_på_AD-objekt.jpg
--------------------------------------------------------------------------------
/InstallServer/img/TS_step_5_-_Lagger_till_servicefonstergrupper.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/InstallServer/img/TS_step_5_-_Lagger_till_servicefonstergrupper.jpg
--------------------------------------------------------------------------------
/InstallServer/img/TS_step_6_-_Satter_angiven_konfiguration_på_natverkskort.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/InstallServer/img/TS_step_6_-_Satter_angiven_konfiguration_på_natverkskort.jpg
--------------------------------------------------------------------------------
/InstallServer/readme.MD:
--------------------------------------------------------------------------------
1 | # INSTALLSERVER
2 |
3 | A home made GUI in Powershell, made with Visual Studio 2019 as a '*WPF App (.Net Core)*' and put output of the XAML in a variable (*$InputXML*) in the Powershell script (*some tweaking of the variable is made after this variable is set*).
4 |
5 | Then it is loaded in a MECM Task sequence and used to populate attributes for a new computer object in Active Directory, works as follows:
6 |
7 | *!! RestPS is not included at this time in this short documentation, used for populating 'Organizational units' and 'Maintenance Windows' in the GUI !!*
8 |
9 | ## Task Sequence step 1 - Start InstallServer
10 |
11 | 
12 |
13 | Trigger the GUI for InstallServer through the built-in script execution
14 |
15 | 
16 |
17 | ## Task Sequence step 2 - Configure network settings
18 |
19 | 
20 |
21 | The TS variable %FRXOU% is set through the main script and used to place the computer object in this step
22 |
23 | ## Task Sequence step 3 - Set local computer description
24 |
25 | 
26 |
27 | ```$tsenv = New-Object -ComObject Microsoft.SMS.TSEnvironment -ErrorAction Continue```
28 |
29 | ```Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\services\LanManServer\Parameters -Name srvcomment -Value $tsenv.Value("FRXDescription") -ErrorAction SilentlyContinue```
30 |
31 | ## Task Sequence step 4 - Set computer description in AD
32 |
33 | **This step requires that you've set (preferably) two hidden TS variables with username and password with delegated rights to perform current task**
34 |
35 | 
36 |
37 | ```$TSEnv = New-Object -ComObject Microsoft.SMS.TSEnvironment -ErrorAction Continue```
38 |
39 | ```$DomainDN = "LDAP://CN=$($TSEnv.Value("FRXComputerName")),$($TSEnv.Value("FRXOU"))"```
40 | ```$Computer = New-Object -TypeName System.DirectoryServices.DirectoryEntry -ArgumentList $DomainDN,$($TSEnv.Value("FRXCustomUserName")),$($TSEnv.Value("FRXCustomUserInfo"))```
41 | ```$Computer.description = $TSEnv.Value("FRXDescription")```
42 | ```$Computer.setinfo()```
43 |
44 | ## Task Sequence step 2 - Add service window groups
45 |
46 | **This step requires that you've set (preferably) two hidden TS variables with username and password with delegated rights to perform current task**
47 |
48 | 
49 |
50 | ```$TSEnv = New-Object -ComObject Microsoft.SMS.TSEnvironment -ErrorAction Continue```
51 |
52 | ```$DomainDN = "LDAP://CN=$($TSEnv.Value("FRXComputerName")),$($TSEnv.Value("FRXOU"))"```
53 | ```$Computer = New-Object -TypeName System.DirectoryServices.DirectoryEntry -ArgumentList``` ```$DomainDN,$($TSEnv.Value("FRXCustomUserName")),$($TSEnv.Value("FRXCustomUserInfo"))```
54 |
55 | ```foreach ( $MW in $($TSEnv.GetVariables() | where { $_ -like "FRXMW*" }) ) {```
56 | ``` $DomainDN = "LDAP://CN=$($TSEnv.Value($MW)),OU=MaintenanceGroups,DC=froxxen,DC=com"```
57 | ``` $MWGroup = New-Object -TypeName System.DirectoryServices.DirectoryEntry -ArgumentList $DomainDN,$($TSEnv.Value("FRXCustomUserName")),$($TSEnv.Value("FRXCustomUserInfo"))```
58 | ``` $MWGroup.Add($Computer.ADSPath)```
59 | ```}```
60 |
61 | ## Task Sequence step 6 - Configure NIC settings
62 |
63 | 
64 |
65 | ```$tsenv = New-Object -ComObject Microsoft.SMS.TSEnvironment -ErrorAction Continue```
66 | ```New-NetIPAddress –IPAddress $tsenv.Value("FRXIPAddress") -DefaultGateway $tsenv.Value("FRXGateway") -PrefixLength $tsenv.Value("FRXSubnet") -InterfaceIndex (Get-NetAdapter).InterfaceIndex```
67 |
68 | ```Set-DNSClientServerAddress –InterfaceIndex (Get-NetAdapter).InterfaceIndex –ServerAddresses $tsenv.Value("FRXDNSPrimary"),$tsenv.Value("FRXDNSSecondary")```
69 |
--------------------------------------------------------------------------------
/LAPS/Get-LAPSCompliance.ps1:
--------------------------------------------------------------------------------
1 | Function Write-Log {
2 | [CmdletBinding()]
3 | param (
4 | [Parameter(Position=0)]
5 | [string]$Message,
6 | [Parameter(Position=1)]
7 | [ValidateSet('INFO','WARN','ERROR')][string]$LogType = 'INFO',
8 | [Parameter(Position=2)]
9 | [ValidateSet('Yes','No')][string]$WritePrefix = 'Yes'
10 | )
11 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
12 | if($Message -eq $null){ $Message = "" }
13 | If ( $WritePrefix -eq "YES" ) {
14 | $LogEntry = "$LogType $CurrentDateTime - $Message"
15 | }
16 | Else {
17 | $LogEntry = "$Message"
18 | }
19 | Add-Content -Value $LogEntry -Path $LogFile -Encoding UTF8
20 | Write-Verbose $LogEntry
21 | }
22 | $LogFile = "C:\Temp\LAPSCompliance.log"
23 | $LookupDomains = @("domain1.local","domain2.local")
24 | $MaxPasswordAge = 30
25 |
26 | ForEach ( $LookupDomain in $LookupDomains ) {
27 | $DomainDN = $(Get-ADDomain -Server $LookupDomain).DistinguishedName
28 | $Servers = Get-ADComputer -filter "samAccountName -like ""*W7*"" -or samaccountName -like ""W0*"" -or samAccountName -like ""33-*"" -or samAccountName -like ""6*-*""" -Searchbase "OU=Servers,OU=Domain Computers,$DomainDN" -SearchScope Subtree -Properties Name,ms-Mcs-AdmPwd,ms-Mcs-AdmPwdExpirationTime -Server $LookupDomain | Select Name,ms-Mcs-AdmPwd,ms-Mcs-AdmPwdExpirationTime
29 | Write-Log $LookupDomain -WritePrefix No -Verbose
30 | Write-Log "Server`tPing`tPW Last set (days)" -WritePrefix No -Verbose
31 | ForEach ( $Server in $Servers ) {
32 | $ExpireInDays = $(NEW-TIMESPAN –Start $(Get-Date) –End $([DateTime]::FromFileTime($Server.'ms-Mcs-AdmPwdExpirationTime')).tostring("yyyy-MM-dd")).Days
33 | If ( $ExpireInDays -lt -$($MaxPasswordAge) ) {
34 | $Ping = $(Test-Connection "$($Server.Name).$LookupDomain" -Count 1 -Quiet)
35 | If ( $ExpireInDays -eq -152468 ) {
36 | Write-Log "$($Server.Name)`t$Ping`tNever" -WritePrefix No -Verbose
37 | }
38 | Else {
39 | Write-Log "$($Server.Name)`t$Ping`t$($ExpireInDays*-1)" -WritePrefix No -Verbose
40 | }
41 | }
42 | }
43 | Write-Log " " -WritePrefix No -Verbose
44 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Fredrik Bergman
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Misc Maintenance/Handle_Old_Computer_Objects.ps1:
--------------------------------------------------------------------------------
1 | # This scripts is supposed to run as a scheduled task with a service acccounts
2 | # Required permissions for this to work is that this account can Disable and Delete computer objects in Active Directory
3 | # and Delete resources from SCCM
4 |
5 | # Change to your environments site code for SCCM
6 | $SCCMSiteCode = ""
7 | # Change to path where logfiles should be saved
8 | $LogFile = "\Handle_Old_Computer_Objects.log"
9 | # Imports the module from the default path when the SCCM AdminConsole is installed
10 | Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
11 | cd "$($SCCMSiteCode):"
12 |
13 | Function Write-Log {
14 | [CmdletBinding()]
15 | param (
16 | [Parameter(Position=0)]
17 | [string]$Message,
18 | [Parameter(Position=1)]
19 | [ValidateSet('INFO','WARN','ERROR')][string]$LogType = 'INFO',
20 | [Parameter(Position=2)]
21 | [ValidateSet('Yes','No')][string]$WritePrefix = 'Yes'
22 | )
23 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
24 | if($Message -eq $null){ $Message = "" }
25 | if ( $WritePrefix -eq "YES" ) {
26 | $LogEntry = "$LogType $CurrentDateTime - $Message"
27 | }
28 | else {
29 | $LogEntry = "$Message"
30 | }
31 | Add-Content -Value $LogEntry -Path $LogFile -Encoding UTF8
32 | Write-Verbose $LogEntry
33 | }
34 |
35 | $NotifyDate = $(Get-Date).AddDays(-90)
36 | $WhenChangedDate = $(Get-Date).AddDays(-104)
37 | $AfterChangedDate = $(Get-Date).AddDays(-284)
38 | # Change to where your clients are located in Active Directory
39 | $SearchBase = 'OU=Clients,DC=domain,DC=local'
40 | [array]$NotifyComputerOwners = Get-ADComputer -filter 'enabled -eq $true' -SearchBase $SearchBase -SearchScope Subtree -Properties WhenChanged | Sort WhenChanged
41 | [array]$DisablingComputers = Get-ADComputer -filter 'WhenChanged -lt $WhenChangedDate -and enabled -eq $true' -SearchBase $SearchBase -SearchScope Subtree -Properties WhenChanged | Sort WhenChanged
42 | [array]$DeleteComputers = Get-ADComputer -filter 'WhenChanged -lt $AfterChangedDate -and enabled -eq $false' -SearchBase $SearchBase -SearchScope Subtree -Properties WhenChanged | Sort WhenChanged
43 |
44 | # Disable the computer objects in Active Directory and and deletes from SCCM that haven't been used for at least $WhenChangedDate days
45 | if ( $DisablingComputers.Count -gt 0 ) {
46 | foreach ( $Computer in $DisablingComputers ) {
47 | try {
48 | Remove-CMDevice -DeviceName $Computer.Name -Force
49 | Write-Log "Successfully removed $($Computer.Name) in SCCM"
50 | }
51 | catch {
52 | Write-Log "Failed to remove $($Computer.Name) in SCCM" -LogType ERROR
53 | }
54 | try {
55 | Disable-ADAccount $Computer.DistinguishedName
56 | Write-Log "Successfully disabled $($Computer.Name) in AD"
57 | }
58 | catch {
59 | Write-Log "Failed to disable $($Computer.Name) in AD" -LogType ERROR
60 | }
61 | }
62 | }
63 |
64 | # Change to where your user accounts are located to be able to retrieve the mail attribute
65 | $StandardUsers = Get-ADUser -Filter * -SearchBase "OU=StandardUsers,DC=domain,DC=local" -SearchScope OneLevel -Properties Mail, msDS-PrimaryComputer
66 | $MailBody = @"
67 | Hello!
68 |
69 | Your computer is about to be disabled within 14 days because it haven't been used for about three months.
70 |
71 | Contact servicedesk at to enable the computer if necessary.
72 |
73 | Best regards
74 |
75 | "@
76 |
77 | $SentList = @()
78 | # Creates a list of mails already sent and won't send to those again the next time this task runs
79 | $AlreadySent = Get-Content 'C:\Program Files\ScheduledTasks\Handle_Old_Computer_Objects\Templist'
80 | Remove-Item 'C:\Program Files\ScheduledTasks\Handle_Old_Computer_Objects\Templist' -Force
81 |
82 | # Deletes the computer object in Active Directory after being disabled for 180 days
83 | If ( $DeleteComputers.Count -gt 0 ) {
84 | foreach ( $Computer in $DeleteComputers ) {
85 | try {
86 | Remove-ADObject $Computer.DistinguishedName -Recursive -Confirm:$False
87 | Write-Log "Successfully deletd $($Computer.Name) in AD"
88 | }
89 | catch {
90 | Write-Log "Failed to delete $($Computer.Name) in AD" -LogType ERROR
91 | }
92 | }
93 | }
94 |
95 | # Sends a mail to people with computers that are about to be disabled, if such a person exists
96 | foreach ( $Computer in $NotifyComputerOwners ) {
97 | if ( $(New-Timespan –Start $NotifyDate –End $($Computer.WhenChanged)).Days -eq 0 ) {
98 | [array]$MailTo = $($StandardUsers | Where msDS-PrimaryComputer -match $Computer.Name).Mail
99 | if ( $MailTo.Count -gt 0 ) {
100 | foreach ( $MailTos in $MailTo ) {
101 | # Change to your organizations UPN
102 | if ( $MailTos -like '*@domain.local' ) {
103 | $MailSubject = "Your computer $($Computer.Name) will be disabled!"
104 | try {
105 | If ( $AlreadySent -notcontains $MailTos ) {
106 | #Send-MailMessage -Body $MailBody -From "noreply@arbetsformedlingen.se" -Encoding UTF8 -SmtpServer 'ismtp.wp.ams.se' -To $MailTos -Subject $MailSubject
107 | Write-Log "Successfully sent notification by mail to owner of $($Computer.Name)"
108 | $SentList += $MailTos
109 | }
110 | }
111 | catch {
112 | Write-Log "Failed to send notification by mail to owner of $($Computer.Name)" -LogType ERROR
113 | }
114 | }
115 | }
116 | }
117 | }
118 | }
119 | $SentList | Out-file 'C:\Program Files\ScheduledTasks\Handle_Old_Computer_Objects\Templist'
120 |
--------------------------------------------------------------------------------
/NTLM/Get-AuthenticatedNTLMSessions.ps1:
--------------------------------------------------------------------------------
1 | $DC = $(Get-ADDomainController).Name
2 | $DCs = $(Get-ADDomainController -Filter * | Select-Object name ).Name
3 |
4 | $DNSRoot = $( Get-ADDomain ).DNSRoot
5 | $LoggedOnToServers = @()
6 | $MaxEvents = 250000
7 |
8 | $FilterXML = ""
9 |
10 | cls
11 | Write-host ""
12 | Write-host "Analyzing NTLM V1 sessions connecting to DCs"
13 | Write-host ""
14 |
15 | ForEach ( $DC in $DCs ) {
16 | Write-host "- Analyzing events from $DC"
17 | $Events = Get-WinEvent –FilterXml $filterXml -ComputerName $DCs[0] -MaxEvents $MaxEvents
18 |
19 | ForEach ( $Event in $Events ) {
20 | $EventXML = $Null
21 | [xml]$EventXML= $Event.ToXml()
22 | ForEach ( $Dataevent in $eventXML.Event.EventData.Data ) {
23 | If ( $($DataEvent.Name) -eq "WorkstationName" ) {
24 | $ServerName = "$($DataEvent.'#text').$DNSRoot"
25 | If ( $LoggedOnToServers -notcontains $ServerName ) {
26 | $LoggedOnToServers += $ServerName
27 | }
28 | }
29 | }
30 | }
31 | }
32 | Write-host ""
33 | Write-Host "NTLM sessions from servers:"
34 | $LoggedOnToServers | Sort
35 | Write-host ""
--------------------------------------------------------------------------------
/New-CustomControl.ps1:
--------------------------------------------------------------------------------
1 | # Examples of one way to simplify the creation of Formobjects, no errorhandling nor ParameterSets added at this point though...
2 | # 2019-05-03 - Created by Fredrik Bergman
3 |
4 | Function New-CustomControl {
5 |
6 | param (
7 | [ValidateSet('Button','CheckBox','CheckedListBox','Form','Label','ListBox','RadioButton','TabControl','TabPage','TextBox')]
8 | [string]$Type,
9 | [string]$Name,
10 | [bool]$UseVisualStyleBackColor=$True,
11 | [int]$XSize,
12 | [int]$YSize,
13 | [int]$TabIndex,
14 | [string]$BackColor,
15 | [ValidateSet('Center','None','Stretch','Tile','Zoom')]
16 | [string]$BackgroundImageLayout,
17 | [ValidateSet('Fixed3D','FixedDialog','FixedSingle','FixedToolWindow','None','Sizable','SizableToolWindow')]
18 | [string]$FormBorderStyle,
19 | [string]$Text,
20 | [int]$Width,
21 | [int]$Height,
22 | [int]$YAxis,
23 | [int]$XAxis,
24 | [int]$MaxLength,
25 | [ValidateSet('CenterParent','CenterScreen','Manual','WindowsDefaultBounds','WindowsDefaultLocation')]
26 | [string]$StartPosition,
27 | [bool]$MaximizeBox=$True,
28 | [bool]$MinimizeBox=$True
29 |
30 | )
31 |
32 | $NewObject = New-Object System.Windows.Forms.$Type
33 | $NewObject.Location = New-Object system.drawing.point($XAxis,$YAxis)
34 |
35 | If ( $Type -eq 'Button' ) {
36 | $NewObject.Text = $Text
37 | $NewObject.Width = $Width
38 | If ( $Height -ne 0 ) {
39 | $NewObject.Height = $Height
40 | }
41 | }
42 |
43 | If ( $Type -eq 'CheckBox' ) {
44 | $NewObject.Text = $Text
45 | $NewObject.Width = $Width
46 | If ( $Height -ne 0 ) {
47 | $NewObject.Height = $Height
48 | }
49 | }
50 |
51 | If ( $Type -eq 'Form' ) {
52 | $NewObject.BackColor = $BackColor
53 | $NewObject.BackgroundImageLayout = $BackgroundImageLayout
54 | $NewObject.FormBorderStyle = $FormBorderStyle
55 | $NewObject.Text = $Text
56 | $NewObject.Width = $Width
57 | $NewObject.Height = $Height
58 | $NewObject.StartPosition = $StartPosition
59 | $NewObject.MaximizeBox = $MaximizeBox
60 | $NewObject.MinimizeBox = $MinimizeBox
61 | }
62 |
63 | If ( $Type -eq 'Label') {
64 | $NewObject.Text = $Text
65 | $NewObject.Width = $Width
66 | If ( $Height -ne 0 ) {
67 | $NewObject.Height = $Height
68 | }
69 | }
70 |
71 | If ( $Type -eq 'RadioButton') {
72 | $NewObject.Text = $Text
73 | $NewObject.Width = $Width
74 | If ( $Height -ne 0 ) {
75 | $NewObject.Height = $Height
76 | }
77 | }
78 |
79 | If ( $Type -eq 'TextBox') {
80 | $NewObject.Text = $Text
81 | $NewObject.MaxLength = $MaxLength
82 | $NewObject.Width = $Width
83 | If ( $Height -ne 0 ) {
84 | $NewObject.Height = $Height
85 | }
86 | }
87 |
88 | If ( $Type -eq 'TabControl' ) {
89 | }
90 |
91 | If ( $Type -eq 'TabPage' ) {
92 | $NewObject.Size = "$XSize, $YSize"
93 | $NewObject.TabIndex = $TabIndex
94 | $NewObject.Name = $Name
95 | $NewObject.Text = $Text
96 | $NewObject.UseVisualStyleBackColor = $UseVisualStyleBackColor
97 | }
98 |
99 | Return $NewObject
100 |
101 | }
102 |
103 | $Form = New-CustomControl -Type Form -Text 'Banal testform' -BackColor '#fffff2' -BackgroundImageLayout None -FormBorderStyle FixedDialog -Width 395 -Height 215 -StartPosition CenterScreen -MaximizeBox $False -MinimizeBox $True
104 | $TabControl = New-CustomControl -Type TabControl
105 | $tabNewUser = New-CustomControl -Type TabPage -XSize 390 -YSize 215 -Name 'tabNewUser' -Text 'Skapa en användare' -UseVisualStyleBackColor $True -TabIndex 0
106 | $tabServer = New-CustomControl -Type TabPage -XSize 390 -YSize 215 -Name 'tabServer' -Text 'Servrar' -UseVisualStyleBackColor $True -TabIndex 1
107 |
108 | $TabControl.Controls.Add($tabNewUser)
109 | $TabControl.Controls.Add($tabServer)
110 | $TabControl.Width = $Form.Width
111 | $TabControl.Height = $Form.Height
112 | $Form.controls.Add($TabControl)
113 |
114 | $lblUserName = New-CustomControl -Type Label -Text 'Användarnamn: ' -Width 100 -XAxis 25 -YAxis 10
115 | $tabNewUser.controls.Add($lblUserName)
116 |
117 | $txtUserName = New-CustomControl -Type TextBox -MaxLength 10 -Width 150 -XAxis 200 -YAxis 10
118 | $txtUserNameChange = { if ( $txtUserName.BackColor -eq '#ffffff' ) { $txtUserName.BackColor = '#eeeeee' } Else { $txtUserName.BackColor = '#ffffff' } }
119 | $txtUserName.Add_TextChanged($txtUserNameChange)
120 | $tabNewUser.controls.Add($txtUserName)
121 |
122 | $chkBox = New-CustomControl -Type CheckBox -Text 'Enabled' -Width 200 -XAxis 290 -YAxis 40
123 | $tabNewUser.controls.Add($chkBox)
124 |
125 | $lblUserName = New-CustomControl -Type Label -Text 'Access group: ' -Width 100 -XAxis 150 -YAxis 70
126 | $tabNewUser.controls.Add($lblUserName)
127 |
128 | $RbtnOK = New-CustomControl -Type RadioButton -Text 'Remote Desktop User' -Width 150 -XAxis 70 -YAxis 100
129 | $tabNewUser.controls.Add($RbtnOK)
130 | $RbtnOK2 = New-CustomControl -Type RadioButton -Text 'Administrator' -Width 150 -XAxis 220 -YAxis 100
131 | $tabNewUser.controls.Add($RbtnOK2)
132 |
133 | $btnOK = New-CustomControl -Type Button -Text 'Press me!' -Width 150 -XAxis 200 -YAxis 130
134 | $btnOK.Add_Click{ [System.Windows.MessageBox]::Show("$($txtUserName.Text)`n$($chkBox.Checked)`n$($RBtnOK.Checked)",'Titel',"Ok","Information") }
135 | $tabNewUser.controls.Add($btnOK)
136 |
137 | [void]$Form.ShowDialog()
138 |
--------------------------------------------------------------------------------
/PSsyslog/Get-PSSyslog.ps1:
--------------------------------------------------------------------------------
1 | $ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
2 | $data = get-content "$ScriptDir\*.log"
3 |
4 | $objTemplateObject = New-Object psobject
5 | $objTemplateObject | Add-Member -MemberType NoteProperty -Name Time -Value $null
6 | $objTemplateObject | Add-Member -MemberType NoteProperty -Name Source -Value $null
7 | $objTemplateObject | Add-Member -MemberType NoteProperty -Name Source_Port -Value $null
8 | $objTemplateObject | Add-Member -MemberType NoteProperty -Name Destination -Value $null
9 | $objTemplateObject | Add-Member -MemberType NoteProperty -Name Destination_Port -Value $null
10 |
11 | $objResult = @()
12 | $rows = $data.split("`r`n")
13 | foreach ( $row in $rows ) {
14 | if ( $row -ne "" ) {
15 | $objTemp = $objTemplateObject | Select-Object *
16 | $objTemp.Time = $row.split(" ")[2]
17 | foreach ( $item in $row.split(" ") ) {
18 | $matches.clear | out-null
19 | if ( $item -like 'SRC=*' ) {
20 | $item -match '(?<=SRC=).*' | out-null
21 | $objTemp.Source = $matches[0]
22 | }
23 | if ( $item -like 'SPT=*' ) {
24 | $item -match '(?<=SPT=).*' | out-null
25 | $objTemp.Source_Port = $matches[0]
26 | }
27 | if ( $item -like 'DST=*' ) {
28 | $item -match '(?<=DST=).*' | out-null
29 | $objTemp.Destination = $matches[0]
30 | }
31 | if ( $item -like 'DPT=*' ) {
32 | $item -match '(?<=DPT=).*' | out-null
33 | $objTemp.Destination_Port = $matches[0]
34 | }
35 | }
36 | $objResult += $objTemp
37 | }
38 | }
39 | $objResult | Sort-Object Time -Descending | Out-GridView -Wait
--------------------------------------------------------------------------------
/PSsyslog/Send-TCPUDP.ps1:
--------------------------------------------------------------------------------
1 | function Send-UDPMessage
2 | {
3 | param (
4 | [string] $EndPoint,
5 | [int] $Port,
6 | [string] $Message
7 | )
8 | $IP = [System.Net.Dns]::GetHostAddresses($EndPoint)
9 | $Address = [System.Net.IPAddress]::Parse($IP)
10 | $EndPoints = New-Object System.Net.IPEndPoint($Address, $Port)
11 | $Socket = New-Object System.Net.Sockets.UDPClient
12 | $EncodedText = [Text.Encoding]::ASCII.GetBytes($Message)
13 | $SendMessage = $Socket.Send($EncodedText, $EncodedText.Length, $EndPoints)
14 | $Socket.Close()
15 | }
16 |
17 | function Send-TCPMessage {
18 | param (
19 | [Parameter(Mandatory=$true, Position=0)]
20 | [ValidateNotNullOrEmpty()]
21 | [string]$EndPoint,
22 | [Parameter(Mandatory=$true, Position=1)]
23 | [int]$Port,
24 | [Parameter(Mandatory=$true, Position=2)]
25 | [string]$Message
26 | )
27 | process {
28 | $IP = [System.Net.Dns]::GetHostAddresses($EndPoint)
29 | $Address = [System.Net.IPAddress]::Parse($IP)
30 | $Socket = New-Object System.Net.Sockets.TCPClient($Address,$Port)
31 | $Stream = $Socket.GetStream()
32 | $Writer = New-Object System.IO.StreamWriter($Stream)
33 | $Message | % {
34 | $Writer.WriteLine($_)
35 | $Writer.Flush()
36 | }
37 | $Stream.Close()
38 | $Socket.Close()
39 | }
40 | }
41 |
42 | Send-UDPMessage -Port 5516 -EndPoint 192.168.2.192 -Message "My first UDP message !"
43 | #Send-TCPMessage -Port 5516 -Endpoint 192.168.2.192 -message "My first TCP message !"
44 |
--------------------------------------------------------------------------------
/PSsyslog/Start-PSSyslog.ps1:
--------------------------------------------------------------------------------
1 | $SysLogPort = 514
2 | $LogFolder = "C:\temp\PSsyslog\"
3 | $LogFile = "PSsyslog-$((Get-Date).ToString("yyyy-MM-dd")).log"
4 |
5 | $Socket = New-Object Net.Sockets.Socket([Net.Sockets.AddressFamily]::Internetwork,[Net.Sockets.SocketType]::Dgram,[Net.Sockets.ProtocolType]::Udp)
6 | $ServerIPEndPoint = New-Object Net.IPEndPoint([Net.IPAddress]::Any,$SysLogPort)
7 | try {
8 | $Socket.Bind($ServerIPEndPoint)
9 | }
10 | catch {
11 | write-output "Could not bind to socket"
12 | break
13 | }
14 |
15 | $SenderIPEndPoint = New-Object Net.IPEndPoint([Net.IPAddress]::Any, 0)
16 | $SenderEndPoint = [Net.EndPoint]$SenderIPEndPoint
17 |
18 | $Buffer = New-Object Byte[] 1024
19 |
20 | Write-Output " "
21 | Write-Output " PSSyslog receiving events."
22 | Write-Output " Close this window to shut down the socket"
23 |
24 | $ServerRunning = $True
25 | While ($ServerRunning -eq $True) {
26 | $BytesReceived = $Socket.ReceiveFrom($Buffer, [Ref]$SenderEndPoint)
27 | $Message = $Buffer[0..$($BytesReceived - 1)]
28 | $MessageString = "$([Text.Encoding]::ASCII.GetString($Message))"
29 | if ( $MessageString -match $MsgContains ) {
30 | $MessageString | Out-File $LogFolder\$LogFile -Encoding utf8 -Append
31 | }
32 | }
--------------------------------------------------------------------------------
/PSsyslog/img/PSSyslog.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/froxxon/Powershell/a32b744280535cc409c93148b402854b0a99da13/PSsyslog/img/PSSyslog.gif
--------------------------------------------------------------------------------
/PSsyslog/readme.MD:
--------------------------------------------------------------------------------
1 | # PSSyslog
2 |
3 | This is a quick and dirty solution to get syslogs to your computer through Powershell, combined some own additions with already working scripts from the web.
4 |
5 | **Start-PSSyslog.ps1** is used to start the actual socket to be able to receive the syslogs, port number, log file location etc. should be modified in this script.
6 |
7 | **Get-PSSyslog.ps1** gets the data from alla the log-files in the script directory, using Out-gridview to display result, should be modified for miscellanious values. Another alternative could be to use Notepad++ or CMTrace for example.
8 |
9 | **Send-TCPUDP.ps1** is used to send a test message by TCP or UDP to a receiving syslog server, the on started with '*Start-PSSyslog*' for example. ;)
10 |
11 | 
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Powershell
2 | A repository containing my powershellscripts for different system, from Collection-creation in SCCM, analyzing of a Windows Firewall log file, opening C$ on a Windows 10 client remotely to reading RADIUS logs etc.
3 |
4 | The two largest *"serious"* script/modules for my part is so far the ones for AD-delegation as well as 2Pint Softwares Stifler-PS module.
5 |
--------------------------------------------------------------------------------
/SCCM/Add-SiteSystemServer_To_BoundaryGroup.ps1:
--------------------------------------------------------------------------------
1 | Clear-Host
2 | Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
3 | cd a01:
4 | $Subnets = @("Bound01")
5 | $SiteSystemServer = @("server01.domain.local","server02.domain.local")
6 |
7 | ForEach ( $Subnet in $Subnets ) {
8 | Try {
9 | Set-CMBoundaryGroup -Name "Production - Central content - $Subnet" -AddSiteSystemServerName $SiteSystemServer
10 | Write-host "Added servers to boundary group for subnet $Subnet"
11 | }
12 | Catch {
13 | Write-host "Failed to add servers to boundary group for subnet $Subnet"
14 | }
15 | }
--------------------------------------------------------------------------------
/SCCM/Create-MaintenanceCollection.ps1:
--------------------------------------------------------------------------------
1 | Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
2 | cd a01:
3 | Write-host ""
4 |
5 | $Today = Get-Date -UFormat %m/%d/%Y
6 |
7 | Function RefreshDayOfWeekMinusOne($Day) {
8 | If ( $Day -eq "TUESDAY" ) { $RefreshDayOfWeek = "MONDAY" }
9 | If ( $Day -eq "WEDNESDAY" ) { $RefreshDayOfWeek = "TUESDAY" }
10 | If ( $Day -eq "THURSDAY" ) { $RefreshDayOfWeek = "WEDNESDAY" }
11 | If ( $Day -eq "FRIDAY" ) { $RefreshDayOfWeek = "THURSDAY" }
12 | If ( $Day -eq "SATURDAY" ) { $RefreshDayOfWeek = "FRIDAY" }
13 | If ( $Day -eq "SUNDAY" ) { $RefreshDayOfWeek = "SATURDAY" }
14 | If ( $Day -eq "MONDAY" ) { $RefreshDayOfWeek = "SUNDAY" }
15 | Return $RefreshDayOfWeek
16 | }
17 |
18 | Function CreateMaintenanceCollection ($Name) {
19 | If ( $Name.SubString(7,3) -like "Mon" ) { $Day = "måndagar" ; $DayOfWeek = "MONDAY" }
20 | If ( $Name.SubString(7,3) -like "Tue" ) { $Day = "tisdagar" ; $DayOfWeek = "TUESDAY" }
21 | If ( $Name.SubString(7,3) -like "Wed" ) { $Day = "onsdagar" ; $DayOfWeek = "WEDNESDAY" }
22 | If ( $Name.SubString(7,3) -like "Thu" ) { $Day = "torsdagar" ; $DayOfWeek = "THURSDAY" }
23 | If ( $Name.SubString(7,3) -like "Fri" ) { $Day = "fredagar" ; $DayOfWeek = "FRIDAY" }
24 | If ( $Name.SubString(7,3) -like "Sat" ) { $Day = "lördagar" ; $DayOfWeek = "SATURDAY" }
25 | If ( $Name.SubString(7,3) -like "Sun" ) { $Day = "söndagar" ; $DayOfWeek = "SUNDAY" }
26 | $StartHour = $Name.SubString($Name.IndexOf("kl ")+3,2)
27 | $LastHour = $Name.SubString($Name.IndexOf("-")+1,2)
28 | $Description = "Servers with maintenance windows from $Day $($StartHour).00 to $($LastHour).00"
29 |
30 | $RefreshDayOfWeek = $DayOfWeek
31 | $RefreshStartHour = $StartHour
32 | If ( $RefreshStartHour -eq "00" -OR $RefreshStartHour -eq "01" -OR $RefreshStartHour -eq "02" -OR $RefreshStartHour -eq "03" -OR $RefreshStartHour -eq "04" ) {
33 | If ( $RefreshStartHour -eq "00" ) {
34 | $RefreshStartHour = "19"
35 | $RefreshDayOfWeek = RefreshDayOfWeekMinusOne -Day $DayOfWeek
36 | }
37 | If ( $RefreshStartHour -eq "01" ) {
38 | $RefreshStartHour = "20"
39 | $RefreshDayOfWeek = RefreshDayOfWeekMinusOne -Day $DayOfWeek
40 | }
41 | If ( $RefreshStartHour -eq "02" ) {
42 | $RefreshStartHour = "21"
43 | $RefreshDayOfWeek = RefreshDayOfWeekMinusOne -Day $DayOfWeek
44 | }
45 | If ( $RefreshStartHour -eq "03" ) {
46 | $RefreshStartHour = "22"
47 | $RefreshDayOfWeek = RefreshDayOfWeekMinusOne -Day $DayOfWeek
48 | }
49 | If ( $RefreshStartHour -eq "04" ) {
50 | $RefreshStartHour = "23"
51 | $RefreshDayOfWeek = RefreshDayOfWeekMinusOne -Day $DayOfWeek
52 | }
53 | }
54 | Else { $RefreshStartHour = "$($RefreshStartHour-5)" }
55 |
56 | Write-host "Creating device collection ""$Name"" with dependencies:"
57 | Try {
58 | $RefreshSchedule = New-CMSchedule -DayOfWeek $RefreshDayOfWeek -Start "$(Get-Date -UFormat %m/%d/%Y) $($RefreshStartHour):00" -RecurCount 1
59 | New-CMDeviceCollection -Name $Name -LimitingCollectionName "SHD.AST#All Managed Windows Servers" -RefreshType 2 -RefreshSchedule $RefreshSchedule -Comment $Description | Out-null
60 | Write-host " - Device collection successfully created"
61 | Try {
62 | Add-CMUserCollectionQueryMembershipRule -CollectionName $Name -RuleName "Maintenance" -QueryExpression "select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.SystemGroupName like ""%\\MAINTENANCE $($DayOfWeek.Substring(0,3)) KL $($StartHour).00-$($LastHour).00""" | Out-null
63 | Write-host " - Query successfully created"
64 | Try {
65 | $MaintenanceSchedule = New-CMSchedule -DayOfWeek $DayOfWeek -Start "$(Get-Date -UFormat %m/%d/%Y) $($StartHour):00" -End "$(Get-Date -UFormat %m/%d/%Y) $($LastHour):00" -RecurCount 1
66 | New-CMMaintenanceWindow -CollectionName $Name -MaintenanceWindowName "Maintenance" -ApplyTo SoftwareUpdatesOnly -Schedule $MaintenanceSchedule | Out-null
67 | Write-host " - Maintenance Window successfully created"
68 | }
69 | Catch { Write-host " - Failed to create Maintenance window - Aborting" }
70 | }
71 | Catch { Write-host " - Failed to create the Query - Aborting" }
72 | }
73 | Catch { Write-host " - Failed to create the collection - Aborting" }
74 | Write-host ""
75 | }
76 |
77 | ### !!! Create an Excluded-collection manually !!! ###
78 |
79 | #Monday
80 | CreateMaintenanceCollection -Name "SHD.MW#Mon kl 21.00-22.00"
81 | CreateMaintenanceCollection -Name "SHD.MW#Mon kl 22.00-23.00"
82 | CreateMaintenanceCollection -Name "SHD.MW#Mon kl 23.00-00.00"
83 | #Tuesday
84 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 07.00-08.00"
85 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 08.00-09.00"
86 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 09.00-10.00"
87 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 10.00-11.00"
88 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 11.00-12.00"
89 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 00.00-01.00"
90 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 01.00-02.00"
91 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 02.00-03.00"
92 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 03.00-04.00"
93 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 04.00-05.00"
94 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 05.00-06.00"
95 | CreateMaintenanceCollection -Name "SHD.MW#Tue kl 06.00-07.00"
96 | #Wednesday
97 | CreateMaintenanceCollection -Name "SHD.MW#Wed kl 21.00-22.00"
98 | CreateMaintenanceCollection -Name "SHD.MW#Wed kl 22.00-23.00"
99 | CreateMaintenanceCollection -Name "SHD.MW#Wed kl 23.00-00.00"
100 | CreateMaintenanceCollection -Name "SHD.MW#Wed kl 00.00-01.00"
101 | CreateMaintenanceCollection -Name "SHD.MW#Wed kl 01.00-02.00"
102 | CreateMaintenanceCollection -Name "SHD.MW#Wed kl 02.00-03.00"
103 | CreateMaintenanceCollection -Name "SHD.MW#Wed kl 03.00-04.00"
104 | CreateMaintenanceCollection -Name "SHD.MW#Wed kl 04.00-05.00"
105 | CreateMaintenanceCollection -Name "SHD.MW#Wed kl 05.00-06.00"
106 | CreateMaintenanceCollection -Name "SHD.MW#Wed kl 06.00-07.00"
107 | #Thursday
108 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 07.00-08.00"
109 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 08.00-09.00"
110 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 09.00-10.00"
111 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 10.00-11.00"
112 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 11.00-12.00"
113 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 21.00-22.00"
114 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 22.00-23.00"
115 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 23.00-00.00"
116 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 00.00-01.00"
117 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 01.00-02.00"
118 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 02.00-03.00"
119 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 03.00-04.00"
120 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 04.00-05.00"
121 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 05.00-06.00"
122 | CreateMaintenanceCollection -Name "SHD.MW#Thu kl 06.00-07.00"
123 | #Friday
124 | CreateMaintenanceCollection -Name "SHD.MW#Fri kl 00.00-01.00"
125 | CreateMaintenanceCollection -Name "SHD.MW#Fri kl 01.00-02.00"
126 | CreateMaintenanceCollection -Name "SHD.MW#Fri kl 02.00-03.00"
127 | CreateMaintenanceCollection -Name "SHD.MW#Fri kl 03.00-04.00"
128 | CreateMaintenanceCollection -Name "SHD.MW#Fri kl 04.00-05.00"
129 | CreateMaintenanceCollection -Name "SHD.MW#Fri kl 05.00-06.00"
130 | CreateMaintenanceCollection -Name "SHD.MW#Fri kl 06.00-07.00"
131 | #Saturday
132 | CreateMaintenanceCollection -Name "SHD.MW#Sat kl 21.00-22.00"
133 | CreateMaintenanceCollection -Name "SHD.MW#Sat kl 22.00-23.00"
134 | CreateMaintenanceCollection -Name "SHD.MW#Sat kl 23.00-00.00"
135 | #Sunday
136 | CreateMaintenanceCollection -Name "SHD.MW#Sun kl 00.00-01.00"
137 | CreateMaintenanceCollection -Name "SHD.MW#Sun kl 01.00-02.00"
138 | CreateMaintenanceCollection -Name "SHD.MW#Sun kl 02.00-03.00"
139 | CreateMaintenanceCollection -Name "SHD.MW#Sun kl 03.00-04.00"
140 | CreateMaintenanceCollection -Name "SHD.MW#Sun kl 04.00-05.00"
141 | CreateMaintenanceCollection -Name "SHD.MW#Sun kl 05.00-06.00"
142 | CreateMaintenanceCollection -Name "SHD.MW#Sun kl 06.00-07.00"
--------------------------------------------------------------------------------
/SCCM/Create-MaintenanceGroup.ps1:
--------------------------------------------------------------------------------
1 | Function CreateMaintenanceGroup ($Day,$StartHour,$LastHour,$Domain) {
2 |
3 | $DomainDN = $(Get-ADDomain -Server $Domain).DistinguishedName
4 |
5 | If ( $Day -eq "Mon" ) { $DayName = "måndagar" }
6 | If ( $Day -eq "Tue" ) { $DayName = "tisdagar" }
7 | If ( $Day -eq "Wed" ) { $DayName = "onsdagar" }
8 | If ( $Day -eq "Thu" ) { $DayName = "torsdagar" }
9 | If ( $Day -eq "Fri" ) { $DayName = "fredagar" }
10 | If ( $Day -eq "Sat" ) { $DayName = "lördagar" }
11 | If ( $Day -eq "Sun" ) { $DayName = "söndagar" }
12 |
13 | $GroupName = "Maintenance $Day kl $($StartHour).00-$($LastHour).00"
14 | $Description = "Servers with maintenance windows from $DayName $($StartHour).00 to $($LastHour).00"
15 |
16 | Try {
17 | New-ADGroup $GroupName -Description $Description -DisplayName $GroupName -GroupCategory Security -GroupScope Global -Path "OU=MaintenanceGroups,$DomainDN" -Server $Domain
18 | Write-host "Created the group: ""$GroupName"" in $Domain"
19 | }
20 | Catch {
21 | Write-host "Failed to create the group: ""$GroupName"" in $Domain"
22 | }
23 | }
24 |
25 | # Domain
26 | CreateMaintenanceGroup -Day "Wed" -StartHour "21" -LastHour "22" -Domain "domain.local"
27 | CreateMaintenanceGroup -Day "Wed" -StartHour "22" -LastHour "23" -Domain "domain.local"
28 | CreateMaintenanceGroup -Day "Wed" -StartHour "23" -LastHour "00" -Domain "domain.local"
--------------------------------------------------------------------------------
/SCCM/Create-SoftwareUpdateDeployments.ps1:
--------------------------------------------------------------------------------
1 | Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
2 | cd a01:
3 |
4 | Function CreateDeployment ( $SoftwareUpdateGroupName,$Collection, $DeploymentType ) {
5 | Write-host "Creating deployment for SUG ""$SoftwareUpdateGroupName"" to the collection ""$Collection"""
6 | Try {
7 | New-CMSoftwareUpdateDeployment -SoftwareUpdateGroupName $SoftwareUpdateGroupName -DeploymentType $DeploymentType -CollectionName $Collection -ProtectedType RemoteDistributionPoint -AvailableDateTime "$(Get-Date -format yyyy/MM/dd) 00:00AM" -DeadlineDateTime "$(Get-Date -format yyyy/MM/dd) 00:00AM" | out-null
8 | Write-host "Created the deployment successfully"
9 | }
10 | Catch {
11 | Write-host "Failed to create deployment"
12 | }
13 | Write-host ""
14 | }
15 |
16 | $TargetCollection = "SHD.SU#Server group - General servers - Domain"
17 | CreateDeployment -SoftwareUpdateGroupName "SHD - ADR - Windows Server 2018-07-11 00:00:00" -Collection $TargetCollection -DeploymentType Required
18 | CreateDeployment -SoftwareUpdateGroupName "SHD - ADR - Windows Server 2018-08-15 00:00:00" -Collection $TargetCollection -DeploymentType Required
19 | CreateDeployment -SoftwareUpdateGroupName "SHD - ADR - Windows Server 2018-09-12 00:00:00" -Collection $TargetCollection -DeploymentType Required
--------------------------------------------------------------------------------
/SCCM/Get-CMBoundariesWithoutDP.ps1:
--------------------------------------------------------------------------------
1 | Function Write-Log {
2 | [CmdletBinding()]
3 | param (
4 | [Parameter(Position=0)]
5 | [string]$Message,
6 | [Parameter(Position=1)]
7 | [ValidateSet('INFO','WARN','ERROR')][string]$LogType = 'INFO',
8 | [Parameter(Position=2)]
9 | [ValidateSet('Yes','No')][string]$WritePrefix = 'Yes'
10 | )
11 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
12 | if($Message -eq $null){ $Message = "" }
13 | If ( $WritePrefix -eq "YES" ) {
14 | $LogEntry = "$LogType $CurrentDateTime - $Message"
15 | }
16 | Else {
17 | $LogEntry = "$Message"
18 | }
19 | Add-Content -Value $LogEntry -Path $LogFile -Encoding UTF8
20 | Write-Verbose $LogEntry
21 | }
22 |
23 | Clear-Host
24 | Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
25 | cd a01:
26 |
27 | $LogFile = "C:\Temp\Get-CMBoundariesWithoutDP.log"
28 |
29 | $BoundaryFilter = "Local Content" # <- Check those Boundaries (filter)
30 | $DHCPServer = "" # <- Put the DHCP server here
31 | $DPs = @("") # <- Put general DPs here
32 | $ReplaceSuffixes = @(".domain.local")
33 | $OverallSiteSystems = @("") # <- Put MPs and general servers here
34 | $FallBackDP = "" # <. Put Fallback DP here
35 | $MissingDHCPScope = @()
36 | $MissingDPs = @()
37 | $HasStandardDP = @()
38 | $HasFallbackDP = @()
39 | $Counter = 1
40 |
41 | $BoundaryGroups = $(Get-CMBoundaryGroup -Name "*$BoundaryFilter*" ).Name | Sort
42 | If ( $DHCPScopes -eq $Null ) { $DHCPScopes = Get-DhcpServerv4Scope -ComputerName $DHCPServer | Sort }
43 |
44 | Write-Log "Counter;Boundary Group;DPType,DHCPLeases" -WritePrefix No
45 |
46 | ForEach ( $BoundaryGroup in $BoundaryGroups ) {
47 |
48 | $ScopeName = ""
49 | $ScopeClients = 0
50 | $ScopeID = ""
51 |
52 | $ScopeName = Try { $BoundaryGroup.Split("-",4)[3].Trim() } Catch {}
53 | If ( $DHCPScopes.Name -notcontains $ScopeName ) { $MissingDHCPScope += $ScopeName }
54 | Else {
55 | $ScopeID = $($DHCPScopes | Where Name -eq $ScopeName).ScopeId.IPAddressToString
56 | $ScopeClients = @(Get-DHCPServerv4Lease -ComputerName $DHCPServer -ScopeId $ScopeID | Where HostName -Like '99-*').Count
57 | }
58 | [System.Collections.ArrayList]$SiteSystems =Try { $(Get-CMBoundary -BoundaryGroupName $BoundaryGroup).SiteSystems.ToUpper() } Catch { Write-Log "Something happened while checking $BoundaryGroup" -WritePrefix No -LogType ERROR}
59 | ForEach ( $ReplaceSuffix in $ReplaceSuffixes ) { $SiteSystems = $SiteSystems -replace $ReplaceSuffix,"" }
60 | $TempString = "$Counter / $($BoundaryGroups.Count);$BoundaryGroup"
61 | ForEach ( $System in $OverallSiteSystems ) { Try { $SiteSystems.Remove($System) } Catch {}}
62 | If ( $SiteSystems -contains $FallBackDP ) { $HasFallbackDP += "$BoundaryGroup" }
63 | if ( $DPs -notcontains $SiteSystems -and $((@($SiteSystems) -like 'LDP*').Count) -eq 0) {
64 | $MissingDPs += $BoundaryGroup
65 | Write-Log "$TempString;Missing;0" -WritePrefix No
66 | }
67 | Else {
68 | If ( $SiteSystems -contains $FallBackDP ) { Write-Log "$TempString;Fallback;$ScopeClients" -WritePrefix No }
69 | Else {
70 | $HasStandardDP += $BoundaryGroup
71 | Write-Log "$TempString;Standard;$ScopeClients" -WritePrefix No
72 | }
73 | }
74 | $Counter++
75 | }
76 | Write-Log " " -WritePrefix No
77 | Write-Log "Has standard DP : $($HasStandardDP.Count)" -WritePrefix No
78 | Write-Log "Has Fallback DP : $($HasFallbackDP.Count)" -WritePrefix No
79 | Write-Log "Missing DP : $($MissingDPs.Count)" -WritePrefix No
80 | Write-Log "Missing DHCP Scope : $($MissingDHCPScope.Count)" -WritePrefix No
81 | Write-Log " " -WritePrefix No
82 |
83 | #If ( $HasStandardDP.Count -gt 0 ) { Write-Log "List of boundary group(s) with Standard DP:" -WritePrefix No ; Write-Log $($HasStandardDP -Join "`n") -WritePrefix No ; Write-Log " " -WritePrefix No}
84 | If ( $HasFallbackDP.Count -gt 0 ) { Write-Log "List of boundary group(s) with Fallback DP:" -WritePrefix No ; Write-Log $($HasFallbackDP -Join "`n") -WritePrefix No ; Write-Log " " -WritePrefix No}
85 | If ( $MissingDPs.Count -gt 0 ) { Write-Log "List of boundary group(s) missing DP:" -WritePrefix No ; Write-Log $($MissingDPs -Join "`n") -WritePrefix No ; Write-Log " " -WritePrefix No}
86 | If ( $MissingDHCPScope.Count -gt 0 ) { Write-Log "List of missing DHCP-scope(s):" -WritePrefix No ; Write-Log $($MissingDHCPScope -Join "`n") -WritePrefix No ; Write-Log " " -WritePrefix No}
87 |
--------------------------------------------------------------------------------
/SCCM/Get-MaintenanceWindows.ps1:
--------------------------------------------------------------------------------
1 | $DomainDN = $(Get-ADDomain).DistinguishedName
2 | $Servers = Get-ADComputer -filter * -SearchBase "OU=Servers,$DomainDN" -SearchScope Subtree
3 | Write-host "Found $($Servers.Count) servers"
4 | $TotalCount = $Servers.Count
5 | $Counter = 1
6 | $ServerList = @()
7 | $ServerList += "Server`tStartHour`tLastHour"
8 | ForEach ( $Server in $Servers ) {
9 | Write-host "Checking $Counter \ $TotalCount"
10 | $Count
11 | $MW = $(Get-ADPrincipalGroupMembership $Server ).Name | Where { $_ -like "*Maintenance*" } | sort
12 | If ( $MW -notlike "*Maintenance Excluded*" ) {
13 | $StartHour = $MW[0] -replace $($MW[0].Substring(0,$($MW[0].IndexOf("kl "))+3)),""
14 | $StartHour = $StartHour -replace $($StartHour.Substring($Starthour.IndexOf("-"),6)),""
15 | $LastHour = $MW[-1] -replace $($MW[-1].Substring(0,$($MW[-1].IndexOf("-"))+1)),""
16 | $ServerList += "$($Server.Name)`t$StartHour`t$LastHour"
17 | }
18 | $Counter++
19 | }
20 |
21 | $ServerList > c:\temp\Servers_MW_WP.log
22 |
23 | $ServerList -replace "`t",";"
--------------------------------------------------------------------------------
/SCCM/QuickScanScheduler/QuickScanScheduler.ps1:
--------------------------------------------------------------------------------
1 | Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
2 | cd a01:
3 |
4 | Function Write-Log ($LogInput) {
5 | If ($LogInput -eq $Null) {
6 | " " | Out-File -File $LogFile -Append
7 | }
8 | Else {
9 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
10 | $CurrentDateTime + “ - " + $LogInput | Out-File -File $LogFile -Append
11 | }
12 | }
13 |
14 | $SiteServer = "" # <- Enter Site Server
15 | $SiteCode = "" # <- Enter Site Code
16 | $Date = Get-Date -format "yyyy-MM-dd"
17 | $LogFile = "C:\Temp\QuickScanScheduler\QuickScanScheduler $Date.log"
18 | $CollectionName = "SHD.EPSS#No QuickScan Collection"
19 | $NoQuickScanCollectionName = "SHD.EPSS#No QuickScan Collection"
20 | $StandardCollection = $False
21 |
22 | $AddedToCollectionCount = 0
23 | $AddedEarlierCount = 0
24 |
25 | Write-Log
26 | Write-Log "--- Start of log ---"
27 | Write-Log
28 |
29 | $QuickScanCollections = Get-WMIObject -ComputerName $siteServer -NameSpace "ROOT\SMS\site_$SiteCode" -Class SMS_Collection | where {$_.Name -like "*SHD.EPSS#Servers - QuickScan - *"}
30 | Write-Log "Found QuickScan-collections:"
31 |
32 | $Counter = 0 ; $IndexCounter = 0 ; $LowestCount = 0
33 |
34 | ForEach ($QuickScanCollection in $QuickScanCollections) {
35 | $QuickScanCollectionCount = Get-WmiObject -ComputerName $SiteServer -Namespace "ROOT\SMS\site_$SiteCode" -Query "SELECT * FROM SMS_FullCollectionMembership WHERE CollectionID='$($QuickScanCollection.CollectionID)' order by name" | select Name
36 | If ($IndexCounter -eq 0) {$LowestCount = $QuickScanCollectionCount.Count}
37 | If ($QuickScanCollectionCount.Count -lt $LowestCount) {$Counter = $IndexCounter}
38 | If ($QuickScanCollectionCount.Count -lt $LowestCount) {$LowestCount = $QuickScanCollectionCount.Count}
39 | $IndexCounter++
40 | Write-Log $QuickScanCollection.Name
41 | }
42 |
43 | Write-Log
44 |
45 | If ( $CollectionName -eq $NoQuickScanCollectionName ) {
46 | Write-Log '$CollectionName and $NoQuickScanCollectionName is the same, skip to check for members in $NoQuickScanCollectionName'
47 | Write-Log
48 | $StandardCollection = $True
49 | $AlreadyInQuickScanCollection = $False
50 | }
51 |
52 | $Temp = 'The variable $StandardCollection is: ' + $StandardCollection
53 | Write-Log $Temp
54 |
55 | Write-Log
56 | Write-Log "This collection contains the least amount of members and will be used first: "
57 | Write-Log $QuickScanCollections[$Counter].Name
58 | Write-Log
59 |
60 | If ( $StandardCollection -eq $False ) {
61 | Write-Log "Gets the objects of collection: $NoQuickScanCollectionName"
62 | $NoQuickScanCollectionMembers = Get-WmiObject -ComputerName $SiteServer -Namespace "ROOT\SMS\site_$SiteCode" -Query "SELECT * FROM SMS_FullCollectionMembership WHERE CollectionID='A0100171' order by name" | select name
63 | $Temp = "Object count: " + $NoQuickScanCollectionMembers.Count
64 | Write-Log $Temp
65 | Write-Log
66 | }
67 |
68 | Write-Log "Gets the objects of collection: $CollectionName"
69 | $GetCollectionID = get-wmiobject -ComputerName $siteServer -NameSpace "ROOT\SMS\site_$SiteCode" -Class SMS_Collection | where {$_.Name -like "$CollectionName*"} | select CollectionID
70 | $CollectionMembers = Get-WmiObject -ComputerName $SiteServer -Namespace "ROOT\SMS\site_$SiteCode" -Query "SELECT * FROM SMS_FullCollectionMembership WHERE CollectionID='$($GetCollectionID.CollectionID)' order by name" | select Name, ResourceID
71 | $Temp = "Object count: " + $CollectionMembers.Count
72 | Write-Log $Temp
73 | Write-Log
74 |
75 | remove-variable QuickScanCollectionsMembers
76 | $GetCollectionIDs = get-wmiobject -ComputerName $siteServer -NameSpace "ROOT\SMS\site_$SiteCode" -Class SMS_Collection | where {$_.Name -like "SHD.EPSS#Servers - QuickScan - *"} | select CollectionID
77 | ForEach ($QuickScanCollectionID in $GetCollectionIDs) {
78 | $QuickScanCollectionsMembers += (Get-WmiObject -ComputerName $SiteServer -Namespace "ROOT\SMS\site_$SiteCode" -Query "SELECT * FROM SMS_FullCollectionMembership WHERE CollectionID='$($QuickScanCollectionID.CollectionID)' order by name" | select Name)
79 | }
80 |
81 | Write-Log "Added servers:"
82 | ForEach ($Computer in $CollectionMembers) {
83 | $AlreadyInQuickScanCollection = $False
84 | If ( $StandardCollection -eq $False ) {
85 | If ($QuickScanCollectionsMembers.Name -contains $Computer.Name) {
86 | $AlreadyInQuickScanCollection = $True
87 | }
88 | Else {
89 | $AlreadyInQuickScanCollection = $False
90 | }
91 | }
92 | If ( $AlreadyInQuickScanCollection -eq $False ) {
93 | Add-CMDeviceCollectionDirectMembershipRule -CollectionName $QuickScanCollections[$Counter].Name -ResourceID $Computer.ResourceID
94 | $Temp = $Computer.Name + " is added to the collection: " + $QuickScanCollections[$Counter].Name
95 | Write-Log $Temp
96 | $AddedToCollectionCount++
97 | }
98 | Else {
99 | $AddedEarlierCount++
100 | Continue
101 | }
102 | If ($Counter -lt $QuickScanCollections.Count) {$Counter++}
103 | If ($Counter -eq $QuickScanCollections.Count) {$Counter = 0}
104 | }
105 |
106 | Write-Log
107 | Write-Log "Count of servers added to QuickScan collections: $AddedToCollectionCount"
108 | Write-Log "Count of servers added earlier to QuickScan collections: $AddedEarlierCount"
109 | Write-Log
110 | Write-Log "--- End of log ---"
111 | Write-Log
--------------------------------------------------------------------------------
/SCCM/RefreshServerComplianceState/Computers.txt:
--------------------------------------------------------------------------------
1 | W7700585
2 | W7800241
--------------------------------------------------------------------------------
/SCCM/RefreshServerComplianceState/RefreshServerComplianceState - Multiple machines.ps1:
--------------------------------------------------------------------------------
1 | $Computers = get-content ".\Computers.txt"
2 |
3 | ForEach ($Computer in $Computers) {
4 | If(Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
5 | Write-host "Trigger RefreshCompliance on $Computer"
6 | Invoke-Command -ComputerName $Computer -ScriptBlock {
7 | $SCCMUpdatesStore = New-Object -ComObject Microsoft.CCM.UpdatesStore ; $SCCMUpdatesStore.RefreshServerComplianceState()
8 | }
9 | }
10 | }
--------------------------------------------------------------------------------
/SCCM/RefreshServerComplianceState/RefreshServerComplianceState - Single machine.ps1:
--------------------------------------------------------------------------------
1 | $Computer = "server01"
2 |
3 | Invoke-Command -ComputerName $Computer -ScriptBlock {
4 | $SCCMUpdatesStore = New-Object -ComObject Microsoft.CCM.UpdatesStore ; $SCCMUpdatesStore.RefreshServerComplianceState() ; New-EventLog -LogName Application -Source SyncStateScript -ErrorAction SilentlyContinue ; Write-EventLog -LogName Application -Source SyncStateScript -EventId 555 -EntryType Information -Message "Sync State ran successfully"
5 | }
--------------------------------------------------------------------------------
/SCCM/Remove-DuplicateUsersFromCMDevice.ps1:
--------------------------------------------------------------------------------
1 | Function Write-Log {
2 | Param ([string]$logstring)
3 | $Timestamp = Get-Date
4 | $logstring = "$Timestamp - $logstring"
5 | Add-content $Logfile -value $logstring
6 | }
7 |
8 | Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1" ; cd a01:
9 |
10 | $Computers = @("Computer1","Computer2","Computer3")
11 | $Domain = "domain.local"
12 | $username = "$Domain\ServiceAccountUser" # <- Put the name for the service account here
13 | $Password = "" # <- Put the password for the service account here
14 | $DomainDN = $(Get-ADDomain).DistinguishedName
15 | $domaininfo = new-object DirectoryServices.DirectoryEntry("LDAP://$Domain/ou=Clients,$DomainDN",$UserName,$Password)
16 | $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
17 | $objSearcher.SearchRoot = $domaininfo
18 |
19 | ForEach ( $Computer in $Computers ) {
20 | $LogFile = "C:\temp\Remove-DuplicateUsersFromCMDevice\Logs\$Computer.log"
21 | $objSearcher.Filter = "(&(objectCategory=computer)(cn=$Computer))"
22 | $objSearcher.PropertiesToLoad.Add("primaryuser") | out-null
23 | $PrimaryUser = $objSearcher.FindAll()
24 | $PrimaryUser = $PrimaryUser.Properties.afprimaryuser
25 | Write-Log "The primary user for $Computer is $PrimaryUser"
26 |
27 | $Users = $(Get-CMUserDeviceAffinity -DeviceName $Computer).UniqueUserName
28 | ForEach ( $User in $Users ) {
29 | If ( $User -ne "$Domain\$PrimaryUser" -or $User -contains "local_users" ) {
30 | If ( $PrimaryUser -ne $Null ) {
31 | Remove-CMDeviceAffinityFromUser -UserName $User -DeviceName $Computer -Force
32 | Write-Log " - Removed $User from $Computer"
33 | }
34 | }
35 | }
36 | If ( $PrimaryUser -eq $Null ) { Move-Item $LogFile "C:\temp\Remove-DuplicateUsersFromCMDevice\Logs\NoPrimaryUser" }
37 | $PrimaryUser = ""
38 | $Users = ""
39 | $User = ""
40 | }
--------------------------------------------------------------------------------
/SCCM/Set-Boundaries_To_Peer-BoundaryGroup.ps1:
--------------------------------------------------------------------------------
1 | Clear-Host
2 | Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
3 | cd a01:
4 | $Boundaries = @("Bound01","Bound02")
5 |
6 | ForEach ( $Boundary in $Boundaries ) {
7 | Try {
8 | $BoundaryID = $(Get-CMBoundary -BoundaryName "*Production - Central - $Boundary*").BoundaryID
9 | Write-host "Successfully" -ForegroundColor Green -NoNewline ; Write-host " retrieved BoundaryID: $BoundaryID for Boundary: ""*Production - Central - $Boundary*"""
10 | Try {
11 | Add-CMBoundaryToGroup -BoundaryID $BoundaryID -BoundaryGroupName "Production - Central Peer content"
12 | Write-host "Successfully" -ForegroundColor Green -NoNewline ; Write-host " added BoundaryGroup: ""Production - Central Peer content"" to BoundaryID: $BoundaryID"
13 | Try {
14 | Remove-CMBoundaryFromGroup -BoundaryGroupName "Production - Central content - $Boundary" -BoundaryId $BoundaryID -Force
15 | Write-host "Successfully" -ForegroundColor Green -NoNewline ; Write-host "Successfully removed BoundaryID: $BoundaryID from BoundaryGroup: ""Production - Central content - $Boundary"""
16 | }
17 | Catch {
18 | Write-host "Failed" -ForegroundColor Red -NoNewline ; Write-host " to remove BoundaryID: $BoundaryID from BoundaryGroup: ""Production - Central content - $Boundary"""
19 | }
20 | }
21 | Catch {
22 | Write-host "Failed" -ForegroundColor Red -NoNewline ; Write-host " to add BoundaryGroup: ""Production - Central content"" to BoundaryID: $BoundaryID"
23 | }
24 | }
25 | Catch {
26 | Write-host "Failed" -ForegroundColor Red -NoNewline ; Write-host " to retrieve BoundaryID: $BoundaryID for Boundary: ""*Production - Central - $Boundary*"""
27 | }
28 | Write-host ""
29 | }
--------------------------------------------------------------------------------
/SharedCode.psm1:
--------------------------------------------------------------------------------
1 | Function Write-Log {
2 | [CmdletBinding()]
3 | param (
4 | [Parameter(Position=0)]
5 | [string]$Message,
6 | [Parameter(Position=1)]
7 | [ValidateSet('INFO','WARN','ERROR')][string]$LogType = 'INFO',
8 | [Parameter(Position=2)]
9 | [ValidateSet('Yes','No')][string]$WritePrefix = 'Yes'
10 | )
11 | $CurrentDateTime = Get-Date -format "yyyy-MM-dd HH:mm"
12 | if($Message -eq $null){ $Message = "" }
13 | If ( $WritePrefix -eq "YES" ) {
14 | $LogEntry = "$LogType $CurrentDateTime - $Message"
15 | }
16 | Else {
17 | $LogEntry = "$Message"
18 | }
19 | Add-Content -Value $LogEntry -Path $LogFile -Encoding UTF8
20 | Write-Verbose $LogEntry
21 | }
22 |
23 | $global:Domain = $( Get-ADDomain ).DNSRoot # domain.domain.com
24 | $global:DomainName = $( Get-ADDomain ).Name # domain
25 | $global:DomainDN = $( Get-ADDomain ).DistinguishedName # DC=domain,DC=domain,DC=com
--------------------------------------------------------------------------------
/Windows/Convert-CSVToExcel.ps1:
--------------------------------------------------------------------------------
1 | Function Convert-CSVToExcel {
2 |
3 | [CmdletBinding()]
4 | param (
5 | [Array]$Headers,
6 | [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][String]$TargetFile,
7 | [ValidateNotNullOrEmpty()][String]$SourceFile,
8 | [String]$SheetName = "Sheet1",
9 | [String]$Delimiter = ";",
10 | [Int]$Rowcount,
11 | [switch]$NoHeadersInCSV
12 | )
13 |
14 | $excel = New-Object -ComObject excel.application
15 | #$excel.visible = $true
16 | $workbook = $excel.Workbooks.Add()
17 | $ExcelWorkbook= $workbook.Worksheets.Item(1)
18 | $ExcelWorkbook.Name = $SheetName
19 |
20 | If ( $Headers -eq $Null ) { $Headers = $(Get-Content $SourceFile -First 1).Split($Delimiter)}
21 | [System.Collections.ArrayList]$Records = Import-Csv -Path $SourceFile -Delimiter $Delimiter -Header $Headers
22 |
23 | If ( $Headers -ne $Null -and $NoHeadersInCSV -eq $false ) { $Records.RemoveAt(0)}
24 | If ( $RowCount -ne 0 ) { $Records = $Records | Select -First $RowCount }
25 |
26 | $Counter = 1
27 | ForEach ( $Header in $Headers ) {
28 | $ExcelWorkbook.Cells.Item(1,$Counter) = $Header
29 | $ExcelWorkbook.Cells.Item(1,$Counter).Font.Size = 12
30 | $ExcelWorkbook.Cells.Item(1,$Counter).Font.Bold=$True
31 | $ExcelWorkbook.Cells.Item(1,$Counter).Font.ColorINdex = 2
32 | $ExcelWorkbook.Cells.Item(1,$Counter).Interior.ColorIndex = 49
33 | $Counter++
34 | }
35 |
36 | $headerRange = $ExcelWorkbook.Range("1:1")
37 | $headerRange.AutoFilter() | Out-Null
38 |
39 | $ExcelWorkbook.Application.ActiveWindow.SplitRow = 1
40 | $ExcelWorkbook.Application.ActiveWindow.FreezePanes = $true
41 |
42 | $Counter = 2
43 | foreach($record in $Records) {
44 | Try {
45 | $HeadCounter = 1
46 | ForEach ( $Header in $Headers ) {
47 | $excel.cells.item($Counter,$headCounter) = $record.$Header
48 | $HeadCounter++
49 | }
50 | $Counter++
51 | }
52 | Catch {}
53 | }
54 |
55 | $usedRange = $ExcelWorkbook.UsedRange
56 | $usedRange.EntireColumn.AutoFit() | Out-Null
57 |
58 | $workbook.SaveAs($TargetFile)
59 | $excel.Quit()
60 | }
61 |
62 | #Convert-CSVToExcel -Headers 'Boundary Group','DPType','ScopeLeases','ScopeDescription','ScopeCIDR' -TargetFile 'C:\Scripts\SCCM\Get-CMBoundariesWithoutDP.xlsx' -SourceFile 'C:\Scripts\SCCM\Get-CMBoundariesWithoutDP.log' -SheetName 'List of Boundaries etc.' -Delimiter ';' -Rowcount 10
63 | Convert-CSVToExcel -TargetFile 'C:\Scripts\SCCM\Get-CMBoundariesWithoutDP.xlsx' -SourceFile 'C:\Scripts\SCCM\Get-CMBoundariesWithoutDP.log' -SheetName 'List of Boundaries etc.' -Delimiter ';' -Rowcount 10
64 |
65 | C:\Scripts\SCCM\Get-CMBoundariesWithoutDP.xlsx
--------------------------------------------------------------------------------
/Windows/Open-ClientDrive.ps1:
--------------------------------------------------------------------------------
1 | $t = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);'
2 | add-type -name win -member $t -namespace native
3 | If ( $(Test-Path variable:global:psISE) -eq $False ) { [native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0) } # This hides the Powershellwindow in the background if ISE isn't running
4 |
5 | Function ViewForm {
6 |
7 | #Load assemblies for System.Windows.Forms and System.Drawing
8 | [reflection.assembly]::loadwithpartialname(“System.Windows.Forms”) | Out-Null
9 | [reflection.assembly]::loadwithpartialname(“System.Drawing”) | Out-Null
10 | Add-Type -AssemblyName PresentationCore,PresentationFramework
11 |
12 | # Create new objects to be used within the script
13 | $Form = New-Object System.Windows.Forms.Form
14 | $ComputerLabel = New-Object System.Windows.Forms.Label
15 | $ComputerTextBox = New-Object System.Windows.Forms.TextBox
16 | $UserNameLabel = New-Object System.Windows.Forms.Label
17 | $UserNameTextBox = New-Object System.Windows.Forms.TextBox
18 | $PasswordLabel = New-Object System.Windows.Forms.Label
19 | $PasswordTextBox = New-Object System.Windows.Forms.TextBox
20 | $ConnectButton = New-Object System.Windows.Forms.Button
21 |
22 | #Defines what will happen when clicking on the button ConnectButton
23 | $handler_ConnectButton_Click = {
24 | If ( Test-Connection -ComputerName $($ComputerTextBox.Text) -Count 1 ) {
25 | net use \\$($ComputerTextBox.Text)\c$ /user:$($UserNameTextBox.Text) $($PasswordTextBox.Text) /p:no
26 | If ( $LASTEXITCODE -eq 0 ) {
27 | explorer \\$($ComputerTextBox.Text)\c$
28 | net use /delete \\$($ComputerTextBox.Text)\c$
29 | }
30 | Else {
31 | $ErrorMessage = "An error occured while connecting."
32 | If ( $error[0] -like "*The referenced account is currently locked out and may not be logged on to.*" ) { $ErrorMessage = "The user account is currently locked out" }
33 | If ( $error[0] -like "*The specified network password is not correct.*" ) { $ErrorMessage = "The password is incorrect" ; $PasswordTextBox.Text = "" }
34 | If ( $error[0] -like "*The user name or password is incorrect.*" ) { $ErrorMessage = "The password is incorrect" ; $PasswordTextBox.Text = "" }
35 | [System.Windows.MessageBox]::Show($ErrorMessage,"$($Form.Text) - Error connecting","Ok","Warning")
36 | }
37 | }
38 | Else {
39 | [System.Windows.MessageBox]::Show("Can't connect to computer $($ComputerTextBox.Text), no ping response","$($Form.Text) - Error connecting","Ok","Warning")
40 | }
41 | }
42 |
43 | # Creating the Form-object
44 | $Form.Text = “Open Client Drive”
45 | $Form.Name = “Open Client Drive”
46 | $Form.FormBorderStyle = 'Fixed3D'
47 | $Form.MaximizeBox = $False
48 | $System_Drawing_Size = New-Object System.Drawing.Size
49 | $System_Drawing_Size.Width = 230
50 | $System_Drawing_Size.Height = 133
51 | $Form.ClientSize = $System_Drawing_Size
52 |
53 | # Sets variables that will be the same for a couple of the objects in the form
54 | $LabelXWidth = 100
55 | $LabelXPoint = 10
56 | $TextBoxXWidth = 250
57 | $TextBoxXPoint = 110
58 | $ButtonXPoint = 10
59 | $RowHeight = 25
60 |
61 | # Creating the ComputerLabel-object
62 | $ComputerLabel.Name = "ComputerLabel"
63 | $ComputerLabel.Text = "Computer:"
64 | $System_Drawing_Size.Width = $LabelXWidth
65 | $System_Drawing_Size.Height = $RowHeight
66 | $System_Drawing_Point = New-Object System.Drawing.Point
67 | $System_Drawing_Point.X = $LabelXPoint
68 | $System_Drawing_Point.Y = 10
69 | $ComputerLabel.Location = $System_Drawing_Point
70 |
71 | # Creating the ComputerTextBox-object
72 | $ComputerTextBox.Name = "ComputerTextBox"
73 | $System_Drawing_Size.Width = $TextBoxXWidth
74 | $System_Drawing_Point = New-Object System.Drawing.Point
75 | $System_Drawing_Point.X = $TextBoxXPoint
76 | $System_Drawing_Point.Y = 10
77 | $ComputerTextBox.Location = $System_Drawing_Point
78 |
79 | # Creating the UserNameLabel-object
80 | $UserNameLabel.Name = "UserNameLabel"
81 | $UserNameLabel.Text = "Username (ex. L2berfeadm):"
82 | $System_Drawing_Size.Width = $LabelXWidth
83 | $System_Drawing_Size.Height = $RowHeight
84 | $System_Drawing_Point = New-Object System.Drawing.Point
85 | $System_Drawing_Point.X = $LabelXPoint
86 | $System_Drawing_Point.Y = 40
87 | $UserNameLabel.Location = $System_Drawing_Point
88 |
89 | # Creating the UserNameTextBox-object
90 | $UserNameTextBox.Name = "UserNameTextBox"
91 | $UserNameTextBox.Text = $UserName
92 | $UserNameTextBox.Enabled = $False
93 | $System_Drawing_Size.Width = $TextBoxXWidth
94 | $System_Drawing_Point = New-Object System.Drawing.Point
95 | $System_Drawing_Point.X = $TextBoxXPoint
96 | $System_Drawing_Point.Y = 40
97 | $UserNameTextBox.Location = $System_Drawing_Point
98 |
99 | # Creating the PasswordLabel-object
100 | $PasswordLabel.Name = "PasswordLabel"
101 | $PasswordLabel.Text = "Password:"
102 | $System_Drawing_Size.Width = $LabelXWidth
103 | $System_Drawing_Size.Height = $RowHeight
104 | $System_Drawing_Point = New-Object System.Drawing.Point
105 | $System_Drawing_Point.X = $LabelXPoint
106 | $System_Drawing_Point.Y = 70
107 | $PasswordLabel.Location = $System_Drawing_Point
108 |
109 | # Creating the PasswordTextBox-object
110 | $PasswordTextBox.Name = "PasswordTextBox"
111 | $System_Drawing_Size.Width = $TextBoxXWidth
112 | $System_Drawing_Point = New-Object System.Drawing.Point
113 | $System_Drawing_Point.X = $TextBoxXPoint
114 | $System_Drawing_Point.Y = 70
115 | $PasswordTextBox.PasswordChar = "*"
116 | $PasswordTextBox.Location = $System_Drawing_Point
117 |
118 | # Creating the ConnectButton-object
119 | $ConnectButton.TabIndex = 7
120 | $ConnectButton.Name = “ConnectButton”
121 | $System_Drawing_Size = New-Object System.Drawing.Size
122 | $System_Drawing_Size.Width = 100
123 | $System_Drawing_Size.Height = 25
124 | $ConnectButton.Size = $System_Drawing_Size
125 | $ConnectButton.UseVisualStyleBackColor = $True
126 | $ConnectButton.Text = “Connect”
127 | $System_Drawing_Point = New-Object System.Drawing.Point
128 | $System_Drawing_Point.X = 110
129 | $System_Drawing_Point.Y = 100
130 | $ConnectButton.Location = $System_Drawing_Point
131 | $ConnectButton.add_Click($handler_ConnectButton_Click)
132 |
133 | # Adding created objects to the Form
134 | $Form.Controls.Add($ComputerLabel)
135 | $Form.Controls.Add($ComputerTextBox)
136 | $Form.Controls.Add($UserNameLabel)
137 | $Form.Controls.Add($UserNameTextBox)
138 | $Form.Controls.Add($PasswordLabel)
139 | $Form.Controls.Add($PasswordTextBox)
140 | $Form.Controls.Add($ConnectButton)
141 |
142 | # Displays the Form-window
143 | $Form.ShowDialog()| Out-Null
144 | }
145 |
146 | # Trigger the ViewForm-function
147 | ViewForm
--------------------------------------------------------------------------------
/Windows/StartMenuCustomizer/StartLayout.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/Windows/StartMenuCustomizer/StartLayout2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/Windows/StartMenuCustomizer/Untitled1.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | hej
7 | hej
8 | hej
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------