Last active
February 3, 2024 02:03
-
-
Save cactaceae21/79271a42f1e267539e185e9c15888768 to your computer and use it in GitHub Desktop.
Powershell #powershell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Get OS of all domain joined computers and group by OS with count | |
# 1. | |
Get-ADComputer -Filter * -Properties OperatingSystem | Sort-Object -Property OperatingSystem | Group-Object -Property OperatingSystem -NoElement | ft -AutoSize | |
# 2. | |
$ADComputers = @() | |
$ADComputers = Get-ADComputer -Filter * -Properties OperatingSystem,lastLogonTimestamp | |
$ADComputers | Sort-Object -Property OperatingSystem | Group-Object -Property OperatingSystem -NoElement | ft -AutoSize | |
##Create date object for queries below | |
$today = (GET-DATE) | |
$anotherday = $today.AddDays(-105) | |
## All computers logged on in last X days: Count by OS type / sort by OS type | |
Get-ADComputer -Filter {lastLogonTimestamp -gt $anotherday} -Properties OperatingSystem,OperatingSystemVersion| Sort-Object OperatingSystem | ` | |
Group-Object -Property OperatingSystem -NoElement | ft -AutoSize | |
##List Windows 7 type OS logged on in last X days | |
Get-ADComputer -Filter {lastLogonTimestamp -gt $anotherday -and OperatingSystem -like "Windows 7*" } -Properties OperatingSystem,OperatingSystemVersion | ` | |
Sort-Object OperatingSystem | Group-Object -Property OperatingSystem -NoElement | ft -AutoSize | |
##List all Windows 2008 R2 hosts and their last logon date: Sort by Last Logon date | |
Get-ADComputer -Filter {lastLogonTimestamp -gt $anotherday -and OperatingSystem -eq "Windows Server 2008 R2 Standard" } ` | |
-Properties OperatingSystem,OperatingSystemVersion,lastlogondate| Sort-Object lastlogondate | ft name,lastlogondate,OperatingSystem | |
##Windows 2012 machines logged on in last X days: Count per OU / sorted by OU | |
##Creates OU list from CanonicalName of object removing the Domain Name at the start and Host Name at the end | |
Get-ADComputer -Filter {lastLogonTimestamp -gt $anotherday -and OperatingSystem -like "Windows Server 2012*" } -Properties OperatingSystem,OperatingSystemVersion,CanonicalName| ` | |
Select-Object @{N="OULocation"; E={$_.CanonicalName.Substring(15,$_.CanonicalName.IndexOf($_.Name)-16)}} | ` | |
Sort-Object OULocation | Group-Object -Property OULocation -NoElement | ft -AutoSize | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function aduser ($username){ | |
$user = Get-ADUser -identity $username -Properties EmailAddress,Enabled,memberOf # | fl -Property SamAccountName,UserPrincipalName,Name,EmailAddress,Enabled | |
#Get-ADUser $username -Properties memberOf | Select -ExpandProperty memberof | |
$GroupMembership = ($user.memberOf | % { (Get-ADGroup $_).Name; }) -join '; ' | |
$output = @{ SamAccountName = $user.SamAccountName | |
UserPrincipalName = $user.UserPrincipalName | |
Name = $user.Name | |
EmailAddress = $user.EmailAddress | |
Enabled = $user.Enabled | |
MemberOf = $GroupMembership | |
} | |
$output | ft -Wrap -HideTableHeaders | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function DecodeUserAccountControl ([int]$UAC) | |
{ | |
$UACPropertyFlags = @( | |
"SCRIPT", | |
"ACCOUNTDISABLE", | |
"RESERVED", | |
"HOMEDIR_REQUIRED", | |
"LOCKOUT", | |
"PASSWD_NOTREQD", | |
"PASSWD_CANT_CHANGE", | |
"ENCRYPTED_TEXT_PWD_ALLOWED", | |
"TEMP_DUPLICATE_ACCOUNT", | |
"NORMAL_ACCOUNT", | |
"RESERVED", | |
"INTERDOMAIN_TRUST_ACCOUNT", | |
"WORKSTATION_TRUST_ACCOUNT", | |
"SERVER_TRUST_ACCOUNT", | |
"RESERVED", | |
"RESERVED", | |
"DONT_EXPIRE_PASSWORD", | |
"MNS_LOGON_ACCOUNT", | |
"SMARTCARD_REQUIRED", | |
"TRUSTED_FOR_DELEGATION", | |
"NOT_DELEGATED", | |
"USE_DES_KEY_ONLY", | |
"DONT_REQ_PREAUTH", | |
"PASSWORD_EXPIRED", | |
"TRUSTED_TO_AUTH_FOR_DELEGATION", | |
"RESERVED", | |
"PARTIAL_SECRETS_ACCOUNT" | |
"RESERVED" | |
"RESERVED" | |
"RESERVED" | |
"RESERVED" | |
"RESERVED" | |
) | |
$Attributes = "" | |
1..($UACPropertyFlags.Length) | Where-Object {$UAC -bAnd [math]::Pow(2,$_)} | ForEach-Object {If ($Attributes.Length -EQ 0) {$Attributes = $UACPropertyFlags[$_]} Else {$Attributes = $Attributes + " | " + $UACPropertyFlags[$_]}} | |
Return $Attributes | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.SYNOPSIS | |
Easy script to remove all empty folders from a folder tree. | |
.DESCRIPTION | |
This script will run on the designated folder tree and remove all empty | |
folders, even nested ones. A HTML report will then be created and | |
emailed to the designated email address. | |
Update the Param section to meet your needs, or use the -TargetFolder | |
parameter when running the script to designate what folder you want the | |
script to work on. | |
** Please Note ** Will run a very long time on massive folder structures. | |
.PARAMETER TargetFolder | |
Designate the folder you want to run the script on. Will remove all | |
empty folders in that path. | |
.PARAMETER To | |
Who to email the report to | |
.PARAMETER From | |
You can designate who the email is coming from | |
.PARAMETER SMTPServer | |
You must designate the name or IP address of your SMTP relay server | |
.EXAMPLE | |
.\Remove-EmptyFolders.ps1 -TargetFolder \\Server\Share\Accounting | |
Will remove all empty folders in the Accounting folder on your server. The | |
report will be emailed to the default settings. | |
.EXAMPLE | |
.\Remove-EmptyFolders.ps1 -TargetPath d:\shares -To [email protected] -From [email protected] -SMTPServer exchange1 | |
Will remove all empty folders in D:\Shares, and email it to [email protected] | |
using the server Exchange1 as the SMTP relay. | |
.NOTES | |
Author: Martin Pugh | |
Twitter: @thesurlyadm1n | |
Spiceworks: Martin9700 | |
Blog: www.thesurlyadmin.com | |
Changelog: | |
1.0 Initial release | |
.LINK | |
http://community.spiceworks.com/scripts/show/1735-remove-emptyfolders-ps1 | |
#> | |
Param ( | |
[string]$TargetFolder = "c:\utils", | |
[string]$To = "[email protected]", | |
[string]$From = "[email protected]", | |
[string]$SMTPServer = "yourexchangeserver" | |
) | |
$Deleted = @() | |
$Folders = @() | |
ForEach ($Folder in (Get-ChildItem -Path $TargetFolder -Recurse | Where { $_.PSisContainer })) | |
{ $Folders += New-Object PSObject -Property @{ | |
Object = $Folder | |
Depth = ($Folder.FullName.Split("\")).Count | |
} | |
} | |
$Folders = $Folders | Sort Depth -Descending | |
ForEach ($Folder in $Folders) | |
{ If ($Folder.Object.GetFileSystemInfos().Count -eq 0) | |
{ $Deleted += New-Object PSObject -Property @{ | |
Folder = $Folder.Object.FullName | |
Deleted = (Get-Date -Format "hh:mm:ss tt") | |
Created = $Folder.Object.CreationTime | |
'Last Modified' = $Folder.Object.LastWriteTime | |
Owner = (Get-Acl $Folder.Object.FullName).Owner | |
} | |
Remove-Item -Path $Folder.Object.FullName -Force | |
} | |
} | |
$Today = Get-Date -Format "MM-dd-yyyy" | |
$Header = @" | |
<style> | |
TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;} | |
TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;} | |
TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;} | |
</style> | |
<Title> | |
Deleted Folders Report for $Today | |
</Title> | |
"@ | |
$MailProperties = @{ | |
From = $From | |
To = $To | |
Subject = "Remove-EmptyFolers.ps1 Run on $TargetFolder" | |
SMTPServer = $SMTPServer | |
} | |
If ($Deleted) | |
{ $Deleted = $Deleted | Select Folder,Deleted,Created,'Last Modified',Owner | Sort Folder | |
$Deleted = $Deleted | ConvertTo-Html -Head $Header | Out-String | |
} | |
Else | |
{ $Deleted = @" | |
<Title> | |
Deleted Folders Report for $Today | |
</Title> | |
<Body> | |
Deleted Folder run at $Today $(Get-Date -f "hh:mm:ss tt")<br> | |
<b>No empty folders detected</b> | |
</Body> | |
"@ | |
} | |
Send-MailMessage @MailProperties -Body $Deleted -BodyAsHtml |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#very basic to exclude internal addresses from Windows Firewall log files (if configured) | |
## C:\Windows\System32\LogFiles\Firewall | |
$tlog = "*.log" | |
$treg1918=@( # filters out RFC1918 addresses | |
"\b(?!10\.|192\.168\.|172\.(?:1[6-9]|2[0-9]|3[01])\.)(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}\b" | |
) | |
$tregmc=@( # for excluding other addresses such as multicast | |
"\b127\.0\.0\.1\b", | |
"\b255\.255\.255\.255\b", | |
"\b239\.255\.255\.250\b", | |
"\b224\.0\.0\.\d{1,3}\b", | |
"\b169\.254\.\d{1,3}\.\d{1,3}\b" | |
) | |
gc -Path $tlog | Select-String -pattern $treg1918 | Select-String -NotMatch -Pattern $tregmc | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Also check out: https://www.red-gate.com/simple-talk/sysadmin/powershell/powershell-one-liners-help,-syntax,-display-and--files/ | |
// List computers in an OU | |
Get-ADComputer -Filter 'name -like "*test*"' -SearchBase "OU=test,OU=test,DC=domain,DC=com" -Properties IPv4Address | ft DNSHostName, IPv4Address | |
// Send email | |
send-emailmessage -to "[email protected]" -from "[email protected]" -SMTPServer "mail.domain.com" -subject "mail subject" | |
// Check Bad Password Count | |
get-aduser <username> -properties badpwdcount -server ((Get-ADDomain).pdcemulator) | |
// Include another script (for Functions etc) | |
. "$PSScriptRoot\scriptname.ps1" | |
// Equiv FIND in DOS | |
Get-ChildItem “C:\path” -recurse | Select-String -pattern “find me” | group path | select name | |
// Change window size | |
$Host.UI.RawUI.BufferSize = New-Object Management.Automation.Host.Size (500, 25) | |
// Resolve IP address to hostname | |
Get-Content C:\IP_Address.txt | ForEach-Object {([system.net.dns]::GetHostByAddress($_)).hostname >> c:\hostname.txt} | |
// Change another users password (requires existing password) | |
Set-ADAccountPassword otheruser | |
// Expand AD properties that have multiple objects (eg. Service Principal Names) | |
Get-ADComputer <Computer> -Properties ServicePrincipalNames | Select-Object -ExpandProperty ServicePrincipalNames | |
Get-ADUser <User> -Properties MemberOf | Select-Object -ExpandProperty MemberOf | |
// List installed windows components | |
Get-WindowsFeature | Where-Object {$_. installstate -eq "isntalled"} | |
// List all empty sub-directories | |
Get-ChildItem | Where-Object { $_.PSIsContainer} | Where-Object {$_.GetFiles().Count -eq 0} | Where-Object {$_.GetDirectories().Count -eq 0} | ForEach-Object {$_.FullName} | |
// List all zero-length files | |
Get-ChildItem | Where-Object {$_.Length -eq 0} | |
// List Powershell object properties | |
$object.PSObject.Properties | |
// List recursive folder size | |
"{0:N2} MB" -f ((Get-ChildItem C:\directory\ -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB) | |
// List Windows addons (requires Admin priv) | |
Get-WindowsCapability -Online | |
//Resolve SID to Friendly Name | |
$objSID = New-Object System.Security.Principal.SecurityIdentifier | |
("S-1-5-21-768745588-123456789-987654321-500") | |
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount]) | |
$objUser.Value | |
//Get all logs and their associated sources | |
Get-EventLog -LogName * |ForEach-Object {$LogName = $_.Log;Get-EventLog -LogName $LogName -ErrorAction SilentlyContinue |Select-Object @{Name= "Log Name";Expression = {$LogName}}, Source -Unique} | |
//Remove all empty directories | |
Get-ChildItem -recurse | Where {$_.PSIsContainer -and @(Get-ChildItem -LiteralPath:$_.fullname).Count -eq 0} |remove-item -Confirm:$false -Force | |
//List call files/directories only | |
gci - recurse -file | select-object FileName | |
gci - recurse -directory | select-object FileName | |
//Finding accounts with Service Principal Names set | |
get-aduser -filter {(objectclass -eq 'user')} -property serviceprincipalname | where-Object {$PSItem.ServicePrincipalName -ne $null} | select-object serviceprincipalname,userprincipalname | ft -Wrap | |
//Listing all Service Principal Names from a group of accounts | |
// "setspn" is a windows AD executable, not a PowerShell Command | |
get-ADUser -filter {name -like "someaccount*" } -Properties servicePrincipalName | where-Object {$_.servicePrincipalName -ne $null} | foreach {setspn -L $_.name} | |
//List attributes of computers contained in an array | |
// "Cheap" and dirty, possibly slow - but it works | |
$ComputerList = @("computer1", "computer2", "computer3") | |
Get-ADComputer -filter {name -like "*"} | Where-Object {$computerList -contains $_.Name} | ft Name,Enabled | |
//Get Antivirus Product Status with PowerShell | |
//Link: (https://jdhitsolutions.com/blog/powershell/5187/get-antivirus-product-status-with-powershell/) | |
//Link: (https://social.msdn.microsoft.com/Forums/en-US/6501b87e-dda4-4838-93c3-244daa355d7c/wmisecuritycenter2-productstate) | |
// Not available on Server OS | |
Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntivirusProduct | |
//Find DNS records in AD based on Forward Zone (A/AAAA/CNAME) instead of Reverse Zone (PTR) | |
Get-DnsServerResourceRecord -ComputerName <dns server> -zonename <zone> | where-object {$_.RecordData.IPv4Address -eq "1.2.3.4"} | |
//Search Windows Event Logs for data - will need to be privileged and can be intensive | |
Get-WinEvent -listlog * | where {$_.RecordCount -gt 0} | Get-WinEvent | where {$_.message -match "<Data to find>"} | select TimeCreated,ProviderName,Id,Message | ft -AutoSize | |
//List Windows Advanced Firewall rules that are actually applied after policy | |
Get-NetFirewallrule -PolicyStore RSOP |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// With Outlook installed, access the first email message and properties | |
// https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.outlook?view=outlook-pia | |
// https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxprops/cc9d955b-1492-47de-9dce-5bdea80a3323 | |
// https://docs.microsoft.com/en-us/archive/msdn-magazine/2013/march/powershell-managing-an-outlook-mailbox-with-powershell | |
// | |
Add-Type -AssemblyName "Microsoft.Office.Interop.Outlook" | |
$Outlook = New-Object -ComObject Outlook.Application | |
$namespace = $Outlook.GetNameSpace("MAPI") | |
$firstmail = $namespace.Folders.Item(1).Folders.Item("Inbox").items(1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$Servers = @("server1.domain.com", "server2.domain.com") | |
foreach ($server in $Servers) { | |
$IPAddress = $null | |
try { | |
$IPAddress = [System.Net.Dns]::GetHostAddresses($server).IPAddressToString | |
} | |
catch { | |
$IPAddress = "No IP resolved." | |
} | |
if ($IPAddress -ne "No IP resolved.") { | |
$Alive = Test-Connection -ComputerName $IPAddress -Count 1 -Quiet | |
} | |
else { $Alive = "" } | |
Write-Host "$server`t`t`t$IPAddress`t`t$Alive" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment