PowerShell

Say ‘NO’ to Googling! Common sys admin tasks and hacks, all on one page.

Contents

Create beep through speakers

[console]::beep(440,500)

View powershell profile location

$profile

Edit powershell profile

Fires up a text editor

start $profile

Create a dialog box

$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("Operation Completed",0,"Done",0x1)
# OR
(new-object -ComObject wscript.shell).Popup("Operation Completed",0,"Done",0x1)
# OR
$wshell.Popup("$Env:ComputerName ",3,"Computername")
[System.Windows.Forms.MessageBox]::Show("Title" , "Content")

Netstat – filter by port

# run netstat as admin
Get-NetTCPConnection -LocalPort 389
netstat -an | findstr :389
netstat -abo | findstr :ldap
# then use get-process –pid  to find the .exe

Launch notepad, then start it again if it quits

Start-Process notepad.exe
$NotepadProc = Get-Process -Name notepad
$NotepadProc.WaitForExit()
Start-Process notepad.exe

Send email via PowerShell

Send-MailMessage -To john@savilltech.net" -Subject 'test subject' -from '<a class="linkification-ext" title="Linkification: mailto:administrator@savilltech.net" href="mailto:administrator@savilltech.net">administrator@savilltech.net</a>' -smtpServer 'savdalex01.savilltech.net' 

Get the time (without date etc)

$Time = get-date -displayhint Time
$Time

Set console window size (win7 only)

$host.UI.RawUI.WindowSize = new-object System.Management.Automation.Host.Size(80,10)

Rename computer and join domain

Rename-Computer -NewName $Computername
$domain = "domain.com.au."
$password = "password" | ConvertTo-SecureString -asPlainText -Force
$username = "$domain\user"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
sleep 5
Add-computer -DomainName $domain -Credential $credential -force -Options JoinWithNewName,AccountCreate

Disable truncated output

$FormatEnumerationLimit =-1

Run an elevated .ps1 script from the command line

PowerShell.exe -Command "{Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""C:\test.ps1""' -Verb RunAs}"

Move files from year 2011 in current directory into a 2011 folder

ls -force .\ *.* | Where-Object {$_.lastwritetime.year -match "2011"} | ForEach-Object {move-item $_ .\2011}

Find files modified within the last day

ls | where-object {(new-timespan $_.LastWriteTime).days -lt 1}

Set admin password

# sets local admin password to "hostnameextra"
([adsi]"WinNT://localhost/Administrator").SetPassword($(hostname).ToString().ToLower() + "extra")

Get currently logged on user

Get-WMIObject -ComputerName laptop03 -class Win32_ComputerSystem -ea silentlycontinue | select username, name
Get-Content .\computers.txt | ForEach-Object {get-wmiObject -ComputerName $_ -class Win32_ComputerSystem} | select name, username

Get last boot time

#local machine:
systeminfo | select-string "system boot"
Get-WmiObject -computer 10.42.200.137 -class win32_operatingsystem | select csname, @{LABEL=’LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}

List modules

Get-Module -ListAvailable

Test a command

# Shows what would happen if…

Get-Childitem C:\SomeFile\*.txt -Recurse | Remove-Item -WhatIf

Test if computer is online, and exit if it fails the test

If (Test-Connection -ComputerName $Computer -Count 1 -ErrorAction SilentlyContinue){
}
Else{
Write-Warning $Computer not pinging...
EXIT
}

Output PowerShell to clipboard

Get-EventLog Application | clip
Get-Content - also show PwdLastSet for a list of PCs
get-content .\workstations.txt | ForEach-Object {Get-ADcomputer $_ -properties passwordLastSet} | Select DNSHostName, PasswordLastSet

Search DNS for records (Win2012 + )

Get-DnsServerResourceRecord -ZoneName 'domain.com' |?{$_.RecordData.HostNameAlias -like "ServerDC01*"}
Get-DnsServerResourceRecord -ZoneName 'domain.com' |?{$_.RecordData.IPv4Address -like "192.1.1.21"}

Show available commands in a module

Ping a range of IP addresses

$i = 250
$AddrIP = "192.168.1."
Do { $IpHost = $AddrIP + $i
$Pingo = Get-WmiObject Win32_PingStatus -f "Address='$IpHost'"
$Pingo | Format-Table Address, StatusCode -auto; $i++
}
until ($i -eq 255)

Find MAC Address with PowerShell

Ipconfig /all | Select-String Physical
[/code]

Launch notepad, then start it again if it quits (powershell)

Start-Process notepad.exe
$NotepadProc = Get-Process -Name notepad
$NotepadProc.WaitForExit()
Start-Process notepad.exe
[/code]

Example PowerShell Profile

Import-Module PSReadline
Add-PSSnapin vmware.vimautomation.core
CLS
Write-Host "PSreadline and VMware PowerCLI loaded" -ForegroundColor Green
Connect-VIserver V01PVMC01 -Credential (Get-Credential "Domain\JSmith-Admin")

Disk space on a remote machine

Get-WmiObject Win32_LogicalDisk -filter "DriveType=3" -computer AU-GEN002 | Select SystemName,DeviceID,VolumeName,@{Name="Size(GB)";Expression={"{0:N1}" -f($_.size/1gb)}},@{Name="FreeSpace(GB)";Expression={"{0:N1}" -f($_.freespace/1gb)}} | FT -Autosize


<h2>Disk space of multiple servers</h2>


<h2><code> Get-WmiObject Win32_LogicalDisk -filter "DriveType=3" -computer (Get-Content .\Servers.txt) | Select SystemName,DeviceID,VolumeName,@{Name="Size(GB)";Expression={"{0:N1}" -f($_.size/1gb)}},@{Name="FreeSpace(GB)";Expression={"{0:N1}" -f($_.freespace/1gb)}} | FT -Autosize</code></h2>


Install PowerShell ISE (for Out-GridView)

Import-Module ServerManager
Add-WindowsFeature PowerShell-ISE

PowerShell version

$PSVersionTable
#OR
host

Open/Run PowerShell

powershell
Allow all .ps1 scripts
set-executionpolicy unrestricted

PowerShell Run

Invoke-Elevated { YOUR COMMAND HERE }
Gwmi Win32_BIOS -comp (gc domaincontrollers.txt)

Set window title

$host.ui.RawUI.WindowTitle = "Multi-Pinger"

Trim text

Eg. Trim everything except for computername from “Drive \\Server\C$ not available”

$Computername = $Computername.TrimStart("Drive \\")
$Computername = $Computername.TrimEnd("\C$ not available")
$Computername = $Computername.Trim()

Point batch file at a .ps1 file

powershell -command "'C:\powershellfile.ps1' "

Enable .Net framework 3.5 on Windows 8.1

Enable-WindowsOptionalFeature –Online –FeatureName NetFx3 –All -LimitAccess -Source \\Server\Software\Microsoft\SxS_Win81
Get-Content .\computers.txt | ForEach-Object {get-wmiObject -ComputerName $ -class Win32_ComputerSystem} | select username

NMap

Scan /24 subnet showing details

sudo nmap -sV -T4 -O -F –version-light 192.168.1.0/24

Show running processes on a remote machine

gwmi -Class win32_process -computername SERVER01 | select CSName, Name, Description, ExecutablePath | Out-GridView

Empty Recycle Bin (all users)

ls -force -recurse -path c:\'$recycle.bin' -ErrorAction SilentlyContinue | remove-item -force -recurse -ErrorAction SilentlyContinue -verbose

DFS status

dfsrdiag backlog /ReceivingMember:Server2 /SendingMember:FileServer1 /RGName:domain.com\DFS\FinanceShare /RFName:FinanceShare
#OR
DFSRDiag ReplicationState

Upgrade to another server edition
DISM /online /Get-CurrentEdition
DISM /online /Get-TargetEditions

Install product key and activate

cscript //b c:\windows\system32\slmgr.vbs /ipk <productkey>

cscript //b c:\windows\system32\slmgr.vbs /ato

Launch Windows Update

C:\Windows\System32\control.exe /name Microsoft.WindowsUpdate

Where is windows getting its time from?
w32tm /query /status

Show installed windows features

Get-WindowsFeature | ? {$_.InstallState -eq "Installed"} | select displayname

DISM /online /Set-Edition:<edition ID> /ProductKey:XXXXX-XXXXX-XXXXX-XXXXX-XXXXX

Migrate a DFS file share

  • Setup a share on the new server with the same share permissions
  • Use robocopy \\sourceserver\share \\destserver\share /MIR /FFT /COPY:DAT /DCOPY:T (mirror, copy date/time/permissions
  • Add the new server/share as a folder target, but set it as disabled in DFS
  • When robocopy finishes, run it again as a delta
  • Switch the new server to enabled, and disable the other one

Log off a user via CMD

# Find the user's session ID
quser
# logoff the user's ID
logoff 3

Find Cert server (CA) from any PC

certutil -config - -ping

DHCP – export/backup all scopes

netsh dhcp server export %userprofile%\desktop\DHCP all

DHCP – import/restore all scopes

netsh dhcp server import %userprofile%\desktop\DHCP all

Show all installed server features

Get-WindowsFeature

Deduplication (Server 2012)

# Show current deduplication jobs
Get-DedupJob
#Show Deduplication schedule
Get-DedupSchedule
#Show disks with deduplication enabled<
Get-DedupVolume
#Show deduplication info eg. saved space
Get-DedupStatus
#Install/enable 2012 data deduplication</h2>


Import-Module ServerManager
Add-WindowsFeature -name FS-Data-Deduplication
Import-Module Deduplication

Install DHCP (recommended to install using GUI)

Add-WindowsFeature DHCP

Uninstall DHCP

Remove-WindowsFeature DHCP

Restart IIS

Iisreset

Show all processes, PIDs and owners

$owners = @{}
gwmi win32_process |% {$owners[$_.handle] = $_.getowner().user}
get-process | select processname,Id,@{l="Owner";e={$owners[$_.id.tostring()]}}

WSUS registry settings example

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate]
“WUServer”=”http://sv-emv-wus1
“WUStatusServer”=”http://sv-emv-wus1
“ElevateNonAdmins”=dword:00000001
“TargetGroup”=”Workstations
“TargetGroupEnabled”=dword:00000001

Server Core menu

sconfig

Capitalize/Sentence Case a variable

# convert inputs to Title Case
$band = (Get-Culture).TextInfo.ToTitleCase($band)

Get PowerShell module path

$env:PSModulePath

List modules

Get-Module -ListAvailable

Test if computer is online, and exit if it fails the test

If (Test-Connection -ComputerName $Computer -Count 1 -ErrorAction SilentlyContinue){
}
Else{
Write-Warning $Computer not pinging...
EXIT
}

Show DNS servers (Powershell v2)

Get-WmiObject win32_networkadapterconfiguration | select DNSServerSearchOrder

Use PowerShell to find IP

Ipconfig | Select-String IP

Find MAC Address with PowerShell

Ipconfig /all | Select-String Physical

Launch notepad, then start it again if it quits (powershell)

Start-Process notepad.exe
$NotepadProc = Get-Process -Name notepad
$NotepadProc.WaitForExit()
Start-Process notepad.exe

Example PowerShell Profile

Import-Module PSReadline
Add-PSSnapin vmware.vimautomation.core
CLS
Write-Host "PSreadline and VMware PowerCLI loaded" -ForegroundColor Green
Connect-VIserver VCENTERSERVER01 -Credential (Get-Credential "DOMAIN\adminuser")

Disk space on a remote machine (Powershell)

Get-WmiObject Win32_LogicalDisk -filter "DriveType=3" -computer COMPUTER02 | Select SystemName,DeviceID,VolumeName,@{Name="Size(GB)";Expression={"{0:N1}" -f($_.size/1gb)}},@{Name="FreeSpace(GB)";Expression={"{0:N1}" -f($_.freespace/1gb)}} | FT -Autosize

Disk space of multiple servers

Get-WmiObject Win32_LogicalDisk -filter "DriveType=3" -computer (Get-Content .\Servers.txt) | Select SystemName,DeviceID,VolumeName,@{Name="Size(GB)";Expression={"{0:N1}" -f($_.size/1gb)}},@{Name="FreeSpace(GB)";Expression={"{0:N1}" -f($_.freespace/1gb)}} | FT -Autosize

Set window title

$host.ui.RawUI.WindowTitle = "Multi-Pinger"

Trim text

$Computername = $Computername.TrimStart("Drive \\")
$Computername = $Computername.TrimEnd("\C$ not available")
$Computername = $Computername.Trim()

Set window buffer size

$console = $host.UI.RawUI
$buffer = $console.BufferSize
$buffer.Height = 5000
$console.BufferSize = $buffer

Open/select a file dialog box

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
# adjust initial directory if required
$OpenFileDialog.initialDirectory = "C:\Temp"
# comment this out to show all files
$OpenFileDialog.filter = "TXT | *.txt"
# This line prevents some machines from hanging
$OpenFileDialog.ShowHelp = $true
$openFileDialog.title = "Select a file"  
$OpenFileDialog.ShowDialog() | Out-Null
$file = $OpenFileDialog.filename

File Chooser (hacky)

$log = dir \\SERVER01\c$\windows\system32\logfiles\*.log | out-gridview -Title "Select log" -passthru

Directory/folder Chooser/picker (.NET)

$app = new-object -com Shell.Application
$directory = ($app.BrowseForFolder(0,"Specify Save Location", 0, "C:\")).Self.Path
while ($directory -like "")
{
$directory = ($app.BrowseForFolder(0, "Select Folder", 0, "C:\")).Self.Path
}
$directory

Compare two files

CLS
$file1 = Read-Host "Full path to file1"
$file2 = Read-Host "Full path to file2"
 
# show only duplicates
Write-Host "`n Duplicates:" -ForegroundColor yellow
Compare-Object $(Get-Content $file1) $(Get-Content $file2) -includeequal | ?{$_.SideIndicator -eq "=="} | Select InputObject
 
# show only unique objects in the first file
Write-Host "`n Unique to file1 ( $file1 ):" -ForegroundColor yellow
Compare-Object $(Get-Content $file1) $(Get-Content $file2) | ?{$_.SideIndicator -eq "<="} | Select InputObject
 
# show only unique objects in the second file
Write-Host "`n Unique to file2 ( $file2 ):" -ForegroundColor yellow
Compare-Object $(Get-Content $file1) $(Get-Content $file2)  | ?{$_.SideIndicator -eq "=>"} | Select InputObject
 
# show only unique objects
Write-Host "`n All unique objects across both files:" -ForegroundColor yellow
Compare-Object $(Get-Content $file1) $(Get-Content $file2)  | ?{$_.SideIndicator -ne "=="} | Select InputObject

Select first or last objects

ls | select -first 3
ls | select -last 30

Delete user profile

# Remove entire Windows user profile for $user
$user = "donald.trump"
$profiles = $null
$profiles = Get-WMIObject -class Win32_UserProfile | Where {$_.LocalPath -eq "C:\Users\$user"}
if ($profiles -ne $null) {
    $profiles | Remove-WmiObject -Verbose
}

Chain commands (run multiple commands from one line sequentially)

ipconfig /release ; ipconfig /renew

Create a multiline input box

Use this for a list of PCs etc, instead of having to get-content

#create multiline input dialog box
function Read-MultiLineInputBoxDialog([string]$Message, [string]$WindowTitle, [string]$DefaultText)
{

    Add-Type -AssemblyName System.Drawing
    Add-Type -AssemblyName System.Windows.Forms
    
    # Create the Label.
    $label = New-Object System.Windows.Forms.Label
    $label.Location = New-Object System.Drawing.Size(10,10)
    $label.Size = New-Object System.Drawing.Size(280,20)
    $label.AutoSize = $true
    $label.Text = $Message
    
    # Create the TextBox used to capture the user's text.
    $textBox = New-Object System.Windows.Forms.TextBox
    $textBox.Location = New-Object System.Drawing.Size(10,40)
    $textBox.Size = New-Object System.Drawing.Size(575,200)
    $textBox.AcceptsReturn = $true
    $textBox.AcceptsTab = $false
    $textBox.Multiline = $true
    $textBox.ScrollBars = 'Both'
    $textBox.Text = $DefaultText
    
    # Create the OK button.
    $okButton = New-Object System.Windows.Forms.Button
    $okButton.Location = New-Object System.Drawing.Size(415,250)
    $okButton.Size = New-Object System.Drawing.Size(75,25)
    $okButton.Text = "OK"
    $okButton.Add_Click({ $form.Tag = $textBox.Text; $form.Close() })
    
    # Create the Cancel button.
    $cancelButton = New-Object System.Windows.Forms.Button
    $cancelButton.Location = New-Object System.Drawing.Size(510,250)
    $cancelButton.Size = New-Object System.Drawing.Size(75,25)
    $cancelButton.Text = "Cancel"
    $cancelButton.Add_Click({ $form.Tag = $null; $form.Close() })
    
    # Create the form.
    $form = New-Object System.Windows.Forms.Form
    $form.Text = $WindowTitle
    $form.Size = New-Object System.Drawing.Size(610,320)
    $form.FormBorderStyle = 'FixedSingle'
    $form.StartPosition = "CenterScreen"
    $form.AutoSizeMode = 'GrowAndShrink'
    $form.Topmost = $True
    $form.AcceptButton = $okButton
    $form.CancelButton = $cancelButton
    $form.ShowInTaskbar = $true
    
    # Add all of the controls to the form.
    $form.Controls.Add($label)
    $form.Controls.Add($textBox)
    $form.Controls.Add($okButton)
    $form.Controls.Add($cancelButton)
    
    # Initialize and show the form.
    $form.Add_Shown({$form.Activate()})
    $form.ShowDialog() > $null   # Trash the text of the button that was clicked.
    
    # Return the text that the user entered.
    return $form.Tag
}

#show input box and gather multiline input
$code = Read-MultiLineInputBoxDialog -Message "Enter your multiline values"  -WindowTitle "Input" 

#exit if user cancels
if ($code -eq $null) { Write-Host "You cancelled!" -ForegroundColor yellow
EXIT}

# continue processing if user said OK, output the $code (the input)
else {
$code
}

Install fonts

$fonts = (New-Object -ComObject Shell.Application).Namespace(0x14)
dir C:\temp\fonts\*.ttf | %{ $fonts.CopyHere($_.fullname) }

IPConfig/get IP address/subnet/DNS etc

# PowerShell cmdlet to interrogate the Network Adapter
$colItems = Get-WmiObject -class "Win32_NetworkAdapterConfiguration" | Where {$_.IPEnabled -Match "True"}
foreach ($objItem in $colItems) {
   Write-Host "--------"
   Write-Host "Hostname: " `t $objItem.DNSHostName
   Write-Host "IPAddress(s): " `t  $objItem.IPAddress
   Write-Host "Subnet(s): " `t  $objItem.IPSubnet
   Write-Host "Gateway: " `t $objItem.DefaultIPGateway
   Write-Host "DNS Servers: " `t $objItem.DNSServerSearchOrder
   Write-Host "Domain name: " `t $objItem.DNSDomain
   Write-Host "DHCP Enabled?:  "  $objItem.DHCPEnabled
   Write-Host "MAC Address: " `t $objItem.MACAddress
 }

Resolve IP address to hostname(ping -a)

[System.Net.Dns]::GetHostbyAddress("10.80.12.12") 

Resolve hostname to IP address

[System.Net.DNS]::GetHostAddresses("laptop14.domain.com").IPaddresstostring

Show all disks with used/free space plus percent used %

get-psdrive|%{
If ($_.Used){
$_|select Name, @{name=’Used’;Expression={"{0:N2}" -f ( $_.Used/1GB)}}, @{name=’Free’;Expression={ "{0:N2}" -f ($_.Free/1GB)}}, @{name=’% full’;Expression={"{0:N2}" -f ($_.Used / ($_.Used + $_.Free) * 100 )}}
}
}

Password generator

Add-Type -AssemblyName System.Web
[System.Web.Security.Membership]::GeneratePassword(10, 3)

Generate a random number between 1 and 50000

get-random -min 1 -max 50000

Take/restore ownership of files/folders

# Takes ownership (takeown) of a file or folder including subdirs, with no prompts
$Path = Read-Host "Full path to folder to take ownership (eg \\computername\c$\FOLDER)"
takeown /f $Path /r /d y
icacls $Path /grant administrators:F /t

Compress files using NTFS compression

$folder = Read-Host "Folder path?"
# search for uncompressed files
$files = ls -path $folder |?{$_.attributes -notmatch "Compressed"}
ForEach ($file in $files) {
$task = "compact.exe /c"
CMD /C $task
}

sCleaner – Removes temp files/logs etc and shows space saved

# v29 May 2017 @ 1pm
# store original window title
$title = $host.ui.RawUI.WindowTitle

# gather disk utilisation of C:\ drive before cleaning in bytes
$freebefore = get-WmiObject win32_logicaldisk | ? {$_.deviceID -eq "C:"} | Select -expandproperty FreeSpace

# Remove error reports older than 30 days
$host.ui.RawUI.WindowTitle = "INFO: Removing old error reports"
Remove-Item -Path "C:\ProgramData\Microsoft\Windows\WER\ReportQueue\*" -ErrorAction SilentlyContinue -force -verbose -recurse | Where-Object {$_.LastwriteTime -lt  (Get-Date).AddDays(-30) }

# Remove temp files older than 30 days
$host.ui.RawUI.WindowTitle = "INFO: Removing old windows temp files"
Remove-Item -Path "C:\WINDOWS\Temp\*" -ErrorAction SilentlyContinue -force -recurse -verbose | Where-Object {$_.LastwriteTime -lt  (Get-Date).AddDays(-30) }

# Empty the recycle bin
$host.ui.RawUI.WindowTitle = "INFO: Putting the bins out"
ls -force -recurse -path c:\'$recycle.bin' -ErrorAction SilentlyContinue | Where-Object {$_.LastwriteTime -lt  (Get-Date).AddDays(-30) } | remove-item -force -recurse -ErrorAction SilentlyContinue -verbose

# Remove temp files older than 30 days across all users' profiles
foreach ($user in ls C:\users){
$host.ui.RawUI.WindowTitle = "INFO: Removing temp files from user profiles"
Write-Host "USER: $user is being cleared of temp files" -ForegroundColor Yellow
Remove-Item -Path "C:\Users\$user\AppData\Local\Temp\*" -ErrorAction SilentlyContinue -force -recurse -verbose | Where-Object {$_.LastwriteTime -lt  (Get-Date).AddDays(-30) }
Remove-item -Path "C:\Users\$user\AppData\Local\Microsoft\Windows\Temporary Internet Files\*" -ErrorAction SilentlyContinue -force -verbose -recurse | Where-Object {$_.LastwriteTime -lt  (Get-Date).AddDays(-30) }
Remove-item -Path "C:\Users\$user\AppData\Local\Microsoft\Windows\WER\*" -ErrorAction SilentlyContinue -force -verbose -recurse | Where-Object {$_.LastwriteTime -lt  (Get-Date).AddDays(-30) }
Remove-item -Path "C:\Users\$user\AppData\Local\CrashDumps\*" -ErrorAction SilentlyContinue -force -verbose -recurse | Where-Object {$_.LastwriteTime -lt  (Get-Date).AddDays(-30) }
}

# Remove IIS .log files older than 90 days
$host.ui.RawUI.WindowTitle = "INFO: Removing old IIS log files"
Get-ChildItem -Path "C:\inetpub\logs\LogFiles\" -Include *.log -Recurse -force -ErrorAction SilentlyContinue | where {$_.LastwriteTime -lt  (Get-Date).AddDays(-90) } | Remove-Item -Verbose -Force -Recurse -ErrorAction SilentlyContinue

$freeafter = get-WmiObject win32_logicaldisk | ? {$_.deviceID -eq "C:"} | Select -expandproperty FreeSpace

# do sums before converting to GB
$saved = $freebefore - $freeafter

# convert variables to GB
$freebefore = [math]::round($freebefore /1Gb, 2)
$freeafter = [math]::round($freeafter /1Gb, 2)
$saved = [math]::round($saved /1Gb, 2)
# remove negative symbol (hack!)
$saved = $saved -replace "-",""

# show me the money
Write-Host "Free space before (GB): $freebefore" -fore green
Write-Host "Free space after cleanup (GB): $freeafter" -fore green
Write-host "Saved space (GB) = $saved" -fore green

# Return original window title
$host.ui.RawUI.WindowTitle = "$title"

Convert negative number to positive/replace text

$number = "-40"
$number = $number -replace "-",""

Show services that should be running but have stopped

Get-WmiObject win32_service | Where-Object -FilterScript { $_.state -ne "Running" -and $_.StartMode -eq "Auto" } | Select-Object name

Activate MS Office via commandline/remotely via PSExec

psexec \\computername cmd.exe
cd c:\program files (x86)\microsoft office\office15\
C:\Program Files (x86)\Microsoft Office\Office15>cscript ospp.vbs /inpkey:#####-#####-#####-#####-#####
C:\Program Files (x86)\Microsoft Office\Office15>cscript ospp.vbs /act
C:\Program Files (x86)\Microsoft Office\Office15>cscript ospp.vbs /dstatus

Check to see if HOSTS file has been modified

if( (get-item C:\Windows\System32\drivers\etc\hosts).length -ne "824")
{
Write-warning "Someone's been messing with the hosts file!"
cat C:\Windows\System32\drivers\etc\hosts | select -last 15
}

Test ports (telnet/nmap equivalent) (Win2012+/PS3+)

# Test specific ports, report success and failure
($ports = 80,135,3389,445) | ForEach-Object {Test-NetConnection -computer mepdom02 -port $_ -InformationLevel detailed }

# Test a range of ports from 1 to 100, only report failures
$ports = 1..100 | ForEach-Object {Test-NetConnection -computer localhost -port $_ }
# Test a range of ports from 1 to 100, report success and failures
($ports = 1..100) | ForEach-Object {Test-NetConnection -computer localhost -port $_ }

Search DNS records for hostname/IP across all zones

$server = $env:COMPUTERNAME
# Find DNS records that match an IP
Get-DnsServerZone -computername "$server" | Get-DnsServerResourceRecord -computername "$server"  | where {$_.recorddata.ipv4address -like "172.20.2.104"} 
# Find DNS records that match a hostname
Get-DnsServerZone -computername "$server" | Get-DnsServerResourceRecord -computername "$server"  | where {$_.RecordData.HostNameAlias -like "ServerDC01*"}

Ping a range of IPs/Subnet (Angry Powershell IP Scanner)

Warning, this is slow, could take 20min to ping 255 IPs

# Start address (usally 1)
$i = 1
$AddrIP = "10.7.103."
Do { $IpHost = $AddrIP + $i
IF (Test-Connection -Count 1 -ComputerName $iphost -ErrorAction SilentlyContinue ){
Try{
$hostname = [System.Net.Dns]::GetHostbyAddress("$iphost") | select -expandproperty hostname
}
Catch
{
}
Write-Host "$IPhost is up, DNS name (if available) is: $hostname" -ForegroundColor Green
}
ELSE
{
Write-Host "$IpHost is down" -foregroundcolor Red
}
$i++
}
until ($i -eq 255)

Show where Windows is getting its time from

Add DNS search suffix

# Add multiple DNS Suffixes (append)
$DNSsuffixes =  “Contoso.com”,”Child.Contoso.com”
invoke-wmimethod -Class win32_networkadapterconfiguration -Name setDNSSuffixSearchOrder -ArgumentList @($DNSSuffixes),$null 

# Add just a single DNS suffix (overwrite)
Invoke-WmiMethod -Class win32_networkadapterconfiguration -Name setDNSSuffixSearchOrder -Argument "contoso.com"

Set service to start automatically

Set-Service -Name w32time -StartupType Auomatic

Disable Windows firewall

# Win8/2012 +
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
# Win7/2008
netsh advfirewall set allprofiles state off

Enable RDP

set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 0

Bypass proxy in powershell

(New-Object System.Net.WebClient).Proxy.Credentials =  [System.Net.CredentialCache]::DefaultNetworkCredentials

Test LDAP/username/password


# Define AD server and domain 
$ServerName = "DC1"
$Port = 389
$domain = "DOMAINNAME"

#Load the assemblies 
[System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.Protocols") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.Net")  | Out-Null

$dn = "$ServerName"+":"+"$Port" 
$c = New-Object System.DirectoryServices.Protocols.LdapConnection "$dn" 
$c.SessionOptions.SecureSocketLayer = $false; 
$c.SessionOptions.ProtocolVersion = 3 

$c.AuthType = [System.DirectoryServices.Protocols.AuthType]::Kerberos

$credentials = Get-Credential -UserName "$domain\" -Message "Enter username/password to test:"

Try
{
$c.Bind($credentials); 
Write-Host "SUCCESS: Username and password authenticated to LDAP" -ForegroundColor Green
} 
catch 
{ 
Write-Host "FAIL: $_.Exception.Message" -ForegroundColor Red
} 

List services and their logon accounts

Get-WmiObject -Class Win32_Service | ?{ ($_.startname -notmatch "NT AUTHORITY") -and ($_.startname -notmatch "localsystem") } |select displayname, startname

Find words/text across multiple files

ls -Path "C:\" -Recurse -Force  | Select-String -pattern "credit card number" | group path | select name

Run command multiple times (one liner), in 10 second interval

1..10 | % { get-process httpd -ea SilentlyContinue; Start-Sleep -Seconds 10 }

Find text/string in multiple files

Get-ChildItem -recurse | Select-String -pattern "password" | select path, linenumber, line

List local adminsitrators

Alternative to NET LOCALGROUP ADMINISTRATORS

([ADSI]"WinNT://localhost/Administrators,group").Members() | % { ([ADSI]$_).Path.Substring(8) }

Create a DNS A record (including PTR)

$name = "SERVER01"
$ip = "10.0.0.3"
$fqdn = "domain.com"
# Create A record + associated PTR
Add-DnsServerResourceRecordA -ZoneName $fqdn -Name $name -IPv4Address $ip -CreatePtr -Verbose

Create PTR Record

# Create PTR record
$name = "SERVER01"
$ip = "10.0.0.3"
$fqdn = "domain.com"

$split = $ip.Split(".")
$zone = $split[2] + "." + $split[1] + "." + $split[0] + ".in-addr.arpa"

Add-DnsServerResourceRecordPtr -ZoneName $zone -Name $name -PtrDomainName $fqdn

Date picker

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 

$objForm = New-Object Windows.Forms.Form 

$objForm.Text = "Select start Date" 
$objForm.Size = New-Object Drawing.Size @(190,190) 
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True

$objForm.Add_KeyDown({
    if ($_.KeyCode -eq "Enter") 
        {
            $startDate=$objCalendar.SelectionStart
            $objForm.Close()
        }
    })

$objForm.Add_KeyDown({
    if ($_.KeyCode -eq "Escape") 
        {
            $objForm.Close()
        }
    })

$objCalendar = New-Object System.Windows.Forms.MonthCalendar 
$objCalendar.ShowTodayCircle = $true
$objCalendar.MaxSelectionCount = 1
$objForm.Controls.Add($objCalendar) 

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})  
[void] $objForm.ShowDialog() 



# Select end date
$objForm = New-Object Windows.Forms.Form 
$objForm.Text = "Select end Date" 
$objForm.Size = New-Object Drawing.Size @(190,190) 
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True

$objForm.Add_KeyDown({
    if ($_.KeyCode -eq "Enter") 
        {
            $enddate=$objCalendar.SelectionStart
            $objForm.Close()
        }
    })

$objForm.Add_KeyDown({
    if ($_.KeyCode -eq "Escape") 
        {
            $objForm.Close()
        }
    })

$objCalendar = New-Object System.Windows.Forms.MonthCalendar 
$objCalendar.ShowTodayCircle = $true
$objCalendar.MaxSelectionCount = 1
$objForm.Controls.Add($objCalendar) 

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})  
[void] $objForm.ShowDialog() 

$startdate
$enddate

Result picker

Similar to Out-Gridview -Passthru. This example lets you pick an process from a list box (from Get-Process)

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 

$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Mailboxes matching $mailbox"
$objForm.Size = New-Object System.Drawing.Size(300,200) 
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {$x=$objListBox.SelectedItem;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
    {$objForm.Close()}})

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objListBox.SelectedItem;$objForm.Close()})
$objForm.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Please select a result:"
$objForm.Controls.Add($objLabel) 

$objListBox = New-Object System.Windows.Forms.ListBox 
$objListBox.Location = New-Object System.Drawing.Size(10,40) 
$objListBox.Size = New-Object System.Drawing.Size(260,20) 
$objListBox.Height = 80


Get-Process | ForEach-Object {[void] $objListBox.Items.Add($_)}


$objForm.Controls.Add($objListBox) 

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

$x