Skip to content

Instantly share code, notes, and snippets.

@publicarray
Last active January 6, 2023 06:20
Show Gist options
  • Save publicarray/81308867363e0c3c9fc83efea68db55f to your computer and use it in GitHub Desktop.
Save publicarray/81308867363e0c3c9fc83efea68db55f to your computer and use it in GitHub Desktop.
Powersell snipits
# Dowload help files (run as Admin)
Update-Help -UICulture en-US
# Search for commands (cmdlets)
Get-command *process*
# man pages
Get-Help Get-Timezone
# Get object types
Get-Date | Get-Member
Get-Random | Get-Member # TypeName: System.Int32
# List all properties of an object
Get-Date | Format-List -Force *
# Ask for input
[int]$num = Read-Host -Prompt "Enter a number"
# echo
Write-Host "hello", "world"
Write-Output "hello", "world"
# read a file
Get-Content C:\Windows\system32\drivers\etc\hosts
# Write to file
Write-Output "hello world" | Out-File out.log
# Write to csv file
Get-Process | ConvertTo-Csv -NoTypeInformation | Out-File out.csv
# grep
Write-output "Hi stranger", "bye" | Select-String -Pattern "hi"
Write-output "Hi stranger", "127.0.0.1" | Where-Object {$_ -like "*.*.*.*"}
# regex
Write-output "Hi stranger", "bye1" | Select-String -Pattern "\d" -AllMatches
# convert to string
[int]10 | Out-String
# Look and install powershell modules
Find-module -Tag uninstall
Install-module find.uninstaller
Get-command -Module Find.Uninstaller
Get-UninstallString -Application Firefox
Uninstall-Module find.uninstaller
# Read JSON from the web
(Invoke-RestMethod 'https://reddit.com/r/powershell.json').data.children.data | Select-Object Score,title | Sort-Object Score -Descending
# Convert formats to powershell objects
ConvertFrom-Csv
ConvertFrom-Json
# Kill script if there is an Error in a cmdlet
#https://www.techthoughts.info/powershell-errors-and-exceptions-handling/
Get-Item -Path c:\nope\nope.txt -ErrorAction Stop;Write-Host 'Hello, will I run after an error?'
# TryCatchFinnaly
try {1/0} catch {Write-Error $_;throw}
# Did the last command run sucessfully?
[System.Environment]::OSVersion.Version; $?
1/0; $?
$LASTEXITCODE
# Give a usefull error message
try{Invoke-WebRequest "example.com/404" -ErrorAction Stop}catch{if($_.Exception -Like "*404*"){Write-Warning "Error:404 Page not found"} else {throw}}
# Remote powershell setup
# https://www.techthoughts.info/powershell-remoting/
Test-WSMan
winrm quickconfig -transport:https
winrm get winrm/config/client
winrm get winrm/config/service
winrm enumerate winrm/config/listener$env:SystemDrive[0]
# Get processes using at least 50% CPU
Get-Process | Where-Object {$_.CPU -gt 50}
# List largest files in home folder
Get-ChildItem -Path $HOME -Recurse | Sort-Object -descending -property length | Select-Object -First 10 @{Name="GigaBytes";Expression={"{0:N2}" -f ($_.Length / 1GB)}},FullName
# Find Uninstall string
Get-ChildItem -Path @('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall','HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall') | Get-ItemProperty | Where-Object {$_.DisplayName -like "*Firefox*"}
# Test for Network
Test-Connection seby.io
Test-Connection seby.io -Traceroute
Test-NetConnection
Test-NetConnection seby.io -Port 443
# Download a File
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest "https://seby.io" -OutFile index.html
# Get domain
$env:USERDOMAIN
(Get-WmiObject Win32_ComputerSystem).Domain
# Get Drive size used and free space
Get-PSDrive ($env:SystemDrive -replace ":","")
(Get-PSDrive ($env:SystemDrive -replace ":","")).free / 1GB
# Get disk information
Get-Disk
Get-Partition | Where-Object { [string]($_.DriveLetter) -ne "" } |ForEach-Object {Get-PhysicalDisk -DeviceNumber $_.DiskNumber | Format-List DriveLetter,MediaType,FriendlyName,SerialNumber, @{Name="Size (GB)";Expression={$_.size/1GB}},HealthStatus}
# Format and Partition Disk
$Disk = Get-Disk -Number 1
$disk|Initialize-Disk -PartitionStyle GPT
$disk|New-Partition -UseMaximumSize -AssignDriveLetter| Format-Volume -Confirm:$false
# BIOS Info
Get-WmiObject -Class "Win32_BIOS"
# Determine boot mode (UEFI or legacy)
$env:firmware_type
# Determince is secure boot is enabled (run as admin)
Confirm-SecureBootUEFI
# Windows Activation check
cscript /Nologo "C:\Windows\System32\slmgr.vbs" /xpr
# Windows build
[environment]::OSVersion.Version.Build
# Installed Antivirus products
Get-CimInstance -Namespace root/SecurityCenter2 -className AntivirusProduct
# Search Windows Event Log (Bluescreens)
Get-WinEvent -FilterHashtable @{LogName = 'application'; ID = '1001'; ProviderName = 'Windows Error Reporting'; Level = 4; Data = 'BlueScreen'; StartTime = ((Get-Date) - (New-TimeSpan -Day 14)) }
# temp profile
Get-WinEvent -FilterHashtable @{LogName = 'Application'; ID = '1511'
# Rename conputer
Rename-computer -NewName $name -Force -Restart
Rename-computer -NewName $NewName -DomainCredential $credential -Force -Restart
# Join a Domain
$password = ConvertTo-SecureString -string $password -asPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("domain\UserAccount", $password)
Add-Computer -DomainName $domain -OUPath $OUPath -Credential $credential -Restart
# Add Regestry key (Disable Cortana)
reg add "hklm\SOFTWARE\Policies\Microsoft\Windows\Windows Search" /d "AllowCortana"=dword:00000000
# Available power states
powercfg /A
# System info
Get-CimInstance -ClassName 'Win32_ComputerSystem'
# Networking
Get-NetAdapter
ipconfig /all
ipconfig /release
ipconfig /renew
ipconfig /cleardns
netsh interface ip set address Ethernet dhcp
netsh interface ip set dns Ethernet dhcp
netsh int ip reset
netsh winsock reset
netsh winhttp reset proxy
# defrag/trim
Optimize-Volume $env:SystemDrive[0]
# Get users on system
get-localuser
# services
Stop-Service -Name spooler
Restart-Service -Name spooler -Force
# fix curruption
sfc /scannow
dism
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment