Skip to content

Instantly share code, notes, and snippets.

@alexmags
alexmags / Set-GitUserDetails.ps1
Created February 26, 2021 08:14
Auto configure Git user name and email based on Active Directory lookup
# Auto configure Git user name and email based on Active Directory lookup
[reflection.assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement") | out-null
$currentUser=[System.DirectoryServices.AccountManagement.UserPrincipal]::Current
& git.exe config --global user.name "$($currentUser.DisplayName)"
& git.exe config --global user.email $($currentUser.EmailAddress)
@alexmags
alexmags / Set-GitUserConfigLocation.ps1
Created February 26, 2021 08:17
Git client puts it's config in %homedrive%%homepath%. This is usual for Windows apps and breaks when homedrive disconnected. Use %appdata%\git
# %homedrive%%homepath% is weird and breaks when homedrive disconnected. Use %appdata%
# https://git-scm.com/docs/git-config#git-config-XDGCONFIGHOMEgitconfig
$ConfigDefaultLocation="$($env:homedrive)$($env:homedrive)\.gitconfig" # breaks when network drive isn't connected
$ConfigBetterLocation="$($env:appdata)\git\config" # Standard location for app data that you want to follow user
[System.Environment]::SetEnvironmentVariable('XDG_CONFIG_HOME', "$($env:appdata)",[System.EnvironmentVariableTarget]::user)
$env:XDG_CONFIG_HOME=[System.Environment]::GetEnvironmentVariable("XDG_CONFIG_HOME","User")
# make better git data folder if not exists
New-Item -ItemType directory -Path "$($env:XDG_CONFIG_HOME)\git" -ErrorAction SilentlyContinue | out-null
@alexmags
alexmags / set-GitUserProxySettings.ps1
Last active February 26, 2021 08:30
Configure Git client to use corporate proxy and authenticate as current user
# This takes a guess at what Git config should be for proxy. Effectivly we're doing netstat.exe | find "8080"
# Lookup current user via Active Directory
[reflection.assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement") | out-null
$currentUser=[System.DirectoryServices.AccountManagement.UserPrincipal]::Current
#region Test if behind a proxy. This also generates some traffic that we'll use to determine proxy URL
try {
Write-output "Testing internet access"
$status = (Invoke-WebRequest -Uri "https://www.powershellgallery.com/api/v2" -UseBasicParsing).StatusDescription
@alexmags
alexmags / set-AADRoleMembersByADSecurityGroup.ps1
Last active February 26, 2022 08:11
PowerShell to map AD security group members to Azure AD roles.
# Make code debuggable
$ErrorActionPreference = "Stop"
Set-StrictMode -Version latest
# Enable use of proxy using current credentials
$browser = New-Object System.Net.WebClient
$browser.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials
# Download PowerShell module if not already installed
function get-moduleIfNotInstalled ($modulename) {
@alexmags
alexmags / AAD Guest last login kql
Last active February 26, 2022 08:10
Report in AAD sign in logs the last time an Azure AD guest account was used
// https://blog.alexmags.com/tags/kql/
let last_sign_in_by_account =
SigninLogs
| where TimeGenerated > now(-90d)
| where ResultType == 0
// filtering out local accounts to identify guest accounts. I couldn't identify account type in log data. Maybe TimeGenerated.HomeTenantId??
| where UserPrincipalName !endswith "companyname.com" and UserPrincipalName !endswith "AlsoCompanyname.com" and UserPrincipalName !endswith "tenantname.onmicrosoft.com" and UserPrincipalName !endswith "YetAnotherVerifiedDomain.com" and UserPrincipalName !endswith "SeriouslyICouldntIdentifyAccountTypeInLogData.com"
// get last login per account
| summarize argmax(TimeGenerated, *) by UserPrincipalName;
last_sign_in_by_account
// KQL because SharePoint Admin centre can make surprise new Conditional Access policies when you configure tenant level settings.
// Look for SharePoint ID and brackets in display name
// Create a notification action on AAD audit logs when this happens. https://blog.alexmags.com/tags/kql/
AuditLogs
| where Category == "Policy" and (Identity == 'Office 365 SharePoint Online' or TargetResources[0].displayName contains '[')
| project TimeGenerated, OperationName, TargetResources[0].displayName,Identity,InitiatedBy.user.userPrincipalName
@alexmags
alexmags / BitlockerStatus.kql
Last active January 11, 2023 16:51
KQL Bitlocker status Defender for Endpoint
// inspired by SecGuru_OTX https://twitter.com/SecGuru_OTX/status/1402580761828593672
let TVMConfigAssessKB = DeviceTvmSecureConfigurationAssessmentKB
| where ConfigurationSubcategory == 'Bitlocker';
let timeframe = 7d;
DeviceLogonEvents
| where Timestamp >= ago(timeframe)
| where ActionType == 'LogonSuccess'
| summarize TimeGenerated = any(*) by DeviceName, DeviceId
| join (
DeviceTvmSecureConfigurationAssessment
@alexmags
alexmags / localadmins.kql
Last active February 26, 2022 08:06
Logins with local administrator access report - Defender for Endpoint
DeviceLogonEvents
| where Timestamp >= ago(30d) // last month
| where IsLocalAdmin == 1
// number of machines connected to by the account
| summarize count() by DeviceName, AccountName,LogonType // ,AdditionalFields
| sort by AccountName
// also see https://www.verboon.info/2020/09/hunting-for-local-group-membership-changes/
// https://blog.alexmags.com/tags/kql/
@alexmags
alexmags / get-ADPublishedPrintQueues.ps1
Last active October 22, 2023 23:50
PowerShell to find print servers from AD
import-module ActiveDirectory # From Remote Server Admin Tools (RSAT) Windows Desktop/server OS feature
# get print queues published in Active Directory
$printqueues=Get-AdObject -filter "objectCategory -eq 'printqueue'" -Properties *
# list the print queue server names and filter out duplicates where one server has multiple print queues
$PrintServers=$printqueues | select servername | Sort-Object -property servername -Unique
# Export to CSV file reports (calculated property printshares as semicolon delimited list) https://ss64.com/ps/select-object.html
$PrintServers | Export-Csv -NoTypeInformation -Encoding UTF8 -path $env:temp\printservers.csv
@alexmags
alexmags / FileUploadedToCloud.KQL
Last active December 20, 2022 20:37
Defender For Endpoint KQL to report on files uploaded to cloud from Edge & Chrome by Sensitivity label. https://blog.alexmags.com/posts/kql-for-file-uploaded-to-cloud/
// https://blog.alexmags.com/tags/kql/
// lookup table for AIP label GUIDs
let AIPLabels=datatable(SensitivityGUID:string,Classification:string,SubClassification:string)
[
// AIP O365 sensitivity label GUID, parent label name, sub label name
"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Public", "Public",
"ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj", "Internal", "Internal",
"kkkkkkkk-llll-mmmm-nnnn-oooooooooooo", "Secret", "Secret",
"pppppppp-qqqq-rrrr-ssss-tttttttttttt", "Super secret", "Super secret"
];