Code Snippets

Here are some code snippets for automating small tasks.

Powershell: Listing all of the Computer Objects in the Unassigned OU, the Owner, and Last Updated timestamp:

[powershell] $objOU = [ADSI]”LDAP://OU=Unassigned,OU=NCSU,dc=wolftech,dc=ad,dc=ncsu,dc=edu”
foreach($computer in $objOU.Children) {
$computer.cn
$computer.ObjectSecurity.Owner
$computer.whenChanged
}
[/powershell]

Powershell: Check to see if hotfix is installed and if not, install appropriate one based on OS.

[powershell] #This script installs Microsoft dll search path fix.
if (!(get-hotfix -id KB2264107)) {
$computer = “LocalHost”
$namespace = “root\CIMV2”
$Processor = Get-WmiObject -class Win32_Processor -computername $computer -namespace $namespace
$OS = Get-WmiObject -class Win32_OperatingSystem -computername $computer -namespace $namespace
$InstallLocation = “C:\Windows”

switch( $Processor.AddressWidth ) {
“64” {
switch -wildcard ( $OS.Version ) {
“6.1*” { wusa.exe $InstallLocation\Windows6.1-KB2264107-x64.msu /quiet /norestart }
“6.0*” { wusa.exe $InstallLocation\Windows6.0-KB2264107-x64.msu /quiet /norestart }
“5.2*” { C:\Windows\WindowsServer2003.WindowsXP-KB2264107-x64-ENU.exe /quiet /norestart }
}
}

“32” {
switch -wildcard ( $OS.Version ) {
“6.1*” { wusa.exe $InstallLocation\Windows6.1-KB2264107-x86.msu /quiet /norestart }
“6.0*” { wusa.exe $InstallLocation\Windows6.0-KB2264107-x86.msu /quiet /norestart }
“5.2*” { C:\Windows\WindowsServer2003-KB2264107-x86-ENU.exe /quiet /norestart}
“5.1*” { C:\Windows\WindowsXP-KB2264107-x86-ENU.exe /quiet /norestart}
}
}
}
}
[/powershell]

Powershell: Run a batch file, retaining the working directory, with UAC elevation:

[powershell]powershell -nologo “start-process .\subdirectory\runme.cmd -workingdirectory (pwd) -verb runas”[/powershell]

Powershell: Get the local serial number (or service tag if its a Dell):

[powershell]Get-WMIObject -Class “Win32_BIOS” -Computer . | select SerialNumber[/powershell]

Powershell: If a GPO has “AllSettingsDisabled” set on it, well, it has all settings disabled. Its inert. Useless. Running the 2 lines of code below yeilds all GPO’s in the domain with that set.
[powershell]import-module Grouppolicy
get-gpo -all | where { $_.GPOstatus -eq “AllSettingsDisabled”}[/powershell]

Powershell: The following couple lines of code will use Out-GridView to display every GPO in the whole domain that has 0/zero/zilch links to GPO’s. If something is linked to the root of the domain or a Site, it will show up in the list too, but this gets the point across.
[powershell] import-module Grouppolicy
$GPOs = get-gpo -all
$list = @{}
foreach($g in $GPOs){
$temp = [adsisearcher]””
$temp.Filter = “(&(objectClass=organizationalUnit)(gPLink=*” + $g.Id + “*))”
$temp2 = $temp.FindAll()
Add-Member -in $g -Type NoteProperty -Name GPLinkCount -Value $temp2.Count
}
$GPOs | Where {$_.GPLinkCount -eq 0} | Select-Object DisplayName,Owner,ModificationTime,GPLinkCount | Sort-Object DisplayName | Out-Gridview

[/powershell]

Powershell: Fun with Out-Gridview!
[powershell] Get-Service | Select-Object * | Out-GridView
Get-EventLog -LogName Application -Newest 100 | Out-GridView
Get-Process | Out-GridView # Short list
Get-Process | Select-Object * | Out-Gridview # Long list
Get-HotFix | Select-Object * | Out-GridView
[/powershell]

Powershell: Search through SYSVOL for stuff that shouldn’t be there.
[powershell] import-module Grouppolicy
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
$path = “\\” + $domain + “\Sysvol\” + $domain + “\Policies”
$Results = Get-ChildItem -Path $path -recurse | Where-Object {$_.name -notmatch “^*.adm|admx|adml|aas|xml|inf|pol|csv|ins|ini|cmtx|cmt|cfg$”}
$Results | ForEach-Object {
$_.PSPath -match “{(.*)}”
Add-Member -in $_ -Type NoteProperty -Name “GUID” -Value $matches[1] $GPO = Get-GPO -Guid $matches[1] Add-Member -in $_ -Type NoteProperty -Name “GPO” -Value $GPO.DisplayName
Add-Member -in $_ -Type NoteProperty -Name “GPO_Owner” -Value $GPO.Owner
}
$Results | Where {$_.PSisContainer -eq $false} | Select-Object GPO,GPO_Owner,DirectoryName,Name,Length | Out-Gridview
[/powershell]

Powershell: Locate all of the ancient objects with SID Histories from when ADMT was used.
[powershell] $query = [ADSISearcher]””
$query.Filter = “(sIDHistory=*)”
$query.SearchRoot = “LDAP://DC=wolftech,DC=ad,DC=ncsu,DC=edu”
$Results = $query.FindAll()
$Results
[/powershell]

Powershell: Delete domain profiles from a local machine
[powershell] $userProfiles = Get-WmiObject Win32_userProfile
foreach ($prof in $userProfiles) {
if ($prof.sid -like “S-1-5-21-2670277017*”) {
$prof.delete()
}
}
[/powershell]

Powershell: Function to test spelling
[powershell] Function Spelling {
param ([String]$testString = $(throw ‘a string is required’))
$oWord=new-object -COM Word.Application
$oWord.CheckSpelling($testString)
}

Spelling(“This is a string”) # True
Spelling(“This is a strg”) # False
[/powershell]

Powershell: Writing to the Event Log
[powershell] $event = New-Object System.Diagnostics.EventLog(“Application”)
$event.Source = “EventSource”
$eventType = [System.Diagnostics.EventLogEntryType]::Information
$eventID = 70
$eventText = “My Test Event”
$event.WriteEntry($eventText,$eventType,$eventID)
[/powershell]

PowerShell: SCCM Application Detection Method

[powershell]

# Version to detect
$version = “4.15.4”
# Path to file
$path = “c:\Program Files\PosPay\version”

$appVersion = get-content -Path $path
if ($appVersion.contains($version)) {
Write-Host “Installed”
}
else {
}

[/powershell]

PowerShell: Sort IP Address

IPv4

[powershell] $IPAddresses | Sort-Object -Property { $_ -as [Version] }
[/powershell]

IPv6 sort last

[powershell] $code = {
$version = $_ -as [Version] if ($version -eq $null) { “z$_” }
else { $version }
}
[/powershell]

IPv6 soft first

[powershell] $code = {
$version = $_ -as [Version] if ($version -eq $null) { “/$_” }
else { $version }
}
[/powershell]

Powershell: Take all of the subfolders from a dfs target and explode them into separate dfs targets. Useful if you are prepping to do file server moves and you want to break up large shares into more manageable pieces.
[powershell] $root = “root”
$server = “server.ncsu.edu”
$folder = “department”
$domain = “wolftech.ad.ncsu.edu”
Get-ChildItem “\\$domain\$root\$folder” | ForEach-Object {
New-DfsnFolder -Path “\\$domain\$root\$folder-new\$_” -TargetPath “\\$server\$folder\$_” #-WhatIf
}
Move-DfsnFolder -Path “\\$domain\$root\$folder” -NewPath “\\$domain\$root\$folder-old”
Move-DfsnFolder -Path “\\$domain\$root\$folder-new” -NewPath “\\$domain\$root\$folder”
[/powershell]