Skip to content

Instantly share code, notes, and snippets.

@cloudcap10
Forked from cactaceae21/AD_Computers.ps1
Created April 19, 2020 01:13
Show Gist options
  • Save cloudcap10/efc77997caa3307c911043eedaa2c537 to your computer and use it in GitHub Desktop.
Save cloudcap10/efc77997caa3307c911043eedaa2c537 to your computer and use it in GitHub Desktop.
Powershell #powershell
#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
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
}
<#
.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
#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
// 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
$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