Skip to content

Instantly share code, notes, and snippets.

@githubfoam
Last active March 7, 2026 00:18
Show Gist options
  • Select an option

  • Save githubfoam/36a9a16d5fdb47adbef230f2f9228c25 to your computer and use it in GitHub Desktop.

Select an option

Save githubfoam/36a9a16d5fdb47adbef230f2f9228c25 to your computer and use it in GitHub Desktop.
powershell cheat sheet
=========================================================================================================
#powershell editor in windows
PowerShell ISE,Visual Studio Code,Notepad++
==========================================================================================================
Example 3: Modify your prompt function
This command changes the prompt function so that it displays the time before the path.
PowerShell
Set-Item -Path function:prompt -Value {'PS '+ (Get-Date -Format t) + " " + (Get-Location) + '> '}
==========================================================================================================
The Active Directory Administrative Center (ADAC) - type dsac in cmd or PowerShell
The PowerShell History Viewer - At the bottom
==========================================================================================================
#update / upgrade powershell
> $PSVersionTable.PSVersion
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 2 2
> iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"
> $PSVersionTable.PSVersion
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 2 3
==========================================================================================================
#ChatGPT
#To execute a PowerShell script from an URL, you can use the Invoke-WebRequest cmdlet to download the script
#from the URL and then use the Invoke-Expression cmdlet to run the downloaded script.
$url = "https://example.com/myscript.ps1"
$script = Invoke-WebRequest -Uri $url -UseBasicParsing
Invoke-Expression -Command $script.Content
==========================================================================================================
#Install chocolatey from github - pwsh script
iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/githubfoam/choco_githubactions/main/scripts/Install_chocolatey.ps1'))
==========================================================================================================
# silently install PowerShell
msiexec.exe /package PowerShell-7.2.1-win-x64.msi /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1 USE_MU=1 ENABLE_MU=1
#If already have the .NET Core SDK installed, install PowerShell as a .NET Global tool.
dotnet tool install --global PowerShell
#pwsh console
iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"
---------------------------------------------------------------
Install PowerShell using WinGet (recommended)
#windows powershell (blue) with privileged administrator account
> winget search Microsoft.PowerShell
Name Id Version Source
---------------------------------------------------------------
PowerShell Microsoft.PowerShell 7.2.1.0 winget
PowerShell Preview Microsoft.PowerShell.Preview 7.3.0.2 winget
> winget install --id Microsoft.Powershell --source winget
winget install --id=Microsoft.PowerShell -e
winget install --id=Microsoft.PowerShell -v "7.1.2" -e
https://learn.microsoft.com/en-gb/powershell/scripting/install/installing-powershell-on-windows?view=powershell-7.5#winget
==========================================================================================================
$myVariable = "Hello, world!" #you can set a variable using the $ symbol followed by the variable name and the value you want to assign to it
Write-Host $myVariable #To run this variable in another command, you can use the variable name preceded by the $ symbol
==========================================================================================================
# write the output of a PowerShell script to a text file
.\MyScript.ps1 | Out-File -FilePath C:\Output.txt
'.\MyScript.ps1' | Out-File -FilePath C:\Output.txt #single quotes to escape chars
.\MyScript.ps1 | Set-Content -Path C:\Output.txt
==========================================================================================================
#windows 10
#cannot upgrade PowerShell 5.1 to PowerShell Core 7.1. PowerShell 7 is installed on a computer separately from Windows PowerShell 5.1.
#cannot use PowerShell ISE with PowerShell v6 or v7.
C:\Windows\System32\WindowsPowerShell\v1.0 #Windows PowerShell 5.1
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
RUN - powershell
Windows key - powershell
>$Env:PSModulePath -split (';')
>$PROFILE | Select-Object *Host* | Format-List
C:\Program Files\PowerShell\7 #PowerShell Core 7.x
C:\Program Files\PowerShell\7\pwsh.exe
RUN - pwsh
Windows key - pwsh
>$Env:PSModulePath -split (';')
>$PROFILE | Select-Object *Host* | Format-List
==========================================================================================================
#vs code, powershell 7.x setting
view - command palette - Preferences: Open Settings (JSON)
#add line
"terminal.integrated.shell.windows" : "C:\Program Files\PowerShell\7\pwsh.exe"
#run powershell script within vs code
view - terminal
> .\scripts\search_string_docx_pdf.ps1
==========================================================================================================
#PowerShell scripts on your system that have been created by other users, you may need to check script execution policy
Set-ExecutionPolicy <policy> where policy is one of
four options:
• Restricted - default execution policy; doesn’t run scripts, interactive only
• AllSigned - runs scripts; scripts and configurationfiles must be signed by trusted publisher
• RemoteSigned – Like as AllSigned when script is downloaded app such as IE and Outlook
• Unrestricted – goes without saying
==========================================================================================================
#ChatGPT
On Windows 10, you can use PowerShell to list, start, and stop running background jobs. Here's an explanation of the commands you can use:
List Background Jobs: To list the currently running background jobs, you can use the Get-Job command. It retrieves information about active jobs in the current session. Here's an example:
powershell
Get-Job
This command will display details of the running background jobs, including their ID, State, and Name.
Start Background Job: To start a new background job, you can use the Start-Job command. It allows you to run a script or command in the background while continuing to work in the current session. Here's an example:
powershell
Start-Job -ScriptBlock { <your script or command here> }
Replace <your script or command here> with the actual script or command you want to run as a background job.
Stop Background Job: To stop a running background job, you can use the Stop-Job command followed by the job ID. Here's an example:
powershell
Stop-Job -Id <job ID>
Replace <job ID> with the ID of the job you want to stop. You can obtain the job ID from the output of the Get-Job command.
Additionally, you can use the Stop-Job command without specifying a job ID to stop all running background jobs:
powershell
Stop-Job *
This command will stop all active background jobs in the current session.
To run a Python script in the background using PowerShell on Windows 10, you can utilize the Start-Job cmdlet. This allows you to run a script in the background while still having access to your PowerShell terminal. Here's how you can do it:
Open PowerShell: Open PowerShell on your Windows 10 machine.
Navigate to the Script Directory: Use the cd command to navigate to the directory where your Python script is located.
powershell
Copy code
cd C:\Path\To\Your\Script\Directory
Run the Script in the Background: Use the Start-Job cmdlet to run your Python script in the background. Here's an example of how to do it:
powershell
Copy code
Start-Job -ScriptBlock {python YourScript.py}
Replace YourScript.py with the actual name of your Python script.
Check the Status: To check the status of the background job, you can use the Get-Job cmdlet.
powershell
Copy code
Get-Job
It will display a list of currently running jobs along with their job ID.
Retrieve Output (Optional): If your script produces any output, you can retrieve it using the Receive-Job cmdlet. For example:
powershell
Copy code
Receive-Job -Id 1
Replace 1 with the actual job ID you want to retrieve output from.
Wait for the Job to Complete (Optional): If you want to wait for the background job to complete before proceeding, you can use the Wait-Job cmdlet:
powershell
Copy code
Wait-Job -Id 1
This will wait for the job with ID 1 to finish before moving on.
Remember to replace YourScript.py with the actual name of your Python script. This method allows you to run a Python script in the background while still having access to your PowerShell terminal. You can also run multiple scripts concurrently in this manner
==========================================================================================================
#PowerShell ISE
#cannot be loaded because running scripts is disabled on this system. For more
#information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
#https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7.2
> Get-ExecutionPolicy
Restricted
> Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine Undefined
> Get-ExecutionPolicy -Scope CurrentUser
Undefined
> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
==========================================================================================================
$PSVersionTable.PSVersion
$PSVersionTable
pwsh #linux macos windows
==========================================================================================================
C:\> powershell -c "<command>" #PowerShell cmdlets can be called from cmd.exe
==========================================================================================================
Get-Help Get-NetIpConfiguration
Get-Help XXX (cmdlet)
To see the examples, type: "get-help Get-NetIPConfiguration -examples".
For more information, type: "get-help Get-NetIPConfiguration -detailed".
For technical information, type: "get-help Get-NetIPConfiguration -full".
For online help, type: "get-help Get-NetIPConfiguration -online"
==========================================================================================================
#multi-line command
#Pipeline Operator: |
Get-Widget |
Where-Object {$_.Height -gt 20 -and $_.Width -gt 20 -and -$_.Depth -gt 20} |
Sort-Object -Property Price |
Select-Object -First 100 |
Select-Object -Property Name, Price, Height, Width, Depth, Description |
Format-Table -AutoSize
&& run the second command only if the first one succeeds.
|| run the second command only if the first one fails.
==========================================================================================================
# one liner to install chrome
$Path = $env:TEMP; $Installer = 'chrome_installer.exe'; Invoke-WebRequest -Uri 'http://dl.google.com/chrome/install/375.126/chrome_installer.exe' -OutFile $Path\$Installer; Start-Process -FilePath $Path\$Installer -Args '/silent /install' -Verb RunAs -Wait; Remove-Item -Path $Path\$Installer
==========================================================================================================
#break command into multi lines, backtick sign
choco install `
vagrant packer
==========================================================================================================
#auto confirm
still prompts target;
is a directory
and it is not empty
and the -Recurse parameter is not specified.
Remove-Item -Recurse -Force -Confirm:$false- # enable it with -Confirm,disable it with -Confirm:$false
Remove-Item .\foldertodelete -Force -Recurse
#add a /A
get-childitem C:\temp\ -exclude *.svn-base,".svn" -recurse | foreach ($_) {remove-item $_.fullname} /A
==========================================================================================================
#run a PowerShell script
powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"
powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"
Powershell.exe -File C:\my_path\yada_yada\run_import_script.ps1
PS> .\run_import_script.ps1 (enter)
type "script_path" | powershell.exe -c -
==========================================================================================================
Get-InstalledModule # list of modules on the computer that were installed by PowerShellGet
Get-InstalledModule -Name "AzureRM.Automation" -MinimumVersion 1.0 -MaximumVersion 2.0
==========================================================================================================
#Collecting Information About Computers, computer name/device name/machine name
#pws
Get-CimInstance -ClassName Win32_Desktop #username etc
Get-CimInstance -ClassName Win32_BIOS #complete information about the system BIOS on the local computer
Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object -Property SystemType #Listing Processor Information
Get-CimInstance -ClassName Win32_ComputerSystem #Listing Computer Manufacturer and Model
Get-CimInstance -ClassName Win32_QuickFixEngineering #Listing Installed Hotfixes
Get-CimInstance -ClassName Win32_QuickFixEngineering -Property HotFixID
"Get-CimInstance -ClassName Win32_QuickFixEngineering -Property HotFixId |
Select-Object -Property HotFixId"
#Listing Operating System Version Information
"Get-CimInstance -ClassName Win32_OperatingSystem |
Select-Object -Property BuildNumber,BuildType,OSType,ServicePackMajorVersion,ServicePackMinorVersion"
Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -Property Build*,OSType,ServicePack*
#Listing Local Users and Owner
Get-CimInstance -ClassName Win32_OperatingSystem |
Select-Object -Property NumberOfLicensedUsers,NumberOfUsers,RegisteredUser
#Getting Available Disk Space
Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3"
Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3" |
Measure-Object -Property FreeSpace,Size -Sum |
Select-Object -Property Property,Sum
#Getting Logon Session Information
Get-CimInstance -ClassName Win32_LogonSession
#Getting the User Logged on to a Computer
Get-CimInstance -ClassName Win32_ComputerSystem -Property UserName
#Getting Local Time from a Computer
Get-CimInstance -ClassName Win32_LocalTime
#Displaying Service Status, view the status of all services on a specific computer,
Get-CimInstance -ClassName Win32_Service |
Select-Object -Property Status,Name,DisplayName
#find remote computer name
Resolve-DnsName 10.1.1.1
#Find computer name from IP address
$ipAddress= "192.168.1.54"
[System.Net.Dns]::GetHostByAddress($ipAddress).Hostname
#Resolve computer name to IP Address
$machineName= "DC1"
$hostEntry= [System.Net.Dns]::GetHostByName($machineName)
$hostEntry.AddressList[0].IPAddressToString
==========================================================================================================
#(requires administrator PowerShell)
PS C:\> Get-WinEvent -LogName system #View all events in the live system Event Log
PS C:\> Get-WinEvent -LogName security
PS C:\> Get-WinEvent -Path example.evtx | fl #View all events in the file example.evtx, format list (fl) output
PS C:\> Get-WinEvent -Path example.evtx | Out-GridView
PS C:\> Get-WinEvent -Path example.evtx | Group-Object id -NoElement | sort count
PS C:\> Get-WinEvent -FilterHashtable @{Path="system.evtx";ID=7030,7045} #Pull events 7030 and 7045 from system.evtx
PS C:\> Get-WinEvent -FilterHashtable @{Path="system.evtx"; ID=7030,7045} # use the live system event log
PS C:\> Get-WinEvent -FilterHashtable @{Path="system.evtx"} | fl | findstr /i USB
PS C:\> Get-WinEvent -FilterHashtable @{logname="system"; id=7030,7045}
PS C:\> Get-WinEvent -FilterHashtable @{Path="system.evtx"} | Where {$_.Message -like "*USB*"}
PS C:\> Get-WinEvent -FilterHashtable @{Path="application.evtx"; level=2}
PS C:\> Get-WinEvent -FilterHashtable @{Path="application.evtx"; level=2} | Measure-Object -Line
PS C:\> Get-WinEvent -logname "Microsoft-Windows-AppLocker/EXE and DLL"
PS C:\> Get-WinEvent -FilterHashtable @{logname="Microsoft-Windows-Applocker/EXE and DLL"; id=8004}
PS C:\> Get-WinEvent -FilterHashtable @{logname="Microsoft-Windows-Applocker/EXE and DLL"; id=8003}
PS C:\> Get-WinEvent -FilterHashtable @{logname="Microsoft-Windows-Windows Defender/Operational"}
==========================================================================================================
Get-EventLog -List
get-eventlog -source "Service Control manager" -LogName System | select message, timegenerated, username | Out-GridView
Get-EventLog -LogName System -Newest 5
Get-EventLog -LogName System -EntryType Error
Get-EventLog -LogName System -InstanceId 10016 -Source DCOM
Get-EventLog -LogName System -ComputerName Server01, Server02, Server03
Get-EventLog -LogName System -Message *description* #include a specific word in the message
#from an event log using a source and event ID
Get-EventLog -LogName Application -Source Outlook | Where-Object {$_.EventID -eq 63} |
Select-Object -Property Source, EventID, InstanceId, Message
#
Get-EventLog -LogName System -UserName NT* | Group-Object -Property UserName -NoElement |
Select-Object -Property Count, Name
#Shutdown Logs in Event Viewer
PS C:\> Get-EventLog System -Newest 10000 | `
Where EventId -in 41,1074,1076,6005,6006,6008,6009,6013 | `
Format-Table TimeGenerated,EventId,UserName,Message -AutoSize -wrap
> $Events = Get-EventLog -LogName System -Newest 5
> $Events | Group-Object -Property Source -NoElement | Sort-Object -Property Count -Descending
#Display the property values of an event
$A = Get-EventLog -LogName System -Newest 1
$A | Select-Object -Property *
$Begin = Get-Date -Date '1/17/2019 08:00:00'
$End = Get-Date -Date '1/17/2019 17:00:00'
Get-EventLog -LogName System -EntryType Error -After $Begin -Before $End
==========================================================================================================
Get-NetAdapter | Where-Object -FilterScript {$_.LinkSpeed -eq "100 Mbps"} #display all network adapters on the server that have a link speed of 100 megabits per second (Mbps)
Get-NetAdapter –Physical #list of physical network adapters
#list active ethernet connections physical and virtual
Get-NetAdapter | Where-Object {$_.InterfaceDescription -like "*Ethernet*" -and $_.Status -eq "Up"} | Select-Object -Property Name, InterfaceDescription, Status
#disable an ethernet connection with a given MAC Address
$mac = "00:0C:29:F5:B9:E8"
$nic = Get-NetAdapter | Where-Object {$_.MacAddress -eq $mac}
$nic | Disable-NetAdapter
Get-NetAdapter –IncludeHidden #show any hidden network adapters
Get-NetAdapter | Where {$_.Virtual –eq $True} #only the virtual network adapters
Get-NetAdapter -InterfaceDescription "*VMware*"
Get-NetAdapter | select name, drivername, majordriverversion, minordriverversion, driverinformation #the driver used by the adapter
Get-NetAdapter | select vlandid, promiscuousmode, portnumber, networkaddress, permanentaddress, mediatype
Get-NetAdapter | select transmitlinkspeed, physicalmediatype, mediaconnectionstate, speed, requestedspeed, maxspeed, fullduplex, linkspeed
#The output of this command consists of objects that can be passed through the pipeline to other cmdlets
#pipe the output into the Set-NetIPInterface cmdlet to assign a metric value of 5 to all interfaces having a link speed of 100 Mbps
PS C:\> Get-NetAdapter | Where-Object -FilterScript {$_.LinkSpeed -eq "100 Mbps"} | `
Set-NetIPInterface -InterfaceMetric 5
Get-NetAdapterBinding -InterfaceAlias "Ethernet" #display the bindings for the specified interface
Disable-NetAdapterBinding -Name "Ethernet 2" -ComponentID ms_pacer #Disabling a binding on a network adapter
Disable-NetAdapter -Name "Ethernet 2" -Confirm:$false #disables the adapter named Ethernet 2 with no confirmation prompt
==========================================================================================================
Get-NetIPAddress | where {$_.PrefixOrigin -eq "DHCP" -or $_.SuffixOrigin -eq "DHCP"} #whether the DNS client on a machine is configured as static or dynamic
==========================================================================================================
Get-NetIpConfiguration
Get-NetIpConfiguration | Select-Object interfaceindex, interfacealias, Ipv4address
#display the IPv4DefaultGateway property
Get-NetIpConfiguration | Select-Object interfaceindex, interfacealias, Ipv4address, @{ Label="DefaultGateway"; Expression={ $_.IPv4DefaultGateway.NextHop }
#include the DNSServer property
Get-NetIpConfiguration | Select-Object interfaceindex, interfacealias, Ipv4address, @{ Label="DefaultGateway"; Expression={ $_.IPv4DefaultGateway.NextHop } }, @{ Label="DnsServers"; Expression={ $_.DnsServer.ServerAddresses } }
#tabular
Get-NetIpConfiguration | format-table interfaceindex, interfacealias, Ipv4address, @{ Label="DefaultGateway"; Expression={ $_.IPv4DefaultGateway.NextHop } }, @{ Label="DnsServers"; Expression={ $_.DnsServer.ServerAddresses } }
#cvs output
Get-NetIpConfiguration | format-table interfaceindex, interfacealias, Ipv4address, @{ Label="DefaultGateway"; Expression={ $_.IPv4DefaultGateway.NextHop } }, @{ Label="DnsServers"; Expression={ $_.DnsServer.ServerAddresses } } | Export-CSV .\output.csv
==========================================================================================================
Get-DnsServerZone #view a list of zones on a DNS server that is also a domain controller
Get-DnsServerResourceRecord -ZoneName corp.contoso.com | Where-Object {$_.RecordType -eq "A"} #list of resource records of type A (address) in the corp.contoso.com zone
#add a new A resource record
Add-DnsServerResourceRecordA -IPv4Address 172.16.11.239 -Name SEA-TEST `
-ZoneName corp.contoso.com
==========================================================================================================
Get-DhcpServerInDC #DHCP server
Get-DhcpServerv4Lease -ComputerName "dhcpserver.contoso.com" -ScopeId 10.10.10.0 #Get all active leases in a scope
Get-DhcpServerv4Lease -ComputerName "dhcpserver.contoso.com" -ScopeId 192.168.0.0
Get-DhcpServerv4Filter -ComputerName <MyDHCP> #If a client isn't able to receive an address, you can check to see whether it appears on the deny list
Get-DhcpServerv4Reservation -ComputerName <MyDHCP> -ScopeId 192.168.0.0 #reserved for devices with a fixed IP
Get-DhcpServerv4Lease -ComputerName "dhcpserver.contoso.com" -IPAddress 10.10.10.10,10.20.20.20 #Get leases for specified addresses
Get-DhcpServerv4Lease -ComputerName "dhcpserver.contoso.com" -IPAddress 10.10.10.10
DhcpServerv4FreeIPAddress -ComputerName <MyDHCP> -ScopeId 192.168.0.0 -StartAddress 192.168.0.59 -NumAddress 20 # lists 20 free addresses, starting from 192.168.0.59
Get-DhcpServerv4ScopeStatistics -ComputerName <MyDHCP>
Get-DhcpServerv4ScopeStatistics -ComputerName <MyDHCP> | # press enter for cursor ">>"
>> select -Property *
Get-DhcpServerAuditLog -ComputerName <MyDHCP> #find out whether logging has been activated for the DHCP service and where the log file is stored
Get-DhcpServerSetting -ComputerName <MyDHCP>
Get-DhcpServerv4Lease -ComputerName "dhcpserver.contoso.com" -ScopeId 10.10.10.0 -BadLeases #Get declined leases
Get-DhcpServerv4Lease -ComputerName "dhcpserver.contoso.com" -ScopeId 10.10.10.0 -ClientId "F0-DE-F1-7A-00-5E", "00-24-D7-C5-25-B0" #Get leases for specified clients
Get-DhcpServerv4Lease -ComputerName "dhcpserver.contoso.com" -ScopeId 10.10.10.0 -AllLeases
#Get active leases from all scopes on a computer
Get-DhcpServerv4Scope -ComputerName "dhcpserver.contoso.com" | Get-DhcpServerv4Lease -ComputerName "dhcpserver.contoso.com"
Get-DhcpServerv4FreeIPAddress -ComputerName "dhcpserver.contoso.com" -ScopeId 10.10.10.0 #Get a free address
Get-DhcpServerv4FreeIPAddress -ComputerName "dhcpserver.contoso.com" -ScopeId 10.10.10.0 -NumAddress 10
#Get a free address from a range
Get-DhcpServerv4FreeIPAddress -ComputerName "dhcpserver.contoso.com" -ScopeId 10.10.10.0 -StartAddress 10.10.10.10 -EndAddress 10.10.10.50
#no pipe, new line
# add a scope for the IP address range 172.16.12.50 through 172.16.11.100. Leave the scope inactive
PS C:\> Add-DhcpServerv4Scope -EndRange 172.16.12.100 -Name test2 `
-StartRange 172.16.12.50 -SubnetMask 255.255.255.0 -State InActive
#exclude the range 172.16.12.70 through 172.16.12.75 from the new scope
PS C:\> Add-DhcpServerv4ExclusionRange -EndRange 172.16.12.75 -ScopeId 172.16.12.0 `
-StartRange 172.16.12.70
# add a reservation for a file server
PS C:\> Add-DhcpServerv4Reservation -ClientId EE-05-B0-DA-04-00 -IPAddress 172.16.12.88 `
-ScopeId 172.16.12.0 -Description "Reservation for file server"
Set-DhcpServerv4OptionValue -Router 172.16.12.1 -ScopeId 172.16.12.0 #configure a default gateway address for the new scope
Set-DhcpServerv4Scope -State Active #activate
#search DHCP logs
PS C:\Windows\System32\dhcp> Get-Content DhcpSrvLog-*.log | Select-String -Pattern "Update Failed"
PS C:\Windows\System32\dhcp> Get-Content DhcpSrvLog-Fri.log | Select-String -Pattern "Update Failed"
PS C:\Windows\System32\dhcp> Get-Content DhcpSrvLog-Fri.log | Select -Last 50 | Select-String -Pattern "Update Failed"
PS C:\Windows\System32\dhcp> Get-Content DhcpSrvLog-Fri.log | Select -Last 10 #last 10 lines
==========================================================================================================
PS C:\> Get-ChildItem #Get a director y listing (ls, dir, gci)
PS C:\> Copy-Item src.txt dst.txt
PS C:\> Move-Item src.txt dst.tx
#Find text within a file
PS C:\> Select-String –path c:\users\*.txt –pattern password
PS C:\> ls -r c:\users\*.txt -file | % {Select-String -path $_ -pattern password}
PS C:\> Get-Content file.txt
PS C:\> Get-Location #Get present director y (pwd, gl):
PS C:\> Get-Process
#This command will first use the Get-NetTCPConnection cmdlet to get a list of all TCP connections on the local computer.
#The Where-Object cmdlet will then filter the results to only include connections where the OwningProcess property is not null.
#This means that the command will only include connections that are associated with a running process
#The Select-Object cmdlet will then select the LocalPort property and the ProcessName property from the results
Get-NetTCPConnection | Where-Object {$_.OwningProcess -ne $null} | Select-Object LocalPort, @{Name='ProcessName';Expression={(Get-Process -Id $_.OwningProcess).Name}}
PS C:\> Get-Service
Find text within a file:
PS C:\> Select-String –path c:\users\*.txt –pattern password
PS C:\> ls -r c:\users\*.txt -file | % {Select-String -path $_ -
pattern password}
Display file contents (cat, type, gc):
PS C:\> Get-Content file.txt
Get present director y (pwd, gl):
PS C:\> Get-Location
Get a process listing (ps, gps):
PS C:\> Get-Process
Get a ser vice listing:
PS C:\> Get-Service
PS C:\> ls | Format-List –property name #Formatting output of a command (Format-List):
PS C:\> ls –r | Out-Host -paging #Paginating output
PS C:\> Get-FileHash -Algorithm SHA1 file.txt #Get the SHA1 hash of a file
PS C:\> Get-Process | Export-Csv procs.csv #
==========================================================================================================
#search string in sub folders recursively
> Get-ChildItem -path "e:\infrastructure v10" -recurse | where {$_.extension -eq ".txt"} | select-string -pattern "elevated"
==========================================================================================================
#List all installed software
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize > C:\temp\AllInstalledPrograms.txt
Get-WmiObject -Class Win32_Product | Select-Object -Property Name
Get-WmiObject -Class Win32_Product | Select-Object -Property Name,InstallLocation
==========================================================================================================
#Find an username, MAC Address in Active Directory with the IP address
nbtstat -a IP_ADDRESS
#Find current user logged on a computer
psloggedon \\testcomp
==========================================================================================================
#Find a computer in Active Directory with the IP address
Get-ADComputer -filter 'ipv4address -eq "192.168.1.23"'
get-adcomputer -filter 'ipv4address -eq "146.6.21.118"' -properties ipv4address | ft name, ipv4address -auto
==========================================================================================================
Get-Content -Path LineNumbers.txt -TotalCount 5 #gets the first five lines of a file
(Get-Content -Path .\LineNumbers.txt -TotalCount 25)[-1] #gets a specific number of lines from a file and then displays only the last line of that content.
Get-Item -Path .\LineNumbers.txt | Get-Content -Tail 1 #gets the last line of content from a file
Get-Content -Path C:\Temp\* -Filter *.log #gets the content of all *.log files in the C:\Temp directory
Get-Content -Path .\LineNumbers.txt -Raw #get the contents of a file as one string, instead of an array of strings
Get-Content -Path C:\temp\test.txt -AsByteStream -Raw #get the contents of a file as a [byte[]] as a single object
==========================================================================================================
Get-Host | Select-Object Version
$PSVersionTable
==========================================================================================================
#zip the Invoices folder in the root C directory and create an archive called Invoices.zip in the Archives folder
Compress-Archive -Path C:\Invoices -DestinationPath C:\Archives\Invoices
#zip the files in the Invoices folder individually using -LiteralPath instead of –Path,creates an archive with just the two files explicitly listed in the –LiteralPath
Compress-Archive -LiteralPath C:\ Invoices\File1.txt, C:\Invoices\File2.txt -DestinationPath C:\Archives\Invoices -Force
#adds all the files in the Invoices folder to my existing Invoices.zip archive
Compress-Archive -Path C:\Invoices\* -Update -DestinationPath C:\Archives\Invoices
#extracts the contents of the Invoices.zip archive to a folder named InvoicesUnzipped using the Expand-Archive cmdlet
Expand-Archive -LiteralPath C:\Archives\Invoices.Zip -DestinationPath C:\ InvoicesUnzipped
==========================================================================================================
#cmdlet uses the Path parameter to specify the directory C:\Test. Get-ChildItem displays the files and directories in the PowerShell console.
Get-ChildItem -Path C:\Test
Get-ChildItem -Path C:\Test -Name
Get-ChildItem -Path C:\Test\*.txt -Recurse -Force #displays .txt files that are located in the current directory and its subdirectories
Get-ChildItem -Path C:\Parent -Depth 2 #The Depth parameter determines the number of subdirectory levels to include in the recursion
Get-ChildItem -Path C:\Test\* -Include *.txt
Get-ChildItem -Path C:\Test\Logs\* -Exclude A*
Get-ChildItem -Path HKLM:\HARDWARE #uses the Path parameter to specify the registry key HKLM:\HARDWARE
Get-ChildItem -Path Cert:\* -Recurse -CodeSigningCert #The CodeSigningCert parameter gets only certificates that have code-signing authority
Get-ChildItem -Path C:\PathContainingHardLink | Format-Table -View childrenWithHardLink # get hard link information
Get-ChildItem /etc/r* #on Unix systems, the Get-ChildItem provides Unix-like output
gci 'C:\' -rec -force -include *.jar -ea 0 | foreach {select-string "JndiLookup.class" $_} | select -exp Path
findstr /s /i /c:"JndiLookup.class" C:\*.jar
==========================================================================================================
Get-Childitem cert:\LocalMachine\root |format-list #View trusted root certificates
Get-Childitem cert:\LocalMachine\root |format-list | findstr "Forti" #View Fortigate trusted root certificates
Get-ChildItem cert:\LocalMachine\root | Where {$_.NotAfter -lt (Get-Date).AddDays(40)} # expired certificates
#show only the expired certificates
Get-ChildItem -Path Cert:\ -Recurse | Where-Object {$_.NotAfter -lt (Get-Date)}
#display a list of only the certificates that have expired, based on the current date and time
Get-ChildItem -Path Cert:\ -Recurse | Where-Object {$_.NotAfter -lt (Get-Date)} | Select-Object Subject, Issuer, NotAfter
==========================================================================================================
Set-Location -Path "HKLM:\" #sets the current location to the root of the HKLM: drive
Set-Location C:
Set-Location -Path "Env:\" -PassThru
Join-Path -Path $(Get-Location) -ChildPath "\scripts\*.ps1"
Push-Location -Path 'C:\Program Files\PowerShell\' -StackName "Paths" #adds the current location to the Paths stack
Set-Location -StackName "Paths" #makes the Paths location stack the current location stack
Get-Location -Stack # displays the locations in the current location stack
Get-Location #displays your location in the current PowerShell drive.
$pwd #Print Current Directory
$curDir = Get-Location #Current Directory Variable
Write-Host "Current Working Directory: $curDir"
Split-Path -Path $curDir -Parent #parent working directory
Write-Host $PSScriptRoot #current directory of script (ps1)
#PowerShell current directory structure as C:\Backup\01-Sept\sqlbackup.ps1
#gets the relative path from the PowerShell current directory as .\01-Sept\sqlbackup.ps1
$relativePath = Get-Item Backup\01-Sept\sqlbackup.ps1 | Resolve-Path -Relative
==========================================================================================================
#https://en.wikipedia.org/wiki/Environment_variable#Windows
$env:UserName
$env:UserDomain
$env:ComputerName
==========================================================================================================
list all environment variables
Get-ChildItem Env:
==========================================================================================================
This command creates an alias of np for Notepad.
PowerShell
Set-Item -Path alias:np -Value "c:\windows\notepad.exe"
==========================================================================================================
#view the environment variable VAGRANT_PREFER_SYSTEM_BIN on PowerShell on Windows 11
get the value of the system variable PATH
Get-Item Env:PATH
Set-Item Env:VAGRANT_PREFER_SYSTEM_BIN $($env:VAGRANT_PREFER_SYSTEM_BIN ) -Scope User
This command changes the value of the UserRole environment variable to Administrator.
PowerShell
Set-Item -Path env:UserRole -Value "Administrator"
get-item env:VAGRANT_PREFER_SYSTEM_BIN
$env:VAGRANT_PREFER_SYSTEM_BIN
#set the environment variable
$Env:VAGRANT_PREFER_SYSTEM_BIN = 1
==========================================================================================================
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
[String] ${stUserDomain},[String] ${stUserAccount} = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name.split("\")
$(Get-WMIObject -class Win32_ComputerSystem | select username).username
$username=( ( Get-WMIObject -class Win32_ComputerSystem | Select-Object -ExpandProperty username ) -split '\\' )[1]
==========================================================================================================
#Write-Host writes to the console itself. Think of it as a MsgBox in VBScript.
#Write-Output , on the other hand, writes to the pipeline, so the next command can accept it as its input
Write-Host "current user:"
Write-Host $(whoami)
Write-Host "Red on white text." -ForegroundColor red -BackgroundColor white
Write-Host (2,4,6,8,10,12) -Separator ", -> " -ForegroundColor DarkGreen -BackgroundColor White
# The following two statements can be used to effectively suppress output from Write-Host
Write-Host "I won't print" -InformationAction Ignore
Write-Host "I won't print" 6>$null
Write-Host "no newline test " -NoNewline
Write-Host "second string"
Write-Output "Hello world!"
Write-Output $VerbosePreference
==========================================================================================================
#run a script as another user.
$cred = Get-Credential UserTo.RunAs
Run-AsUser.ps1 "whoami; pause" $cred
Run-AsUser.ps1 "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; pause" $cred
param(
[Parameter(Mandatory=$true)]
[string]$script,
[Parameter(Mandatory=$true)]
[System.Management.Automation.PsCredential]$cred
)
Start-Process -Credential $cred -FilePath 'powershell.exe' -ArgumentList 'noprofile','-Command',"$script"
==========================================================================================================
# powershell
$PSVersionTable #check the version of PowerShell
powershell_ise.exe #start The Windows PowerShell Integrated Scripting Environment (ISE)
==========================================================================================================
Execute command2 after execution of command1 has finished
command1 -f & command2
Execute command2 only if execution of command1 has finished successfully
command1 -f && command2
Execute command2 only if execution of command1 has finished unsuccessfully
command1 -f || command2
& "C:\Users\username\Downloads\first_script.ps1" #runs a script stored in the Downloads folder
==========================================================================================================
Set-PSDebug -Trace 2; foreach ($i in 1..3) {$i} #Turns script debugging features on and off, sets the trace level
Set-PSDebug -Step; foreach ($i in 1..3) {$i}
Set-PSDebug -Strict; $NewVar # puts PowerShell in strict mode and attempts to access a variable that doesn't have an assigned valu
Set-PSDebug -Off; foreach ($i in 1..3) {$i}
==========================================================================================================
Get-Command #every command that PowerShell has
Get-Command –Name *IP* # find all cmdlets that contain the word “IP”
Get-Command –Module NetTCPIP –Name *IP*
Get-Command -Module Pester #all commands inside of the Pester module
Get-Help New-NetIPsecQuickModeCryptoProposal #the syntax and how you can use that specific cmdlet
Get-Help Write-Verbose -Online
Update-Help
Get-Process | Get-Member #see the methods and properties that pipe output to Get-Member
Get-Process | Where-Object {$_.Name –eq “iexplore”} #
Get-Process tphkload
Get-Process tphkload –fileversioninfo #path to the executable file
(get-wmiobject win32_process | where{$_.ProcessName -eq 'tphkload'})
(get-wmiobject win32_process | where{$_.ProcessName -eq 'tphkload.exe'}).creationdate
(get-wmiobject win32_process | where{$_.ProcessName -eq 'tphkload.exe'}).getowner | Select -property domain, user
get-wmiobject win32_process | get-member #which properties and methods are available
==========================================================================================================
Get-Process | Out-File -Filepath \testfile.txt
Get-Process | Out-File -Filepath \testfile.txt -NoClobber #f another file exists with the same name and you don’t want your command to overwrite this file
==========================================================================================================
$VerbosePreference = "SilentlyContinue" #set to bypass verbose stream
$VerbosePreference = "Continue" #set to output verbose stream
==========================================================================================================
Get-Service -ComputerName computer -Name servicename
Get-Service -Name "osqueryd" | Restart-Service -Force
Get-Service -Name "osqueryd" | Stop-Service -Force
Get-Service | Where-Object {$_.Status -eq 'Running'} #only running services
get-wmiobject win32_service | format-list Name, Description # service description
Get-Service -ComputerName computername -Name servicename | Restart-Service -Force
Get-Service -ComputerName computername -Name servicename | Stop-Service -Force
Get-Service -ComputerName computername -Name servicename | Start-Service
Get-Service "wmi*" #service names that begin with WMI
"WinRM" | Get-Service #Get a service through the pipeline operator
Get-Service -Displayname "*network*"
Get-Service -Name "win*" -Exclude "WinRM"
Get-Service | Where-Object {$_.Status -eq "Running"} #displays only the services with a status of Running
Get-Service | Sort-Object status
Get-Service "s*" | Sort-Object status
Get-Service "WinRM" -RequiredServices #gets the services that the WinRM service requires
Get-Service | Where-Object {$_.name -eq “osqueryd”}
#services that have dependent services
Get-Service |
Where-Object {$_.DependentServices} |
Format-List -Property Name, DependentServices, @{
Label="NoOfDependentServices"; Expression={$_.dependentservices.count}
}
==========================================================================================================
Start-Service -Name "eventlog"
Start-Service -DisplayName *remote* -WhatIf #shows what would occur if you started the services that have a display name that includes "remote"
#Start a service and record the action in a text file
$s = Get-Service wmi
Start-Service -InputObject $s -PassThru | Format-List >> services.txt
#shows how to start a service when the start type of the service is Disabled
Get-CimInstance win32_service | Where-Object Name -eq "tlntsvr"
Set-Service tlntsvr -StartupType manual
Start-Service tlntsvr
==========================================================================================================
#check public IP,private (viewable within an internal network) or public (can be seen by other machines on the Internet)
#3rd party web-sites
> (Invoke-WebRequest icanhazip.com/ip).Content.Trim()
> (Invoke-WebRequest ifconfig.me/ip).Content.Trim()
> (Invoke-WebRequest ifconfig.co/ip).Content.Trim()
> (Invoke-WebRequest ident.me/ip).Content.Trim()
==========================================================================================================
Get-WindowsCapability -Online -Name "SNMP*" #verify if the SNMP service is installed,the elevated PowerShell console
==========================================================================================================
==========================================================================================================
powershell scripts
==========================================================================================================
==========================================================================================================
#the last logon times of each computer in the domain
$dcs = Get-ADComputer -Filter { OperatingSystem -NotLike '*Server*' } -Properties OperatingSystem
foreach($dc in $dcs) {
Get-ADComputer $dc.Name -Properties lastlogontimestamp |
Select-Object @{n="Computer";e={$_.Name}}, @{Name="Lastlogon"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}
}
==========================================================================================================
#from bash to pwsh
pwsh -c " /path-to/script.ps1 -Param1 ABC -Param2 @{ 'key'='value' } "
==========================================================================================================
'{0:yyyy-MMM-dd}' -f $convertDate ## Convert datetime to yyyy-mmm-dd datetime format
==========================================================================================================
#query user
> whoami
> (whoami).Split('\')[1]
> whoami /fqdn
> whoami /upn
> get-childitem env:\username
> (Get-ChildItem Env:\USERNAME).Value #username only
> ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name).Split('\')[1]
> [System.Security.Principal.WindowsIdentity]::GetCurrent()
qwinsta /server:dc1 # list the sessions on DC1
quser /server:dc1
(Get-WMIObject -ClassName Win32_ComputerSystem).Username
==========================================================================================================
#troubleshoot connectivity
#By default, Test-NetConnection uses TCP protocol to test the connection
Test-NetConnection -ComputerName 192.168.0.1 -Port 80 -Protocol UDP -InformationLevel Detailed
Test-NetConnection -ComputerName 192.168.0.1 -Port 80 -InformationLevel Detailed
==========================================================================================================
Get-NetTCPConnection: displays a list of all TCP connections on a system
Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, OwningProcess
#run the command continuously for a specific period of time
#creates a loop that runs the "Get-NetTCPConnection" command every 5 seconds for 1 minute (12 loops)
for ($i=1; $i -le 12; $i++) { Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, OwningProcess; Start-Sleep -Seconds 5 }
Get-NetUDPEndpoint: displays a list of all UDP endpoints on a system
Get-NetUDPEndpoint | Select-Object LocalAddress, LocalPort, OwningProcess
Invoke-Command: runs a command on a remote computer
New-PSDrive: creates a new PowerShell drive that maps to a network share or a local folder.
Get-Content: displays the contents of a file
Set-Content: writes or replaces the content in a file
Invoke-Item: opens a file or starts an application
New-Item: creates a new file or folder
Remove-Item: deletes a file or folder
Get-Process: displays a list of all running processes on a system
Stop-Process: stops a specified process or a group of processes
============================================================================
#powershell
PS C:\> 1..255 | % {echo "10.10.10.$_";ping -n 1 -w 100 10.10.10.$_ | Select-String ttl} #ping sweep
PS C:\> 1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.10.10.10",$_)) "Port $_ is open!"} 2>$null #port scan
PS C:\> (New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/nc.exe","nc.exe") #Fetch a file via HTTP (wget in PowerShell)
PS C:\> Get-ChildItem "C:\Users\" -recurse -include *passwords*.txt #Find all files with a par ticular name
PS C:\> Get-HotFix #Get a listing of all installed Microsoft Hotfixes
#Navigate the Windows registry
PS C:\> cd HKLM:\
PS HKLM:\> ls
PS C:\> Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\run #List programs set to star t automatically in the registr y
PS C:\> [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("PSFTW!")) #Conver t string from ascii to Base64
#List and modify the Windows firewall rules
PS C:\> Get-NetFirewallRule –all
PS C:\> New-NetFirewallRule -Action Allow -DisplayName LetMeIn -
RemoteAddress 10.10.10.25
==========================================================================================================
# information gathering, ChatGPT
Get-NetAdapter: displays a list of network adapters on a system, along with their configuration information.
Get-NetIPAddress: displays a list of IP addresses assigned to a system, along with their configuration information.
Get-NetRoute: displays a list of routing table entries on a system, which can help to identify the network topology.
Get-NetTCPConnection: displays a list of all TCP connections on a system, which can help to identify active connections and the remote systems they are connected to.
Get-NetUDPEndpoint: displays a list of all UDP endpoints on a system, which can help to identify active connections and the remote systems they are connected to.
Get-Process: displays a list of all running processes on a system, along with their resource usage.
Get-Service: displays a list of all running services on a system, along with their configuration information.
Get-EventLog: displays the contents of an event log, which can provide insight into system events and errors.
Get-WmiObject: allows you to retrieve information from the Windows Management Instrumentation (WMI) database, which contains a wealth of information about system configuration and performance.
Get-Hotfix: displays a list of installed hotfixes and updates on a system.
==========================================================================================================
#DNS enumeration, ChatGPT
Resolve-DnsName: allows you to resolve a DNS name to an IP address, and vice versa. You can use this command to perform forward and reverse DNS lookups.
Test-Connection: allows you to test the connectivity to a remote host or IP address. This command can be used to check if a DNS server is online and responsive.
Get-DnsServerZone: allows you to retrieve the DNS zones that are hosted on a specific DNS server. This command can be used to discover the names of subdomains or hosts within a domain.
Get-DnsServerResourceRecord: allows you to retrieve the DNS resource records for a specified DNS zone. This command can be used to discover the types of DNS records associated with a domain, such as MX, A, CNAME, and NS records.
Resolve-DnsName -type MX: allows you to retrieve the mail exchange (MX) records for a specified domain. This command can be used to discover the email servers associated with a domain.
Resolve-DnsName -type SRV: allows you to retrieve the service (SRV) records for a specified domain. This command can be used to discover the network services associated with a domain, such as Active Directory domain controllers, LDAP servers, or SIP servers.
Get-DnsClientCache: allows you to retrieve the DNS cache entries that are stored on a local machine. This command can be used to discover the DNS resolutions that have been performed recently.
nslookup: although not a PowerShell command, nslookup is a commonly used command-line tool for DNS enumeration. It allows you to perform DNS queries and display the results.
==========================================================================================================
#In order to find out what user stopped the Windows Event Log, you can use the following PowerShell commands, ChatGPT
PS HKLM:\> Stop-Service -Name "eventlog" -Force
PS HKLM:\> Start-Service -Name "eventlog"
PS HKLM:\> Get-WinEvent -FilterHashtable @{LogName='Security'; ID=1100} -MaxEvents 50
ProviderName: Microsoft-Windows-Eventlog
TimeCreated Id LevelDisplayName Message
----------- -- ---------------- -------
2/18/2023 2:35:13 AM 1100 Information The event logging service has shut down.
2/18/2023 1:41:43 AM 1100 Information The event logging service has shut down.
2/15/2023 9:59:07 AM 1100 Information The event logging service has shut down.
2/10/2023 8:04:13 AM 1100 Information The event logging service has shut down.
2/9/2023 11:43:27 PM 1100 Information The event logging service has shut down.
#Clear the log events
PS HKLM:\> wevtutil cl Security
PS HKLM:\> Get-WinEvent -FilterHashtable @{LogName='Security'; ID=1102} -MaxEvents 50 | ForEach-Object { $_.Properties }
#The method to find the PID of the svchost.exe process associated with the Windows Event Log service , chatGPT
Get-WmiObject -Class Win32_Service -Filter "Name='eventlog'" | Select-Object -ExpandProperty ProcessId
#Sure, here's how you can list the Thread IDs (TIDs) of all the threads running in a specific process using Sysinternals tools in Windows 10:
>> Get-WmiObject Win32_Thread -Filter "ProcessHandle=9248" | Select-Object Handle
Cmdlets are small scripts that follow a dashseparated verb-noun convention such as "Get-Process".
New- Creates a new resource
Set- Modifies an existing resource
Get- Retrieves an existing resource
Read- Gets information from a source, such as a file
Find- Used to look for an object
Search- Used to create a reference to a resource
Star t- (asynchronous) begin an operation, such as starting a process
Invoke- (synchronous) perform an operation such as running a command
Objects:
The output of most cmdlets are objects that can be passed to other cmdlets and further
acted upon. This becomes important in pipelining cmdlets
get a list of all available cmdlets
PS C:\> Get-Command
PS C:\> gcm *[string]*
filter cmdlets on the verb set
PS C:\> Get-Command Set*
PS C:\> Get-Command *Process
PS C:\> Get-Help <cmdlet>
PS C:\> Get-Help <cmdlet> -detailed
PS C:\> Get-Help <cmdlet> -examples
PS C:\> help [cmdlet] -examples
PS C:\> Get-Help <cmdlet> -full
PS C:\> Get-Help <cmdlet> -online
list available aliases (alias alias)
PS C:\> Get-Alias
PS C:\> alias <unknown alias>
PS C:\> get-child<TAB>
PS C:\> ls –recurse s equivalent to PS C:\> ls -r
Searches for strings in files or output, like grep
PS C:\> Select-String
PS C:\> sls –path [file] –pattern [string]
Takes each item on pipeline and handles it as $_
PS C:\> ForEach-Object { $_ }
PS C:\> [cmdlet] | % { [cmdlet] $_ }
ForEach-Object in the pipeline (alias %)
PS C:\> ls *.txt | ForEach-Object {cat $_}
Piping cmdlet output to another cmdlet
PS C:\> Get-Process | Format-List –property name
Where-Object condition (alias where or ?)
PS C:\> Get-Process | Where-Object {$_.name –eq "notepad"}
Generating ranges of numbers and looping
PS C:\> 1..10
PS C:\> 1..10 | % {echo "Hello!"
Creating and listing variables
PS C:\> $tmol = 42
PS C:\> ls variable
Examples of passing cmdlet output down pipeline
PS C:\> dir | group extension | sort
PS C:\> Get-Service dhcp | Stop-Service -PassThru | Set-Service
-StartupType Disabled
==========================================================================================================
#ChatGPT
Get-ADUser -Filter {Surname -eq "Doe"} -Properties SamAccountName #find a user's logon name by their last name
Get-ADUser -Filter {GivenName -eq "FIRST_NAME"} -Properties SamAccountName #find a user's logon name by their first name
Get-ADUser -Filter {(GivenName -eq "FIRST_NAME") -and (Surname -eq "LAST_NAME")} -Properties SamAccountName
==========================================================================================================
#ChatGPT
#find computer accounts that haven't been used in the last 90 days
#use the -ComputersOnly parameter to limit the search to computer accounts only,
#and the -AccountInactive parameter to specify the number of days of inactivity before an account is considered inactive.
Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 90.00:00:00 `
| Export-CSV "d:\pwsh_reports\inactive_computer_accounts_last90days.csv"
Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 180.00:00:00 `
| Export-CSV "d:\pwsh_reports\inactive_computer_accounts_last180days.csv"
Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 365.00:00:00 `
| Export-CSV "d:\pwsh_reports\inactive_computer_accounts_last365days.csv"
# more than one year
Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 365.00:00:00 `
| ForEach-Object { Get-ADComputer $_ -Properties LastLogonTimestamp, OperatingSystem, OperatingSystemServicePack, DistinguishedName } `
| Where-Object { $_.LastLogonTimestamp.Ticks -lt (Get-Date).AddDays(-365).Ticks -and $_.DistinguishedName -notmatch "CN=Computers,CN=Accounts" } `
| Select-Object Name, OperatingSystem, OperatingSystemServicePack, LastLogonTimestamp `
| Export-Csv -Path "d:\pwsh_reports\inactive_computer_accounts.csv" -NoTypeInformation
# more than two years
Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan 730.00:00:00 `
| ForEach-Object { Get-ADComputer $_ -Properties LastLogonTimestamp, OperatingSystem, OperatingSystemServicePack, DistinguishedName } `
| Where-Object { $_.LastLogonTimestamp.Ticks -lt (Get-Date).AddDays(-730).Ticks -and $_.DistinguishedName -notmatch "CN=Computers,CN=Accounts" } `
| Select-Object Name, OperatingSystem, OperatingSystemServicePack, LastLogonTimestamp `
| Export-Csv -Path "C:\Reports\InactiveComputers.csv" -NoTypeInformation
==========================================================================================================
#check if a computer is joined to a domain, domain member
Test-ComputerSecureChannel -Server SERVERNAME #not IP but hostname
==========================================================================================================
#create scheduled task with command prompt/powershell
schtasks /create /tn "FailedLogins" /tr "C:\scripts\failed_logins.ps1" /sc DAILY /st 00:00 /st 12:00
schtasks /create /tn "Failed Login Attempts" /tr "C:\tmp\pwsh scripts\Failed Login Attempts.ps1" /sc DAILY /st 00:00 /st 09:06
schtasks /create /tn "MyDailyScript" /tr "powershell.exe -File C:\Scripts\MyScript.ps1" /sc daily /st 10:00
schtasks /create /tn "Failed Login Attempts" /tr "powershell.exe -File C:\tmp\pwsh scripts\Failed Login Attempts.ps1" /sc daily /st 09:10
==========================================================================================================
#windows 11
Register-ScheduledTask -TaskName "MyTask" -Trigger (New-ScheduledTaskTrigger -Daily -At "12:00 AM") -Action (New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File 'C:\Path\to\Script.ps1' -WindowStyle Hidden")
$Action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File 'D:\pwsh_scripts\computer_name_from_IP_addresses.ps1' -WindowStyle Hidden"
$Trigger = New-ScheduledTaskTrigger -Daily -At "12:00 AM"
$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -StartWhenAvailable
Register-ScheduledTask -TaskName "MyTask" -Trigger $Trigger -Action $Action -Settings $Settings
c
Register-ScheduledTask -TaskName "MyTask" -Trigger (New-ScheduledTaskTrigger -Daily -At "12:00 AM") -Action (New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File 'C:\Path\to\Script.ps1' -WindowStyle Hidden")
Save-ScheduledTask -TaskName "MyTask"
$Action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File 'D:\pwsh_scripts\computer_name_from_IP_addresses.ps1' -WindowStyle Hidden"
$Trigger = New-ScheduledTaskTrigger -Daily -At "12:00 AM"
$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -StartWhenAvailable
Register-ScheduledTask -TaskName "MyTask" -Trigger $Trigger -Action $Action -Settings $Settings
Save-ScheduledTask -TaskName "MyTask"
====================================================================================================================================================================================================================
#Check password expiration status
Get-ADUser john.doe -Properties PasswordLastSet, PasswordExpired
Get-ADUser john.doe -Properties PasswordExpired
Get-ADUser john.doe -Properties PasswordLastSet
Get-ADUser john.doe -Properties PasswordLastSet, PasswordExpired, EmailAddress, DisplayName
Get-ADUser john.doe, jane.smith, alex.brown -Properties PasswordExpired
====================================================================================================================================================================================================================
#ChatGPT
#This command first checks if the group "SG_PowerBi" exists using Get-ADGroup. If the group exists, it then checks if the user "arhodes" exists using Get-ADUser. If both conditions are true, it executes the Add-ADGroupMember command. If the user or group does not exist, it prints an appropriate error message and exits without running the rest of the command.
if ((Get-ADGroup -Filter {Name -eq "SG_PowerBi"})) { if ((Get-ADUser -Filter {SamAccountName -eq "arhodes"})) { Add-ADGroupMember -Identity "SG_PowerBi" -Members arhodes } else { Write-Host "User 'arhodes' does not exist." } } else { Write-Host "Group 'SG_PowerBi' does not exist." }
# Adding user Alan Rhodes to the group SG_PowerBi
Add-ADGroupMember -Identity "SG_PowerBi" -Members arhodes
# verify the member, list members
Get-ADGroupMember -Identity "SG_PowerBi" | ft
# Adding the users Alan Rhodes, Flenn Parker and Mike Reyes to the group SG_PowerBi
Add-ADGroupMember -Identity "SG_PowerBi" -Members arhodes, fparker, mreyes
# Get all users with the job title "Account Manager" and add them to the group SG_PowerBi
Get-ADUser -Filter "title -eq 'account manager'" | ForEach-Object { Add-ADGroupMember -Identity "SG_PowerBi" -Members $_ }
# Get all the users from the group Sales Management and add them to the group SG_PowerBi
Get-ADGroupMember -Identity "Sales Management" | ForEach-Object { Add-ADGroupMember -Identity "SG_PowerBi" -Members $_ }
# add the group “Sales Management” to the group “SG_PowerBi”
Add-ADGroupMember -Identity "SG_PowerBi" -Members "Sales Management"
====================================================================================================================================================================================================================
#check if the host is a domain member on windows server 2019 standard In the PowerShell window
Get-WmiObject -Class Win32_ComputerSystem | Select-Object Domain
====================================================================================================================================================================================================================
ChatGPT
Press Win + X and select "Windows PowerShell" or "Windows PowerShell (Admin)"
To compare the contents of two folders on your Windows 10 desktop (one on your USB drive and one on your desktop) to find out what has changed,
$desktopFolder = Get-ChildItem -Path "C:\Users\<YourUsername>\Desktop\YourFolder" -Recurse
$usbFolder = Get-ChildItem -Path "E:\YourFolder" -Recurse
Compare-Object -ReferenceObject $desktopFolder -DifferenceObject $usbFolder
====================================================================================================================================================================================================================
get a list of directories
Get-ChildItem -Directory
====================================================================================================================================================================================================================
====================================================================================================================================================================================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment