Skip to content

Instantly share code, notes, and snippets.

@Celoxocis
Created February 14, 2018 13:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Celoxocis/b87733dc0f1f18aafbfff0b9c9aeb53d to your computer and use it in GitHub Desktop.
Save Celoxocis/b87733dc0f1f18aafbfff0b9c9aeb53d to your computer and use it in GitHub Desktop.
Collection of handy PowerShell commands

PowerShell Commands

Sanity check (i.e., change term window size)

mode con:cols=150 lines=50

Set execution policy

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Unset execution policy

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Undefined

Run Windows Update

wuauclt /showwuautoscan

footzilla comments on ITT:Handy Commands You Might Not Know

Install cmdlet from PowerShell Gallery

Install-Module -Name "PSWindowsUpdate"

Get PowerShell Environment Variables

Get-Childitem -Path Env:* | Sort-Object Name

Reboot

Restart-Computer

PSRemoting

Enable-PSRemoting -Force Enter-PSSession -ComputerName dc-corp-1203 -Credential corp\lstephens

Enable PSRemoting How To Enable Powershell Remoting via Group Policy How to Run PowerShell Commands on Remote Computers

Grep Equivalent - sls (alias for Select-String)

ls * -r | sls 'ramesh’

Grep, the PowerShell way – Communary

Mount shared drive

New-PSDrive -Name "Z" -PSProvider FileSystem -Root "\\file-corp-1202\IT Apps" -Credential CORP\lstephens -Persist

Pipe to CSV

| Export-CSV "$home\Downloads\filename_$(get-date -f MMddyyyy_hhmmss).csv"

Sort as hash table

XYZ command -FilterHashtable

Full List of Users

get-wmiobject -class "win32_account" -namespace "root\cimv2" | sort caption | format-table caption, __CLASS, FullName

Current User Info

Get-ADUser -Identity $env:USERNAME -Properties *

AD User Info

Get-ADUser -Identity ldapreader -Properties *

List all locked out users / unlock said deviants

Import-Module activedirectory
Search-ADAccount -LockedOut | Unlock-ADAccount

List Lockout Events for User

Get-ADUser -Identity etan Get-WinEvent -ComputerName dc-corp-1203 -FilterHashtable @{logname='security';id=4740;data='S-1-5-21-985829038-2064205030-564823159-2069'} OR

Get-WinEvent -ComputerName dc-corp-1203 -FilterHashtable @{logname='security';id=4740;data=‘etan’} |
Select-Object -Property timecreated,
@{label='username';expression={$_.properties[0].value}},
@{label='computername';expression={$_.properties[1].value}}

OUTPUT


TimeCreated                             username                                computername
-----------                             --------                                ------------
3/21/2017 9:16:25 AM                    etan
3/21/2017 8:30:14 AM                    etan
3/20/2017 3:09:50 PM                    etan
3/20/2017 2:00:21 PM                    etan                                    \\SEA2-ACS-01
3/20/2017 11:13:01 AM                   etan                                    \\SEA1-ACS-01
3/20/2017 10:07:26 AM                   etan                                    \\SEA2-ACS-01
3/20/2017 6:09:17 AM                    etan                                    \\SEA2-ACS-01
3/16/2017 1:12:49 PM                    etan                                    \\SEA1-ACS-01
3/16/2017 12:48:03 PM                   etan
3/16/2017 11:50:25 AM                   etan

OUTPUT AS CSV

Get-WinEvent -ComputerName dc-corp-1203 -FilterHashtable @{logname='security';id=4740;data=‘etan’} |
Select-Object -Property timecreated,
@{label='username';expression={$_.properties[0].value}},
@{label='computername';expression={$_.properties[1].value}} |
Export-Csv "$home\Downloads\ad_lockout_user_$(get-date -f MMddyyyy_hhmmss).csv" –NoTypeInformation

PowerShell: Filter by User when Querying the Security Event Log with Get-WinEvent and the FilterHashTable Parameter – Mike F Robbins

Query for cached credentials

Install-Module -Name PSCredentialManager Get-CachedCredential -ComputerName dc-corp-1203

http://searchenterprisedesktop.techtarget.com/tip/Clear-cached-credentials-with-the-cmdkey-and-PowerShell

OUTPUT AS TABLE .\Get-MS17010.ps1 1.1.1.1 | ft -Wrap

https://www.reddit.com/r/sysadmin/comments/6bl2my/powershell_script_to_scan_a_host_or_network_for/#bottom-comments

Query RDP users on server (disconnect/logoff)

query user /server:dc-corp-1203

  • Use session ID to remotely logoff a user logoff 2 /server:dc-corp-1203

https://stackoverflow.com/a/18193461

Query Event Viewer

Get-WinEvent -ComputerName erpts-corp-1201 -FilterHashtable @{logname='system';id=1131} -MaxEvents 50 | FL *

  • LogNames:
    • Application
    • System
    • Security
    • Setup

Get-WinEvent - PowerShell - SS64.com Get-WinEvent

List Event Viewer Log Categories

NOTE: Get-EventLog deprecated in favor of Get-WinEvent Get-EventLog -List

https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.management/get-eventlog

Get Event Viewer Error logs

Get-EventLog -LogName "System" -EntryType Error -Newest 10

Get Event Viewer logs by source and event ID

Get-EventLog -LogName "System" -EntryType Error | where {$_.eventID -eq 10010}

Last 10 Event Viewer logs with pretty printing

Get-WinEvent -LogName System -MaxEvents 10 | FL * OR Get-WinEvent -FilterHashTable @{LogName="Microsoft-Windows-TerminalServices-Printers/Admin"} -maxevents 25 | FL *

Get local Event Viewer logs from past day

Get-WinEvent -ComputerName $env:computername -FilterHashtable @{LogName="Application","Security","System";Level=1, 2, 3;StartTime=(get-date).AddDays(-1); EndTime=(get-date).AddHours(-1)}

Get local Event Viewer logs from past week

Get-WinEvent -ComputerName $env:computername -FilterHashtable @{LogName="Application","Security","System";Level=1, 2, 3;StartTime=(get-date).AddDays(-7); EndTime=(get-date).AddHours(-1)}

Get local Event Viewer RDP logs from past week

Get-WinEvent -ComputerName $env:computername -FilterHashtable @{LogName="Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational";StartTime=(get-date).AddDays(-7); EndTime=(get-date).AddHours(-1)}

Note * May need to remove -ComputerName $env:computername to run command on Windows 7 * Ditto on –NoTypeInformation flag for CSV output

Get GPO policy for user/computer

gpresult /Scope User /v gpresult /Scope Computer /v gpresult /h $home\Downloads\gpresult_$(get-date -f MMddyyyy_hhmmss).html /f

Invoke-WebRequest (wget / curl Equivalent)

PSv2.0 iex (New-Object Net.WebClient).DownloadString('https://git.io/v9rJg’) PSv3.0+ iwr https://gallery.technet.microsoft.com/scriptcenter/Get-LoggedOnUser-Gathers-7cbe93ea/file/85728/5/Get-LoggedOnUser.ps1 -OutFile Get-LoggedOnUser.ps1

3 ways to download files with PowerShell

Test WinRM

Invoke-Command -ComputerName "erp-corp-1201" -ScriptBlock {ipconfig /all} -Credential CORP\lstephens OR Enter-PSSession -ComputerName "erp-corp-1201" -Credential CORP\lstephens

Test RDP Port

Test-NetConnection erp-corp-1201 -Port 3389 -InformationLevel Quiet

Netstat with ports and PIDs

netstat -ano

Windows Update

Import-Module PSWindowsUpdate
Get-WUServiceManager
Add-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d -Confirm:$false
Get-WUInstall -MicrosoftUpdate -IgnoreUserInput -AcceptAll -IgnoreReboot -Verbose

Powershell for automatize windows update and program installation | WindowsBBS

Outstanding Windows Updates

Get-WUList

WSUS client report

PsExec.exe @MyListFile.txt -d wuauclt /reportnow

https://www.experts-exchange.com/questions/28952652/WSUS-force-computer-to-check-in-with-powershell.html

List DCs

Get-ADComputer -Filter * -SearchBase "OU=Domain Controllers,DC=corp,DC=rhapsody,DC=com"

List All Computers by OS

Get-ADComputer -Filter * -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion -Wrap –Auto

List All Computers by Name

Get-ADComputer -Filter * | Select-Object -Property Name && Export as TXT | Out-File $home\Downloads\domainPCs.txt OR | Out-File -FilePath "$ScriptPath\$(get-date -f "yyyy.MM.dd-HH.mm.ss").txt"

Trim whitespace and blank lines in TXT file

(gc C:\Users\lstephens\Downloads\domainPCs.txt)| % {$_.trim()} | sc C:\Users\lstephens\Downloads\domainPCs.txt

How to trim all the lines in a file in powershell - Stack Overflow Get-Content Set-Content

Get user AD expiration date

Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" |
Select-Object -Property "Displayname",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} |
sls Stephens

One-Liner: Get a List of AD Users Password Expiry Dates – PoSh Chap

List OUs

Get-ADOrganizationalUnit -Filter * -Properties CanonicalName | Select-Object -Property CanonicalName

Export Users as a CSV

Get-ADUser -SearchBase "OU=Users_and_Groups,DC=corp,DC=rhapsody,DC=com" -Filter * -Properties DisplayName, EmailAddress, Title | select DisplayName, EmailAddress, Title | Export-CSV "$home\Downloads\ad_users_$(get-date -f MMddyyyy_hhmmss).csv"

List All Users in OU

Get-ADUser -Filter {(Name -like "*")} -SearchBase "OU=TermedOU,DC=corp,DC=rhapsody,DC=com"

Disable All Users in OU

Get-ADUser -Filter {(Name -like "*")} -SearchBase "OU=TermedOU,DC=corp,DC=rhapsody,DC=com" | Disable-ADAccount

List Enabled Users in OU

Get-ADUser -Filter {(Enabled -eq $true)} -SearchBase "OU=TermedOU,DC=corp,DC=rhapsody,DC=com"

List Computers in OU

Get-ADObject -Filter {Name -Like "*"} -Searchbase "OU=ProductionMicrosoftServers,DC=corp,DC=rhapsody,DC=com" | Select-Object Name

MS Server 2003 in OU

Get-ADObject -Filter { OperatingSystemVersion -like "*5.2*" } -Searchbase "OU=ProductionMicrosoftServers,DC=corp,DC=rhapsody,DC=com" | Select-Object Name

Fix NTP sync

w32tm /query /source Local CMOS Clock >> Should be MS or NIST w32tm /config /manualpeerlist:"time.nist.gov" /syncfromflags:manual /reliable:yes /update net stop W32Time net start W32Time w32tm /resync w32tm /query /status

Leap Indicator: 0(no warning)
Stratum: 2 (secondary reference - syncd by (S)NTP)
Precision: -23 (119.209ns per tick)
Root Delay: 0.0302976s
Root Dispersion: 7.7754862s
ReferenceId: 0x808A8C2C (source IP:  128.138.140.44)
Last Successful Sync Time: 11/22/2017 2:19:41 PM
Source: time.nist.gov
Poll Interval: 10 (1024s)

w32tm /query /source time.nist.gov

How do I force sync the time on Windows Workstation or Server? - Server Fault how to sync windows time from a ntp time server in command - Stack Overflow

Check SMB Version

Get-SmbConnection

Windows Service Accounts

get-service | foreach {Write-Host NT Service\$($_.Name)}

Get installed Windows features

Get-WindowsFeature | ? Installed

Script pwd equivalent

$workingDir= (Get-Item -Path ".\" -Verbose).FullName OR $workingDir = (Get-Location).path

https://stackoverflow.com/questions/8343767/how-to-get-the-current-directory-of-the-cmdlet-being-executed/23131958#23131958

IIS Application Pools

Get-WebConfiguration system.applicationHost/applicationPools/* /* | where {$_.ProcessModel.identitytype -eq 'ApplicationPoolIdentity'} | foreach {Write-Host IIS APPPOOL\$($_.Name)}

Hyper-V VMs

get-vm | foreach {Write-Host NT VIRTUAL MACHINE\$($_.Id) - $($_.VMName)}

List of Installed Windows Updates

Filter by KB Get-WmiObject -Class "win32_quickfixengineering" | sls KB3159706 Export as CSV Get-WmiObject -Class "win32_quickfixengineering" | Export-Csv -Path $home\Downloads\updates.csv –NoTypeInformation

Import Perfmon XML Template

logman import -n "CPU Utilization" -xml perfmon_cpu.xml

DC Replication Errors

repadmin /showrepl * /csv | ConvertFrom-Csv | Out-GridView

Active Directory Replication Cmdlets vs. Repadmin – PoSh Chap

which Profile alias

function which($name)
{
    Get-Command $name | Select-Object -ExpandProperty Definition
}

https://stackoverflow.com/questions/63805/equivalent-of-nix-which-command-in-powershell/16949127#16949127

wc Equivalent

some-command | Measure-Object -line -word -character

Windows Powershell: Unix Equivalents in Powershell

Show NPS Clients

netsh nps show client

Conflict Objects (DFSR)

dsquery * forestroot -gc -attr distinguishedName -scope subtree -filter "(|(cn=*\0ACNF:*)(ou=*OACNF:*))"

Directory Admin: Find CNF objects in Active Directory

DSC Environment Analyzer (DSCEA)

Install RSAT to Import and Install Modules Install-Module -Name DSCEA

Generate MOF file

Discover SMB1 in your environment with DSCEA – Microsoft Datacenter blog by Ralph Kyttle

Start-DSCEAscan -MofFile .\localhost.mof -InputFile C:\Users\lstephens\Downloads\domainPCs.txt

Unexpected shutdown

Get-EventLog System | Where-Object {$_.EventID -eq "1074" -or $_.EventID -eq "6008" -or $_.EventID -eq "1076"} | ft Machinename, TimeWritten, UserName, EventID, Message -AutoSize -Wrap

  • Export Get-EventLog System | Where-Object {$_.EventID -eq "1074" -or $_.EventID -eq "6008" -or $_.EventID -eq "1076"} | Select-Object -Property Machinename, TimeWritten, UserName, EventID, Message | Export-Csv "$home\Downloads\shutdown_events_$(Get-Date -f MMddyyyy_hhmmss).csv" -NoTypeInformation

Get Free Space on Remote Machine

Get-WMIObject Win32_Logicaldisk -filter "deviceid='C:'" -ComputerName dc-corp-1102 |
Select PSComputername,DeviceID,
@{Name="SizeGB";Expression={$_.Size/1GB -as [int]}},
@{Name="FreeGB";Expression={[math]::Round($_.Freespace/1GB,2)}}

Look up GPO by name

Get-GPO -Name 'User Workstation Standards GPO' -Domain corp.rhapsody.com

Look up GPO by GUID

Get-GPO -guid 894AD25C-78CC-40F9-8D53-A079704AC384 -Domain corp.rhapsody.com OUTPUT:

DisplayName      : WSUS
DomainName       : corp.rhapsody.com
Owner            : CORP\Domain Admins
Id               : 894ad25c-78cc-40f9-8d53-a079704ac384
GpoStatus        : AllSettingsEnabled
Description      :
CreationTime     : 11/30/2016 2:07:00 PM
ModificationTime : 11/15/2017 10:59:34 AM
UserVersion      : AD Version: 0, SysVol Version: 0
ComputerVersion  : AD Version: 10, SysVol Version: 10
WmiFilter        :

Get-GPO

STDOUT to clipboard

ps | clip

bluesoul comments on ITT:Handy Commands You Might Not Know

Repair trust relationship

Test-ComputerSecureChannel [-Repair]

mjwinger1 comments on ITT:Handy Commands You Might Not Know

netstat filters

netstat -ano 1 | findstr 443

Trying to track down what process on your windows machine is trying to get out to the internet in your firewall logs? Replace 443 with whatever you like, source/destination port or IP, or process ID if you just want to see all the network connections that a certain process has. the 1 in there keeps netstat refreshing every 1 second

sysadmin__ comments on ITT:Handy Commands You Might Not Know

gpupdate then reboot if needed

echo n | gpupdate /force && shutdown -r -t 0

NtGuru comments on ITT:Handy Commands You Might Not Know

gpupdate on remote OU

Get-ADComputer -Filter * -SearchBase "OU=Clients,OU=NorthAmerica,DC=Contoso,DC=Com" | For-Each { Invoke-GPUpdate -Computer $_.Name -Force }

Lets you force an update against an OU remotely. We use it when rolling new policies office by office. For example something like LAPS; Add the LAPS policy to office's computer OU, run the above. If you're doing it after hours it even has the -Boot option that gpupdate has.

omers comments on ITT:Handy Commands You Might Not Know

Last boot time of remote PC

Get-WmiObject win32_operatingsystem -ComputerName the_name_of_the_remote_computer | select csname, @{label='LastBootupTime' ;EXPRESSION={$_.ConvertToDateTime($_.lastbootuptime)}}

Garetht comments on ITT:Handy Commands You Might Not Know

Comprehensive user information

whoami
whoami /claims
whoami /user
whoami /groups

OR whoami /all

Gary_Chan1 comments on ITT:Handy Commands You Might Not Know

Set DNS on remote server

Set-DnsClientServerAddress -ServerAddresses x.x.x.x,y.y.y.y Set-DNSClientServerAddress –interfaceIndex $_.ifIndex –ServerAddresses ("10.0.0.1","10.0.0.2") -Verbose

Open files on remote server

openfiles /query /s \\dc-corp-1203 /v OUTPUT

Hostname        ID       Accessed By          Type       #Locks     Open Mode       Open File (Path\executable)
=============== ======== ==================== ========== ========== =============== ================================================================================
dc-corp-1203.co 67126374 lstephens            Windows    0          Write + Read    \srvsvc
dc-corp-1203.co 53697025 adsvc                Windows    0          Read            C:\Windows\Netwrix Auditor\Event Collection\226eae05-e03d-43a0-81fe-daacf1730261
dc-corp-1203.co 12081848 adsvc                Windows    0          Read            C:\Windows\NETWRIX AUDITOR\EVENT COLLECTION
dc-corp-1203.co 46977537 adsvc                Windows    0          Read            C:\Windows\NETWRIX AUDITOR\EVENT COLLECTION
dc-corp-1203.co 67115419 adsvc                Windows    0          Write + Read    \EVENTLOG
dc-corp-1203.co 28858409 adsvc                Windows    0          Write + Read    \EVENTLOG
dc-corp-1203.co 28185724 RHAP-WMRM-PROD-$     Windows    0          Write + Read    \samr
dc-corp-1203.co 46976285 WMRM-PROD-1205$      Windows    0          Write + Read    \samr

Open SMB open files on remote server

$Computername = read-host "Enter computername" Invoke-Command -ComputerName $Computername -ScriptBlock {Get-SmbOpenFile | Select ClientUserName,@{N="Source";E={(Resolve-DnsName $_.ClientComputerName).NameHost}}} OR w/hard-coded computer name: Invoke-Command -ComputerName dc-prod-1201 -ScriptBlock {Get-SmbOpenFile | Select ClientUserName,@{N="Source";E={(Resolve-DnsName $_.ClientComputerName).NameHost}}}

Need some help in modifying Powershell script to show open files in File server

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment