Snippets that are useful for small business administrating Windows:
Find user that matches like expression with successful logins on a Windows 7 computer.
Get-WinEvent -FilterHashtable @{ id='4624' ; logname='security' } | where-object {$_.Properties[5].value -like "*jeffrey*" } | select TimeCreated, @{Label="User"; Expression={ $_.Properties[5].value} } , @{Label="Computer"; Expression={ $_.Properties[18].value} }
<#
.DESCRIPTION
FIND USERS LAST LOGIN
#>
function last-logon { param($username) get-aduser $username -properties * | select-object name, @{name=”lastlogon”;expression={[datetime]::fromfiletime($_.lastlogon)}} | s
ort-object lastlogon
<#
.DESCRIPTION
Get logon failures or success
#>
function GetLogonFailures {
Get-WinEvent -FilterHashTable @{ logname='security'; id=4625 } |
select-object TimeCreated,
@{Label="Username"; Expression={ $_.Properties[5].Value } } ,
@{ Label = "Domain" ; Expression={ $_.Properties[6].Value } } ,
@{ Label = "Source IP Address"; Expression={ $_.Properties[19].Value } }
}
function GetLogonSuccesses {
Get-WinEvent -FilterHashTable @{ logname='security'; id=4624 } |
select-object TimeCreated,
@{Label="Username"; Expression={ $_.Properties[5].Value } },
@{ Label = "Domain" ; Expression={ $_.Properties[6].Value } } ,
@{ Label = "Source IP Address"; Expression={ $_.Properties[18].Value } }
}
Another quick and dirty ADSI users and logon time sorted.
get-aduser -properties * -filter *| select Name, @{name = "lastlogon";expression={[datetime]::fromfiletime($_.lastlogon)}} |sort-object lastlogon
<#
.DESCRIPTION
Get group membership
#>
function group-membership {
param($name)
$adsi = new-object system.directoryservices.directorysearcher
$adsi.filter = "(&(objectCategory=user)(samAccountname=$name)) "
$groups = $adsi.findone().properties.memberof
foreach ($strGroup in $groups) {
$strGroup = $strGroup.split(',')[0]
$strGroup = $strGroup.split('=')[1]
$strGroup
}
}
<#
.DESCRIPTION
Obtain metadata for username
#>
function get-adminmetadata { param($username) get-aduser $username | get-adreplicationattributemetadata -server localhost | ft LastOriginatingChangeTime,LocalChangeUsn, LastOriginatingChangeDirectoryServerIdentity, LastOriginatingChangeUsn,AttributeName,Version}
<#
.DESCRIPTION
Find history of users added to groups.
#>
function get-usergrouphistory { param($username) $userobj = get-aduser $username ; get-aduser itadmin -Properties memberof | select-object -ExpandProperty memberof | foreach-object { Get-ADReplicationAttributeMetadata $_ -ShowAllLinkedValues -server localhost | where-object {$_.AttributeName -eq "member" -and $_.AttributeValue -eq $userobj } | select-object FirstOriginatingCreateTime,Object,AttributeValue | sort-object FirstOriginatingCreateTime -Descending } | ft }
<#
.DESCRIPTION
Sample of xml query from security logs
#>
function queryEventlog {
[XML]$query = @"
<QueryList>
<Query Id="0" Path="Security">
<Select Path="Security">*[System[(EventID=4624)]]</Select>
</Query>
</QueryList>
"@
Get-WinEvent -filterxml $query
}
<#
.DESCRIPTION
Sample using Gridview PassThru on Windows Logs
#>
function PassThru { { Get-EventLog -list | Out-GridView -PassThru | foreach { $_.Log; Get-EventLog -LogName $_.Log -Newest 10 } }
<#
.DESCRIPTION
Enable the recycle bin (restore AD object)
logontime: [datetime]::findtimestamp
Find Stale Groups
Move account to org, disable after 30-days, delete after 90-days
Computer delete A, AAAA, and PTR records.
#>
<#
.DESCRIPTION
Find ADGroups, display member counts, and when last changed.
#>
function stale-groups { get-adgroup -filter * -properties Name , whencreated, whenchanged, member, memberof | select-object name, whencreated, member, whenchanged, memberof, description, @{name ='membercount'; expression={$_.member.count}}}
<#
.DESCRIPTION
Find Stale Users
#>
function findlastlogon { param($username) get-aduser $username -properties * | select-object name, @{name=”lastlogon”;expression={[datetime]::fromfiletime($_.lastlogon)}} | sort-object lastlogon }
<#
.DESCRIPTION
Find all computers based on XP
#>
function oldxpcomputers {get-adcomputer -filter {OperatingSystem -like "*XP*"} -properties WhenChanged,lastlogontimestamp | select-object name, whenchanged, @{name='lasttime';expression={[datetime]::FromFileTimeUTC($_.LastLogonTimeSTamp)}}}
Enabled AD Recycle Bin (Forest and Domain 2012+) in Powershell:
# Pull the full name and path to recycle bin (can be very long)
$name = Get-ADOptionalFeature -filter *
Enable-ADOptionalFeature -Identity "$name.DistinguishedName"
-Target domain.com -Scope ForestOrConfigurationSet
Find files older then days:
# This scripts will identify old files in backup directories and remove them
#
$date = get-date
$directories = "Production","JBSettings","UniPoint_Live","UniPoint_unidx"
foreach ($oldfiles in $directories)
{ gci $oldfiles | where-object {$_.LastWriteTime.AddDays(3) -lt $date } }
Find 10 largest files in directory e:\Library:
invoke-command -ComputerName 192.168.1.1 -Credential $cred -ScriptBlock { gci e:\library -Recurse | Sort-Object -Descending Length | select -First 10 }
Here’s a simple, but very powerful and useful script to parse your Windows logs. Beginning in Windows 2008 Get-WinEvent replaced Get-EventLog.
function GetLogonFailures {
Get-WinEvent -FilterHashTable @{ logname='security'; id=4625 } |
select-object TimeCreated,
@{Label="Username"; Expression={ $_.Properties[5].Value } } ,
@{ Label = "Domain" ; Expression={ $_.Properties[6].Value } } ,
@{ Label = "Source IP Address"; Expression={ $_.Properties[19].Value } }
}
function GetLogonSuccesses {
Get-WinEvent -FilterHashTable @{ logname='security'; id=4624 } |
select-object TimeCreated,
@{Label="Username"; Expression={ $_.Properties[5].Value } },
@{ Label = "Domain" ; Expression={ $_.Properties[6].Value } } ,
@{ Label = "Source IP Address"; Expression={ $_.Properties[18].Value } }
}
This function can be used to extract a Active Directory user’s group memberships and copy them to an array.
function group-membership {
param($name)
$adsi = new-object system.directoryservices.directorysearcher
$adsi.filter = "(&(objectCategory=user)(samAccountname=$name)) "
$groups = $adsi.findone().properties.memberof
foreach ($strGroup in $groups) {
$strGroup = $strGroup.split(',')[0]
$strGroup = $strGroup.split('=')[1]
$strGroup
}
}
A fun function to avoid spammers with encoding your e-mail address.
function EncodeEmail { param($string)
$encode = $string;
$bytes=[System.Text.Encoding]::Unicode.GetBytes($encode);
$EncodedText=[Convert]::ToBase64String($bytes);
$EncodedText }
function DecodeEMail { param($string)
$decode = $string;
$decoded = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($decode))
$decoded;
}