Powershell Tips
Tips and links.
This list will be regularly updated.
Threat hunting with event logs
https://www.sans.org/blog/working-with-event-log-part-2-threat-hunting-with-event-logs/
Equivalent of grep for a recursive search
$> ls -r *.txt | Select-String "ZIP"
$> ls -r | Select-String dummy | select line,path
Find which process is currently listening on a port
netstat -ano -p tcp | Select-String 8888
Find a service by name, and stop it by name
# Stop service
Get-Service | Where {$_.DisplayName -like "*elnet*"} | Stop-Service
Get-Service -DisplayName "telnet" | Stop-Service
# Format display result
Get-Service -Name "telnet" | Format-List -Property Name, DependentServices
# Stop a service that has dependent services
Stop-Service -Name "telnet" -Force -Confirm -WhatIf
# Force option : option required to stop a service that has some dependent services
# Confirm option : required if you want a prompt for confirmation before all the dependent services are stopped
# WhatIf option : Show what would happen if the cmdlet ist executed. The cmdlet is not executed.
Stop-Service -Name "WebDev 19" -Force -Confirm -WhatIf
# Result is : What if: Performing the operation "Stop-Service" on target "Serveur d'Application WebDev 19 (PC SOFT) (WebDev 19)".
# Start service
Get-Service -DisplayName "telnet" | Start-Service
Find process by name, and stop it by it’s id
Get-Service | Where {$_.DisplayName -like "*w19*"}
# Alternative :
Get-WmiObject Win32_Process | select commandline | Select-String -Pattern "wd19*"
Get-Process | Where {$_.ProcessName -Like "*wd19*"}
Get-Service -Name "WebDev 19"
# Get process IDs
Get-Process | Where {$_.ProcessName -Like "*svchost"} | select -expand id
# Stop one or more process
Stop-Process -Name "w190admin" -Force -WhatIf
Execute cmd file on a windows server from a linux server
Through ssh, you can install ssh on the windows server just follow the instructions here: https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse?tabs=powershell
- A device running at least Windows Server 2019 or Windows 10 (build 1809).
- PowerShell 5.1 or later.
- An account that is a member of the built-in Administrators group.
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'
# Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
# Install the OpenSSH Server
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
# Start the sshd service
Start-Service sshd
# OPTIONAL but recommended:
Set-Service -Name sshd -StartupType 'Automatic'
# Confirm the Firewall rule is configured. It should be created automatically by setup. Run the following to verify
if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) {
Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..."
New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
} else {
Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists."
}
Now from a linux server:
ssh Administrator@172.30.XXX.XXX '"C:\nicotest\nicotest.cmd"'
REM Example of source code of nicotest.cmd @echo off set path_exe=C:\nicotest cd %path_exe% echo Nico test at %Date% %time% >> %path_exe%\nicotest.log
Delete files older than x days
$limit = (Get-Date).AddDays(-15)
Get-ChildItem -Path "C:\Oracle\diag" -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limit } | Remove-Item -Force
# FYI
# !$_.PSIsContainer true corresponds to a file
# $_.PSIsContainer true corresponds to a directory
# or like this is equivalent :
Get-ChildItem "C:\Oracle\diag" -Recurse -File | Where LastWriteTime -lt $limit | Remove-Item -Force
# Before you execute you can test which files will be deleted :
Get-ChildItem -Path "C:\Oracle\diag" -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limit } | Select-Object -Property FullName, CreationTime, LastWriteTime
# You can filter file name with the condition $_.DisplayName -like "*filenameSearched*"
Get-ChildItem -Path "C:\Oracle\diag" -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limit -and $_.Name -like "*.trm" } | Select-Object -Property FullName, CreationTime, LastWriteTime
Execute all scripts inside a directory which is inside current dir
$target_dir = Join-Path -Path $PWD.Path -ChildPath "\clean_logs"
Get-ChildItem $target_dir | ForEach-Object {
# Execut each script inside target_dir
& $_.FullName
}
Show last system boots
A useful script from https://thesysadminchannel.com
Function Get-RebootHistory {
<#
.SYNOPSIS
This will output who initiated a reboot or shutdown event.
.NOTES
Name: Get-RebootHistory
Author: theSysadminChannel
Version: 1.0
DateCreated: 2020-Aug-5
.LINK
https://thesysadminchannel.com/get-reboot-history-using-powershell -
.EXAMPLE
Get-RebootHistory -ComputerName Server01, Server02
.EXAMPLE
Get-RebootHistory -DaysFromToday 30 -MaxEvents 1
.PARAMETER ComputerName
Specify a computer name you would like to check. The default is the local computer
.PARAMETER DaysFromToday
Specify the amount of days in the past you would like to search for
.PARAMETER MaxEvents
Specify the number of events you would like to search for (from newest to oldest)
#>
[CmdletBinding()]
param(
[Parameter(
Mandatory = $false,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[string[]] $ComputerName = $env:COMPUTERNAME,
[int] $DaysFromToday = 7,
[int] $MaxEvents = 9999
)
BEGIN {}
PROCESS {
foreach ($Computer in $ComputerName) {
try {
$Computer = $Computer.ToUpper()
$EventList = Get-WinEvent -ComputerName $Computer -FilterHashtable @{
Logname = 'system'
Id = '1074', '6008'
StartTime = (Get-Date).AddDays(-$DaysFromToday)
} -MaxEvents $MaxEvents -ErrorAction Stop
foreach ($Event in $EventList) {
if ($Event.Id -eq 1074) {
[PSCustomObject]@{
TimeStamp = $Event.TimeCreated
ComputerName = $Computer
UserName = $Event.Properties.value[6]
ShutdownType = $Event.Properties.value[4]
}
}
if ($Event.Id -eq 6008) {
[PSCustomObject]@{
TimeStamp = $Event.TimeCreated
ComputerName = $Computer
UserName = $null
ShutdownType = 'unexpected shutdown'
}
}
}
} catch {
Write-Error $_.Exception.Message
}
}
}
END {}
}