These are collected for my own reference and should not be taken as complete or entered without some understanding of the ramifications.
Where possible, I’ve included my source of info, which should be referenced for more context. In most cases, the CMD version works in PS; PS commands will not work in CMD
Have a suggestion? Send it to tips@ajones.xyz and check back soon.


Contributors:

This space reserved for contributors requesting general credit, which is happily given!


(WIN) System utilities by executable

ctrl+shift+enter to run as admin (usually works)
Sometimes requires shift-rightClick - Run as another user (then use admin)

(CMD) Disk Defrag

defrag [volume] /A /U /V
defrag [volume] /D /U /V
defrag /C

(CMD) Get and run command history

F7 for interactive display of history
F8 for in-line selection

(CMD) Take ownership of a directory and files (see also: icacls)

takeown /f x:\path\to\file /r /d y
takeown /f x:\path\to\file /a /r /d y

Current user takes ownership of the folder and contents / Administrators group takes ownership of the folder and contents

(CMD) Get, add file security permissions (icacls)

icacls \\path\to\file /grant "domain\user":[permission level] /t
icacls c:\tmp\note.csv /grant "HQ\ajones":M
icacls C:\temp\notesdir /setowner "hq\ajones" /t

Recursively takes ownership of the directory notesdir

(CMD) Pipe multiple lines to a file

(echo line1
 echo line2
 echo line3
     .     
     .     
     .     
) > x:\path\to\file.txt

(CMD) Get installed updates from command line

wmic qfe list

(CMD) Uninstall windows updates by kb

wusa /uninstall /kb:#######

(CMD) Get SFC Scannow results from cbs.log

findstr /c:"[SR]" %windir%\logs\cbs\cbs.log > C:\temp\sfc_result.txt

(CMD) Get NTP time details, set details, etc with w32tm

Get the current time source information with w32tm

c:\windows\system32\w32tm.exe /query /status
c:\windows\system32\w32tm.exe /query /configuration
c:\windows\system32\w32tm.exe /query /source
c:\windows\system32\w32tm.exe /stripchart /computer:remote.time.server.tld

Set a new time source

  1. c:\windows\system32\w32tm.exe /config /syncfromflags:manual /manualpeerlist:"pool.ntp.org time.nist.gov" /reliable:yes /update
  2. net stop w32time
  3. net start w32time
  4. w32tm /resync /force

(CMD) Uninstall drivers from command line

pnputil -e
pnputil -f -d xxxxx.info

(CMD) Update assigned group policies, show assigned group policies

gpupdate /force
gpupdate /force /target:user
gpupdate /force /target:computer
gpresult /r
gpresult /r /user Username
gpresult /r /s [Hostname|IP]
gpresult /r /scope:[user|computer]

(CMD) List connected RDS sessions

qwinsta
query user

(CMD) DCDIAG example

dcdiag /c /v /f:c:\temp\dcdiag_result.TXT

(CMD) Get logon server (DC authenticating to)

echo %logonserver%

(CMD) Add network printer from command line

rundll32 printui.dll PrintUIEntry /ga /n "\\path\to\printer"

(CMD) Run As example

runas /user:administrator@domain.tld /noprofile cmd.exe

(CMD) Remove installed Office 365 licenses from apps (eg, after license change/downgrade)

  1. cscript "%Programfiles%\Microsoft Office\Office16\OSPP.VBS" /dstatus
  1. cscript "%Programfiles%\Microsoft Office\Office16\OSPP.VBS" /unpkey:<key>

(CMD) Echo hostname with domain (for logged in user)

echo %COMPUTERNAME%.%USERDNSDOMAIN%

(CMD) Command line script wrapper

cscript [path\to\script] [/script options]

(CMD) Manage windows license activations from command line (see CSCRIPT)

slmgr.vbs /ipk [windows-key-here]
slmgr.vbs /ato
slgmr.vbs /xpr

(CMD) Windows License Manager UI:

slui [1|2|3|4]
slui 3

(CMD) Get logged in user, log off user:

query user /server:[hostname/ip]
logoff [sessionID]

(CMD) Remote sysinfo:

systeminfo[.exe] [/s Computer [/u Domain\User [/p Password]]] [/fo {TABLE|LIST|CSV}] [/nh]

Where: - /fo { TABLE | LIST | CSV } - Specifies the format to use for the output. Valid values are TABLE, LIST, and CSV. The default format for output is LIST.
- /nh - Suppresses column headers in the output. Valid when the /fo parameter is set to TABLE or CSV

(CMD) Get Win10 original license for HW:

wmic path softwarelicensingservice get OA3xOriginalProductKey

(CMD) Get remote interface names 1/2:

netsh -r (hostname/ip) interface ipv4 show interfaces

(CMD) Get local adapter interface names and info

wmic nic get Name,NetConnectionID,MACAddress

(CMD) Ipconfig release single network adapter

ipconfig /release [adapter name]

(CMD) Get Asset tag/serial:

wmic bios get serialnumber

(CMD) Get list of installed software

wmic product get name,version

(CMD) Manage Services:

net [start,stop] servicename
sc.exe config servicename start=disabled [disabled,auto,delayed-auto,demand(='manual')]
sc.exe delete servicename
sc query type= service
wmic service list config

(CMD) Kill processes command line

taskkill /f /im [processname.exe]
taskkill /f /im notepad.exe
taskkill /pid 1223 /pid 1224

(CMD) Overwrite a Windows password:

** NB - normal password change warnings apply! Encrypted content no longer accessible, saved credentials gone, etc. **

  1. Boot to a linux live distro or windows rescue media (assuming linux below because done in recent memory)
  2. Mount the windows filesystem (eg, mount /dev/sda1 /media/mount/winmount/)
  3. Navigate to Windows/System32
  4. Change sethc.exe to sethc.exe.bak (mv ./sethc.exe ./sethc.exe.bak)
  5. Copy cmd.exe to sethc.exe (cp ./cmd.exe ./sethc.exe)
  6. Undo mount (cd ~ ; umount /dev/sda1)
  7. Boot to windows
  8. Press shift 5 times (sticky keys - should now launch command prompt)
  9. At windows command prompt: net user <username> *
  1. Log in
  2. Reboot to live media
  3. Undo filesystem changes

(CMD) Command line user administration

Get local account information, including logon time and password last set

net user [username]

Get domain user account information

net user [username] /domain

nb; active: yes means unlocked.

Get password policy, min/max age, length, lockout duration

net accounts
net accounts /domain

Add local user

net user [username] * /add

Add user to local administrators group

net localgroup administrators [username] /add

Set the built-in administrator to enabled

net user administrator /active:yes

(CMD) Set local user password to never expire

wmic useraccount where “Name='username'” set PasswordExpires=false

(CMD) netstat - list listening ports

netstat -nbp [tcp|udp|tcp6|ICMP|ICMPv6]

(CMD) Hide / Add drive letter (eg for system partitions)

Hide it:

diskpart
select volume [volume letter or number]
remove letter [letter]

Add it back:

diskpart
select volume [volume number]
assign letter [volume letter]

(CMD) NSLookup quick reference

nslookup [name] [server]
nslookup -type=[record type] [name] [server]
nslookup -type=mx google.com 75.75.75.75
nslookup -debug host.site.tld

(CMD) add static route

route ADD [networkIP] MASK [subnetmask] [gatewayIP]
route ADD 192.168.30.0 MASK 255.255.255.0 192.169.20.2
route -p ADD [ip] MASK [mask] [gateway]
route delete [networkIP]
route delete 192.168.30.0

(CMD) create file of arbitrary size

fsutil file createnew \path\to\file.txt [size in bytes]
fsutil file createnew c:\temp\testfile.txt 2000000

Copy/Paste interactive command block for creating max 20 50kb files in current dir

update: read-host doesn’t work correctly in a copy-paste block. This is useful as a script or if pasted per-line, but would be better rewritten as a function with mandatory parameters

$name = read-host -prompt "Files basename?"
$count = read-host -prompt "Number of empty files?"
$size = read-host -prompt "Size of each file in b?"
if ($size -gt 50000){
$size = 50000
}
if ($count -gt 20){
$count = 20
}
for ($num=1; $num -le $count; $num++) {
fsutil file createnew $name$num $size
}

(CMD) Get disk info via WMIC

wmic diskdrive get /all /format:list

(CMD) PSexec.exe sample - where current directory is where psexec.exe exists, and remote computer has file locally

./psexec.exe \\[remotecomputername] "C:\path\to\remote\file"

(CMD) Query, Delete scheduled tasks from command line

schtasks /query /v /fo list [/u [domain\]user /p password]
schtasks /query /fo list /v | find "some string to match"
    schtasks /delete /tn [name of task] /f
    schtasks /create /tn reboot_once /tr "c:\windows\system32\shutdown.exe /r /t 60" /sc once /st 23:59 /rl highest /np /sd "02/22/2019"
schtasks /create /tn no_screenlock /tr "c:\temp\capslock.vbs" /sc minute /np

(CMD) Map a network drive from command line (net use /?)

net use [driveletter]: \\path\to\file /persistent:Yes
net use S: \\contoso-FS01\Scandocs /persistent:Yes

As .bat file:

@echo off
net use S: \\contoso-FS01\Scandocs
exit

(CMD) List mapped share drives

net use

(CMD) List shares (shared from computer)

net share

(CMD) Work with registry from command line - REG

reg query path\to\key
reg query hklm\software\microsoft\windows

Export registry keys

reg export keyname filename
reg export hklm\software\sonicewall c:\users\username\desktop\file.reg

Add registry keys

reg add key /v valuename /t datatype /d data
reg add HKLM\Software\Somename /v DataVal /t REG_DWORD /d 10010

(CMD) Manipulate network settings with netsh|MS

(CMD) Change IP settings from command line

netsh interface show interface
netsh interface ipv4 add dnsserver "interfacename" address=xxx.xxx.xxx.xxx index=#
netsh interface ip set dns "InterfaceName" static 123.123.123.123
netsh interface ip set [dns|address] "InterfaceName" dhcp

Show IP settings

netsh [command [sub-command]] /?
netsh interface show interface
netsh inteface ipv4 show ipstats

Set a firewall rule

Enable inbound ping (v4):
netsh advfirewall firewall add rule name="ICMP Allow incoming V4 echo request" protocol=icmpv4:8,any dir=in action=allow [ remoteip=ip1,ip2 ]
Enable inbound ping (v6):
netsh advfirewall firewall add rule name="ICMP Allow incoming V6 echo request" protocol=icmpv6:8,any dir=in action=allow [remoteip=ip1,ip2 ]
Enable inbound TCP on port 12345 from 127.0.0.1:
netsh advfirewall firewall add rule name="allow_inbound_TCP_port_12345" protocol=TCP dir=in localport=12345 action=allow remoteip=127.0.0.1 profile=Domain

(CMD) Get uptime

net stats workstation
(c:\windows\system32\) systeminfo.exe | find "Time:"

(CMD) Query installed drivers

driverquery /v /fo list

(BAT) Self reference a script or path

"%~dp0"
"%~f0"

(CMD) DISM commands

dism.exe /online /cleanup-image /checkhealth
dism.exe /online /cleanup-image /scanhealth
dism.exe /online /cleanup-image /restorehealth
dism.exe /online /cleanup-image /restorehealth /source:d:\path\to\source\windows

(CMD) Run control panel and sub-items directly

control.exe
control.exe printers
control.exe /name canonical.name
control.exe /name microsoft.networkandsharingcenter

(PS) List and access all control panel items

get-controlpanelitem
show-controlpanelitem [item]
show-controlpanelitem mail*

(PS) Get uptime from powershell

Get-WmiObject Win32_OperatingSystem | Select-Object LastBootUpTime
systeminfo.exe | select-string "Time:"

(PS) List connected RDS sessions

get-rdusersession

(PS) Watch a command (eg, run it repeatedly and show updated result)

while (1) {command | out-host;sleep 5;clear}

(PS) Repeat a task N times with for loop increment

for ($i=1; $i -le 10; $i++) {do something}

(PS) Measure how much time a command takes to complete

measure-command {command goes here}
measure-command {get-childitem}
measure-command {command|out-default}

(PS) Get count and sum of files, sizes

get-childitem | measure-object -sum length

(PS) Recursively get files newer than N days

Get-ChildItem -Path . -Recurse| ? {$_.LastWriteTime -gt (Get-Date).AddDays(-3)}

(PS) Get command history, run (“invoke”) command history

history
invoke-history [command index]

(PS) Generic output filtering

some command | ft property1,property2
some command | fl property1, property2

Example Output of “ps | ft” vs “ps | fl” (where ps = get-process)

As list:

Id : 12480 Handles : 795 CPU : 47.203125 SI : 1 Name : Zoom

As table:

Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName 795 111 45084 10176 47.36 12480 1 Zoom

(PS) DISM commands in powershell

repair-windowsimage -checkhealth
repair-windowsimage -scanhealth
repair-windowsimage -restorehealth

(PS) Find content in results with context (equivalent to “find” in CMD)

[some command] | select-string -pattern SearchString -context 2,4

(PS) List SMB shares (shared from computer)

get-smbshare

(PS) Get user mapped drives from registry

$usersid = (User's SID identifier here. Use gci hku:\ for possible matches)
get-childitem -path HKCU:\$usersid\

(PS) Get processeses / sorted descending by cpu use:

get-process [ProcessName]
get-process Notepad
ps Notepad
get-process -computername [name or ip] | sort-object [object] -descending[/ascending]

(PS) Get Win10 original license for HW:

powershell "(Get-WmiObject -query ‘select * from SoftwareLicensingService’).OA3xOriginalProductKey"

(PS) List services with path/executable

Get-WmiObject win32_service | ?{$_.Name -like '*searchstring_omit-to-list-all*'} | select Name, DisplayName, State, PathName
get-service

(PS) Remote powershell session:

Enter-PSSession Server01  (may work by name only)
exit-pssession

(PS) Get Hyper-V Host from guest:

(get-item "HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters")

(PS) Get Hyper-V Guests from Host

Get-VM
Get-VM -name [VMGuestName]
Get-VM -ComputerName [VMHostName]

(PS) Remote restart

PS C:\> Restart-Computer -ComputerName Server01

(PS) Get remote interface names/details including MAC 2/2:

get-netadapter -name * -cimsession <computername>
get-netadapter -name * -cimsession <computername>

(PS) Get graphics card device information

Get-WmiObject Win32_VideoController | Select description,driverversion

(PS) Get Registry values and sub-values filter by properties:

$Path = 'HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR\*\*'
Get-ItemProperty -Path $Path | Select-Object -Property FriendlyName, CompatibleIDs, Mfg
get-itemproperty -path HKLM:\System\CurrentControlSet\Services\* | select-object -Property ImagePath > path/to/file

(PS) Windows search filters:

* filename (date)created: MM/DD/YYYY (date)modified: MM/DD/YYYY size: GB,MB,KB Operators: < > = <= >= <>

(PS) Powershell get disk info:

Get-psdrive C
Get-psdrive C | select-object free,used

(PS) Get all connected drives

Get-psdrive -psprovider 'filesystem'
gdr -psprovider 'filesystem'

(PS) Physical disk health and info:

Get-PhysicalDisk
Get-PhysicalDisk –FriendlyName PhysicalDisk1 | Get-StorageReliabilityCounter
Get-PhysicalDisk | Get-StorageReliabilityCounter | ft deviceid,temperature,wear
Get-PhysicalDisk | Sort Size | FT FriendlyName, Size, MediaType, SpindleSpeed, HealthStatus, OperationalStatus -AutoSize

(PS) Get files matching name CAB_* and last modified older than 10 days ago (today -10):

$cabfiles= get-childitem c:\windows\temp | where-object {$_.name -like "CAB_*" AND $_.lastwritetime -lt (Get-Date).adddays(-10)}

(PS) Ask for URL, then start google instance with tabs and search multiple sites:

    $url = Read-Host -Prompt "Enter Url to Search"
    start-process "chrome.exe" "https://www.urlscan.io","https://whois.icann.org/en/lookup?name=$url","https://toolbox.googleapps.com/apps/dig/#ANY/$url","https://transparencyreport.google.com/safe-browsing/search?url=$url", '--profile-directory="Guest"'

(PS) Stop Process by name/PID/other:

stop-process -name <string>

(PS) Powershell file hash / checksum:

get-filehash -algorithm [md5,sha256,etc] file
(get-filehash ...).hash
(get-filehash -algorithm sha256 testfile.txt).hash

(PS) Diff text:

diff (cat file1) (cat file2)

(PS) Tail a file

get-content path\to\file -tail 20 -wait
get-content path\to\file | select-object -last 20

(PS) Output powershell result to a grid view window with filtering

do-something | output-gridview
do-something | ogv

(PS) Reinstall Windows 10 default apps:

Get-AppXPackage | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppXManifest.xml"}

(PS) Execute Powershell with the Bypass Execution Policy (use RemoteSigned instead):

powershell –ExecutionPolicy Bypass

(PS) Powershell O365 session:

  1. Install EXO V2 (with executionpolicy = remotesigned):
Install-Module PowershellGet -Force
Install-Module -Name ExchangeOnlineManagement
Connect-ExchangeOnline -userprinciplename [user@domain.tld]
----------------------------------------------------------------------------
We have released new management cmdlets which are faster and more reliable.

|--------------------------------------------------------------------------|
|    Old Cmdlets                    |    New/Reliable/Faster Cmdlets       |
|--------------------------------------------------------------------------|
|    Get-CASMailbox                 |    Get-EXOCASMailbox                 |
|    Get-Mailbox                    |    Get-EXOMailbox                    |
|    Get-MailboxFolderPermission    |    Get-EXOMailboxFolderPermission    |
|    Get-MailboxFolderStatistics    |    Get-EXOMailboxFolderStatistics    |
|    Get-MailboxPermission          |    Get-EXOMailboxPermission          |
|    Get-MailboxStatistics          |    Get-EXOMailboxStatistics          |
|    Get-MobileDeviceStatistics     |    Get-EXOMobileDeviceStatistics     |
|    Get-Recipient                  |    Get-EXORecipient                  |
|    Get-RecipientPermission        |    Get-EXORecipientPermission        |
|--------------------------------------------------------------------------|

To get additional information, run: Get-Help Connect-ExchangeOnline
Please send your feedback and suggestions to exocmdletpreview@service.microsoft.com
----------------------------------------------------------------------------

// — do things — //

disconnect-exchangeonline

Example Things to Do

Manage calendar permissions:

Get-MailboxFolderPermission username:\calendar
Get-Mailbox –database mbxdbname| ForEach-Object {Get-MailboxFolderPermission $_”:\calendar”} | Where {$_.User -like “Default”} | Select Identity, User, AccessRights
Add-MailboxFolderPermission -Identity user1@domain.com:\calendar -user user2@domain.com -AccessRights Editor
Get-Mailbox –database mbxdbname | ForEach-Object {Set-MailboxFolderPermission $_”:\calendar” -User Default -AccessRights Reviewer}
Remove-MailboxFolderPermission -Identity user1@domain.com:\calendar –user user2@domain.com
Get-Mailbox -Filter {recipienttypedetails -eq "SharedMailbox"} | Set-Mailbox -HiddenFromAddressListsEnabled $true
Calendar permission types:

Get mailbox rules and rule settings:

get-inboxrule -mailbox user@domain.com -IncludeHidden | select -property * > \\path\to\file.txt

Get all user inbox rules:

get-mailbox -resultsize unlimited  |
foreach {
    Write-Verbose "Checking $($_.alias)..." -Verbose
    $inboxrule = get-inboxrule -Mailbox $_.alias  
    if ($inboxrule) {
        foreach($rule in $inboxrule){
        [PSCustomObject]@{
            Mailbox         = $_.alias
            Rulename        = $rule.name
            Rulepriority    = $rule.priority
            Ruledescription = $rule.description
        }
    }
    }
} |
Export-csv "$env:userprofile\desktop\export.csv" -NoTypeInformation

Get Recoverable Items count and quantity

Get-MailboxFolderStatistics <username> -FolderScope RecoverableItems | FL Name,FolderAndSubfolderSize,ItemsInFolderAndSubfolders
Get-MailboxFolderStatistics <username> -FolderScope RecoverableItems -Archive | FL Name,FolderAndSubfolderSize,ItemsInFolderAndSubfolders

Manage Archiving

Enable Archiving
Enable-Mailbox <user mailbox> -AutoExpandingArchive
Set-OrganizationConfig -AutoExpandingArchive
Check Archiving Status
Get-Mailbox <user mailbox> | FL AutoExpandingArchiveEnabled

Run managed folder assistant

start-managedfolderassistant -identity "user@domain.tld"

Work with mailboxes:

Get user mailboxes only
get-mailbox -recipienttypedetails usermailbox
List folders and properties including dates of newest and oldest items
Get-MailboxFolderStatistics -identity $userName -IncludeOldestAndNewestItems -folderscope Inbox | ft folderpath,oldestitemreceiveddate
get-mailboxfolderstatistics -identity $userName | ft name,folderpath,itemsinfolder,folderandsubfoldersize,archivepolicy
List all public folders [1] [2]
get-publicfolder -Identity "\" -Recurse
Get status of mailbox junk rule settings
get-mailboxjunkemailconfiguration -identity "user"
get-mailbox -recipienttypedetails usermailbox | get-mailboxjunkemailconfiguration | export-csv -path \\path\to\file

Enable modern authentication for 2FA in O365

set-organizationconfig -OAuth2ClientProfileEnabled $True
Get-OrganizationConfig | Format-Table Name,OAuth* -Auto

(PS) Get file from url

Invoke-WebRequest -Uri [URL] -OutFile [OutputDestFile]

(PS) DNS lookup from Powershell:

resolve-dnsname -name [hostname] -server [lookupserver]
resolve-dnsname -name [hostname] -type [ALL;A;TXT;MX;CNAME;PTR;NS;SOA;...etc]

(PS) Set Powershell TLS 1.2:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

(PS) Parse XML in powershell:

[xml]$somevar = get-content path\to\xml

OR

[xml]$somevar = wget (get-webrequest) url/to/xml/data
$somevar.nodeParent.nodeChild.nodeGrandchild
$somevar.dot.path.valuewithattribute.'#text' (read #text value from node that also has an attribute)

(PS) Create Hash Table in powershell:

$hash = @{}
$hash["<key>"]= "<value>"
$hash.clear()

(PS) Translate SID to User:

$objSID = New-Object System.Security.Principal.SecurityIdentifier ("ENTER-SID-HERE")
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
$objUser.Value

As one line:

([System.Security.Principal.SecurityIdentifier]("PUT-SID-HERE")).Translate([System.Security.Principal.NTAccount]).Value

(PS) Tee powershell output to two places:

do-thing | tee-object -filepath "\\path\to\file.txt" | do-more-things

(PS) Message trace from powershell O365

Get-MessageTrace -SenderAddress john@contoso.com -StartDate 06/13/2018 -EndDate 06/15/2018

(PS) Get file version from Powershell:

[System.Diagnostics.FileVersionInfo]::GetVersionInfo("path\to\file").FileVersion
[System.Diagnostics.FileVersionInfo]::GetVersionInfo("c:\windows\system32\TSpkg.dll").FileVersion

(PS) Test remote connection / port

test-netconnection -informationlevel "Detailed" -computername "$hostnameOrIP" -port $portNum

(PS) Get AD User / user info:

Import-Module ActiveDirectory
Get-ADUser -identity AccountName
Get-ADUser GlenJohn -Properties *  (return properties for user GlenJohn)
Get-ADUser -Filter * -SearchBase "OU=Finance,OU=UserAccounts,DC=FABRIKAM,DC=COM"   (return all users in the fabricam.com/UserAccounts/Finance OU)
get-aduser -filter ('Name -like '*fuzzyname*') | fl Name,UserPrincipalName
get-aduser -filter * -properties passwordlastset,passwordneverexpires | ft name,passwordlastset,passwordneverexpires
As a copy-paste script
$name=read-host -prompt "Look up what name?"
get-aduser -filter ("Name -like '*$name*'")
pause
Some available parameters:

[-AuthType ] [-Credential ] -Filter [-Properties <String[]>] [-SearchBase ] [-SearchScope ] [-Server ] []

(PS) Reset domain user password from PS

Set-ADAccountPassword -Identity EvanNa

Please enter the *current* password for 'CN=Evan Narvaez,CN=Users,DC=Fabrikam,DC=com'
Password:**********
Please enter the *desired* password for 'CN=Evan Narvaez,CN=Users,DC=Fabrikam,DC=com'
Password:***********
Repeat Password:***********

(PS) Manipulate local user accounts

get-localuser
set-localuser
    [-AccountExpires <DateTime>]
    [-AccountNeverExpires]
    [-Description <String>]
    [-FullName <String>]
    [-Name] <String>]
    [-Password <SecureString>]
    [-PasswordNeverExpires <Boolean>]
    [-UserMayChangePassword <Boolean>]
    [-WhatIf]
    [-Confirm]
rename-localuser
new-localuser
remove-localuser
Get-LocalGroupMember -Group "Administrators"
Add-LocalGroupMember -Group "Administrators" -Member "userName"

(PS) Get computer account last AD login date:

Import-Module Activedirectory
get-adcomputer -filter * -properties * | FT Name,LastLogonDate | Clip
get-adcomputer -filter * -properties * | where-object {$_.lastlogondate -gt (get-date).adddays(-90)} |FT Name,LastLogonDate
get-adcomputer -identity HOSTNAME [-properties *]
Excel: Filter AD results (whitespace separated) in A4 into two columns:

Left(name):

=LEFT(A4,FIND(" ",A4)-1)

Right(lastlogondate):

=TRIM(RIGHT(A4,LEN(A4)-LEN(B4)))

(PS) Get AD Locked Out Accounts

import-module activedirectory
search-adaccount -lockedout

Pipe to unlock:

search-adaccount -lockedout | unlock-adaccount -confirm

(PS) Get domain password requirements

get-addefaultdomainpasswordpolicy

(PS) Get group policy report

get-gpo -all | select-object -property "DisplayName"
get-gporeport -name $GPOName -reporttype XML -path "\\path\to\file"
get-gporeport -all -domain "$domain.tld" -reporttype HTML -path "\\path\to\file"

Search GPO Report from PS, without save to file:

$gpoReport = get-gporeport -name $gponame -reporttype xml
$gpoReport = $gpoReport.split("`n")
$gpoReport | select-string "searchterm" -simplematch

(PS) Get file/folder ACL permissions:

(get-acl <folder name>).access | ft IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -auto

(PS) DIR only directories, show only Name:

dir -directory | select-object Name

(PS) Force a network connection to a profile

Get-NetConnectionProfile
Set-NetConnectionProfile -InterfaceIndex <index number> -NetworkCategory Private

NB: Can’t be used to set a profile to Domain (“DomainAuthenticated”).

(PS) Robocopy example

robocopy /copyall /zb /e /R:2 /W:2 /V /np /LOG+:\\path\to\logfile /L C:\path\to\source C:\path\to\destination

(PS) Run, RunOnce Registry Key Paths (gi = Get-Item)

gi HKLM:\Software\Microsoft\Windows\CurrentVersion\Run
gi HKCU:\Software\Microsoft\Windows\CurrentVersion\Run
gi HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce
gi HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce

(PS) Read Event logs

get-eventlog -logname [System|Application|Security|etc]
-after (get-date -date '01/01/2001 00:00:00')
-before (get-date -date '01/30/2001 00:00:00')
-entrytype \[Error|Information|FailureAudit|SuccessAudit|Warning\]
-Newest \[number of events\]
-Message \[*searchstring*\]

Updated method get-winevent

get-winevent -logname System -MaxEvents 100 | sort-object TimeCreated | fl timecreated,ID,leveldisplayname,message,providername
get-winevent -providername *updateclient* | where-object {$_.message -like "*feature*"
Useful pipe example
&_ | Where-Object {$_.EventID -eq 63} | Select-Object -Property Source, ID, InstanceId, Message | ft -wrap > c:\temp\errorlog

(PS) Get public IP

Method 1

nslookup myip.opendns.com. resolver1.opendns.com

Method 2

wget diagnostic.opendns.com/myip | fl content

(PS) Simple IP scan on internal IP range

1..254 | ForEach-Object {Get-WmiObject Win32_PingStatus -Filter "Address='192.168.0.$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0" | select ProtocolAddress*}

(PS) Work with DHCP

get-dhcpserverindc
get-dhcpserverv4scope (-computername $[dhcpServer])
get-dhcpserverv4scopestatistics (-scopeid $[scopeID])
get-dhcpserverv4dnssetting -scopeID $[scopeID]
Get-DhcpServerv4Lease -scopeid $[scopeID]
get-dhcpserverv4lease -scopeid $[scopeID] -badleases

(PS) Get installed Updates

Get-HotFix | select-object hotfixid,installedon | sort installedon

(PS) Fix domain trust issue

Reset-ComputerMachinePassword -server $DCServerHostname -credential $domain\$user

(PS) Check if members of ListA are in ListB

$listA | where-object {$listB -notcontains $_}

(*NIX) Find stuff

find [path] -[opt] "[string]"
find ./ -iname "myfile*"

(*NIX) VIM; write current r/o file out as operation:

:w !sudo tee %
:q!

(*NIX) Dig (DNS Lookup) with trace

dig -4 domain.tld +trace | awk 'length($)<50'

(*NIX) Add and remove users from groups

usermod -a -G groupname username
usermod -g groupname username
gpasswd -d username groupname

(*) Useful Regex examples:

Email Address:  ([a-zA-Z0-9_\.-]+)@([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})
SSN:    ^\d{3}-?\d{2}-?\d{4}$
IP Addr:    ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$
Percentages: ([0-9]*\.*[0-9]+%)

(WIN) Enable 2FA in Outlook 2013

(WIN) Windows profile recreation:

Assumptions: computer has been rebooted, user has been warned about what’s about to happen, logged in as not-the-user with admin access.
  1. Rename c:\users\$username to ~.old
    1. Seeing more cases of files in use even with logged off user. Use Sysinternals’ Process Explorer, “Find”, enter path to profile, kill processes.
  2. Note last four of user’s corresponding reg key value (their SID) or the full Guid string in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\ProfileList\$userKey where ProfileImagePath matches the users’s profile path.
  3. Delete HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\ProfileList\$userKey
  4. Match the Guid or the SidString value and delete HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\Current Version\ProfileGuid\$userGuid
  5. Reboot (to restart any stopped processes and services in step 1a) and log in as the user - the profile directory will be recreated.
  6. Copy relevant data from old user profile to new profile, skipping appdata directories wherever possible. Remember to remap printers and drives (where not deployed by GPO), Outlook profiles, browser bookmarks (can be restored from Appdata), etc.

(WIN) Registry key and service for windows installer in safe mode:

REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\SafeBoot\Minimal\MSIServer" /VE /T REG_SZ /F /D "Service"
net start msiserver

(WIN) Win10 auto logon registry keys:

REG ADD "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AutoAdminLogon /t REG_SZ /d 1 /f
REG ADD "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultDomainName /t REG_SZ /d $**DOMAIN.TLD** /f
REG ADD "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultUserName /t REG_SZ /d $**USERNAME** /f
REG ADD "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword /t REG_SZ /d $**PASSWORD** /f

(WIN) Enable remote desktop on a manageable remote computer

  1. Manage - Services - Start Remote Registry
  2. Regedit - Connect network registry - [$Computer]
  3. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server
  4. Set fDenyTSConnections to 0

(WIN) Windows firewall log location

C:\Windows\System32\LogFiles\Firewall\pfirewall.log

() Outlook sent items in sender, not delegated sent folder

  1. Regedit
  2. HKEY_CURRENT_USER\Software\Microsoft\Office\$**x.0**\Outlook\Preferences
  3. New DWORD Value DelegateSentItemsStyle=1

(*NIX) Centos Firewalld rules:

sudo firewall-cmd --get-default-zone
sudo firewall-cmd --set-default-zone=[value]
sudo firewall-cmd --get-services
sudo firewall-cmd --zone=public --add-service=http --permanent
sudo firewall-cmd --zone=public --remove-service=http --permanent
sudo firewall-cmd --zone=public --add-port=12345/tcp --permanent
sudo firewall-cmd --zone=public --remove-port=12345/tcp --permanent

() Sonicwall CLI, enabling http management on interface

  1. SSH to sonicwall - Older version of sonicOS used in testing/discovery - login required login, username, password, where login used was admin
  2. user: (admin username)
  3. pass: (admin pass)
config
web-management allow-http
interface X0 (# or needed interface)
no https-redirect enable
management http enable
finished
exit

also useful:

show ?
show device
show status
show system

(WEB) PortQuiz.net - Test outbound port traffic

http://portquiz.net:1234

(WEB) Office Configuration Tool - create xml configs for deploy

https://config.office.com/

(WEB) Password generator with configurable parameters

https://passwordsgenerator.net/plus/

(WEB) Temporary throw-away mail, useful for trial software or “free with email account”

https://www.10minutemail.com

(WEB) Expand SPF and get DNS query count

https://emailstuff.org/spf/check

(WEB) Scan an URL, get sandboxed image of destination

https://urlscan.io

(WEB) Test regex strings, with info:

https://regexr.com

(WEB) Descriptive explanation of shell commands:

https://explainshell.com

(WEB) Test mail for config errors

https://www.mail-tester.com/

(WEB) Gmail search filter reference

https://support.google.com/mail/answer/7190?hl=en - note that “Primary” (eg, the default view of the Inbox) is a category

(WEB) Multi OS visual click-through guides:

https://www.chasms.com

(WEB) *nix abbreviated (tl;dr) man pages

https://tldr.sh/

(WEB) Chrome search string for Splunk:

http://IP:PORT/en-US/app/search/search?q=%s

(WEB) IT Pro Tuesday - crowd-sourced list of useful stuff

https://www.everycloud.com/it-pro-tuesdays

(WEB) Chrome Custom Search Shortcuts (These can be added as bookmarks with keywords in Firefox as well)


(MAC) Create a local admin user:

Tested to work for allowing authentication for admin privileges, but not for login. Anticipated to work with full login if no exclusions made.

dscl . create /Users/administrator
dscl . create /Users/administrator RealName "Administrator Account"
dscl . passwd /Users/administrator thisistheaccountpassword
dscl . list /Users UniqueID
dscl . create /Users/administrator UniqueID [UID]
dscl . create /Users/administrator PrimaryGroupID 80
dscl . create /Users/administrator UserShell /bin/bash
dscl . create /Users/administrator NFSHomeDirectory /Users/administrator
cp -R /System/Library/User\ Template/English.lproj /Users/administrator
chown -R administrator /Users/administrator
dseditgroup -o edit -a administrator -t user admin

(WIN) Sendkeys - script sending keys to system (save as .vbs)

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.sendkeys "{SCROLLLOCK}"

(WIN) Group Policy for shared sessions in Kaseya

Computer Configuration -> Administrative Templates -> Windows Components -> Remote Desktop Services -> Remote Desktop Session Host -> Connections -> Set Rules for Remote Control of Remote Desktop Services User Sessions