Windows
which version of powershell is installed
$PSVersionTable
hibernate
powercfg.exe -h off
enable powershell
set-executionpolicy unrestricted
Configure network
- Static ip.
netsh interface ip set address name="Local Area Connection" static 192.168.122.41 255.255.255.0 192.168.122.1 1
- Dhcp
netsh interface is set address name="Local Area Connection" dhcp
- extract msi
msiexec /a "C:\software.msi" /qb TARGETDIR="C:\Folder"
restart network
route -f ipconfig /release ipconfig /renew arp -d * nbtstat -R nbtstat -RR ipconfig /flushdns ipconfig /registerdns
Profile
- Profile
C:\Users\abjorklund\AppData\Roaming\Microsoft\Windows\Start Menu
restart via rdesktop
CTRL + ALT + END
alternative shutdown
Shutdown with restart
shutdown /t 0 /r /f
Shutdown
shutdown /t 0 /s /f
logoff
shutdown /l /f
change password
Start a command prompt as administrator.
net user username password
remove cached passwords
list/remove cached passwords graphically
rundll32.exe keymgr.dll,KRShowKeyMgr
list/remove cached passwords cli
cmdkey /list
is your account locked. bat file
@echo off :again date /t & time /t net user /domain mdinkel > c:\temp\mdinkel find "active" c:\temp\mdinkel timeout 10 goto again
unlock account
Net user username /DOMAIN /active:YES
Browse active dirctory structure
adsiedit.msc
time zone conversion
Here you can convert from Windows to unix time zones tz.
http://www.unicode.org/cldr/charts/latest/supplemental/zone_tzid.html
uptime
net statistics server
Uptime and other information
systeminfo /FO CSV | ConvertFrom-CSV
credetial manager empty cache
rundll32.exe keymgr.dll,KRShowKeyMgr
remote powershell pssession
Create pssession.
$secpasswd = ConvertTo-SecureString "*************" -AsPlainText -Force $mycreds = New-Object System.Management.Automation.PSCredential ("domain\user", $secpasswd) New-PSSession -ComputerName 10.111.222.5 -Credential $mycreds
get pssessions.
get-pssession
enter pssession
Enter-PSSession -Name Enter-PSSession -ComputerName 10.50.197.70 Enter-PSSession 172.18.1.198 -Credential domain\uer
remove pssession
remove-pssession -name Session15
Run remote command.
Invoke-Command -name "Session14" -ScriptBlock { hostname }
Login to remote machine
Enter-PSSession 10.50.197.70 -Credential $mycreds
PowerShell
gc
Get-content. Print content of file.
gc c:\temp\file.txt
Set-content
Set-Content -path REMOTE\Filename.txt
Out-File
Out-File -Encoding UTF8
replace text in file
Get-Content REMOTE\Filename.txt | foreach-object { $_ -replace "OLD", "NEW" } | Set-Content REMOTE\Filename.txt
get-service
Status of one service.
get-service ipeventwatcher
status of all services.
Get-Service
stop-service
stop-service ipeventwatcher
restart-service
restart-service ipremote -force
start-service
start-service ipeventwatcher
variable
Set variable to content of file.
$a = gc IPremote.exe.config
md5sum
[CmdletBinding(SupportsShouldProcess=$False)] param([string]$File) function Get-Checksum([string]$strInFile) { $objCrypto = New-Object "System.Security.Cryptography.MD5CryptoServiceProvider" $objFile = Get-Item $strInFile $objStream = $objFile.OpenRead() $objBytes = $objCrypto.ComputeHash($objStream) $strChecksum = "" foreach($objByte in $objBytes) { $strChecksum += $objByte.ToString('x2') } $objStream.Close() | Out-Null return $strChecksum } $strFileToCheck = $File if(Test-Path($strFileToCheck)) { Get-Checksum $strFileToCheck }
Get md5sum of all files.
gci * | Get-FileHash -Algorithm md5 | ft Hash,@{n="File";e={(Get-item $_.Path).Name}}
tcp connect
nc, netcat
(New-Object Net.Sockets.TcpClient).Connect("1.2.3.4",80) $Tcp = New-Object Net.Sockets.TcpClient;$Tcp.BeginConnect("1.2.3.4", 80, $null, $null).AsyncWaitHandle.WaitOne(5000);$Tcp.Close() New-Object System.Net.Sockets.TCPClient -ArgumentList "1.2.3.4",3389 Test-NetConnection -ComputerName 192.168.122.1 -InformationLevel Detailed -port 23
Latest and greatest.
$Computer="127.0.0.1"; $Port=20010; $Socket = New-Object Net.Sockets.TcpClient;($Socket.BeginConnect($Computer, $Port, $Null, $Null)).AsyncWaitHandle.WaitOne(200);$Socket.Close();
grep
gc IPremoteDebug.log | select-string "ip2date"
grep recursive
dir -Recurse | Select-String -pattern "192.168.19.102"
list processes
Get-Process
restart processes
get-process -name powershellserver | stop-process
clear content
Clear-Content filename.doc
dir recursive
dir /a/s/b filename.txt
dir recursive
'Get-ChildItem "c:\program files\" -rec | ForEach-Object -Process {$_.FullName}' 'Get-ChildItem . -recurse -force | ForEach-Object -Process {$_.FullName}'
dir filename size
'get-childitem "C:\Program Files\directory" -rec | where {!$_.PSIsContainer} | select-object Name, Length'
dir human readable file size
function
Function Format-FileSize() { Param ([int]$size) If ($size -gt 1TB) {[string]::Format("{0:0.00} TB", $size / 1TB)} ElseIf ($size -gt 1GB) {[string]::Format("{0:0.00} GB", $size / 1GB)} ElseIf ($size -gt 1MB) {[string]::Format("{0:0.00} MB", $size / 1MB)} ElseIf ($size -gt 1KB) {[string]::Format("{0:0.00} kB", $size / 1KB)} ElseIf ($size -gt 0) {[string]::Format("{0:0.00} B", $size)} Else {""} }
command
Get-ChildItem | Select-Object Name, @{Name="Size";Expression={Format-FileSize($_.Length)}}
base64
decode base64 string
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
troubleshooting network
netstat -ano | findstr <ipremote-pid>
diff
Compare two files.
compare-object (get-content one.txt) (get-content two.txt)
log file. Eventlog
List event logs.
Get-EventLog -list
List evnts in a log.
Get-EventLog -LogName IPremoteLog
List events sins date.
Get-EventLog -LogName Application -after "den 5 november 2014 10:00:00"
date
Get-Date
full output
Print all variable with full output
'(Get-Variable).StdOut'
Send output to line like the following to get more output.
| Ft -autosize | out-string -width 4096
restart services via samba
install samba-common
yum install samba-common
List services.
net rpc service list -I IPADDRESS -U USERNAME%PASSWORD
Stop service.
net rpc service start ipremote -I IPADDRESS -U 'user%password'
Start service.
net rpc service start ipeventwatcher -I IPADDRESS -U 'user%password'
Windows version
[System.Environment]::OSVersion.Version http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833%28v=vs.85%29.aspx (Get-WmiObject -class Win32_OperatingSystem).Caption
Which architecture.
gwmi win32_operatingsystem | select osarchitecture
Is proxy bypassed
$url = "http://10.127.12.10";$webclient = New-Object System.Net.WebClient; $webclient.Proxy.IsBypassed($url)
curl
(Invoke-WebRequest http://localhost/Requests -UseBasicParsing).content
wget
Invoke-WebRequest -Uri "http://1.2.3.4/file.txt" -OutFile "file.txt"
turn of index services when computer is not used
In stopindexer enter the line
net stop wsearch
In the startindexer enter the line
net start wsearch
robocopy(backup)
robocopy C:\Users\user_name\Documents h:\backup\user_name /e /mir /np /log+:c:\temp\backup_log.txt
number of cpus
Get-WmiObject -class Win32_processor | ft systemname,Name,DeviceID,NumberOfCores,NumberOfLogicalProcessors, Addresswidth
cpu_usage
Get-Counter '\Process(*)\% Processor Time'| Select-Object -ExpandProperty countersamples | Select-Object -Property instancename, cookedvalue| Sort-Object -Property cookedvalue -Descending| Select-Object -First 20| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100).toString('P')}} -AutoSize | Ft -autosize | out-string -width 4096 Get-WmiObject win32_processor | select LoadPercentage |fl
Stats and all processes. Including process running under svhost.
$CpuInfo = Get-WmiObject -Namespace "root\cimv2" -Class Win32_PerfFormattedData_PerfOS_Processor;$MemInfo = Get-WmiObject -Namespace "root\cimv2" -Class Win32_PerfFormattedData_PerfOS_Memory;$SysInfo = Get-WmiObject -Namespace "root\cimv2" -Class Win32_PerfFormattedData_PerfOS_System;$PrcInfo = Get-WmiObject -Namespace "root\cimv2" -Class Win32_PerfFormattedData_PerfProc_Process;$SvcInfo = Get-WmiObject -Namespace "root\cimv2" -Class Win32_Service;$GeneralInfo = @{};$ProcOutput = @();$ServiceTable = @{};$GeneralInfo.Add("_Name", $env:COMPUTERNAME);$GeneralInfo.Add("ProcessorQueueLength", $SysInfo.ProcessorQueueLength);$GeneralInfo.Add("PercentInterruptTime", $($a = $CpuInfo | %{$_.PercentInterruptTime}; $a -join " "));$GeneralInfo.Add("AvailableMBytes", $MemInfo.AvailableMBytes);$GeneralInfo.Add("PercentIdleTime", $($a = $CpuInfo | %{$_.PercentIdleTime}; $a -join " "));$GeneralInfo.Add("PercentPrivilegedTime", $($a = $CpuInfo | %{$_.PercentPrivilegedTime}; $a -join " "));$GeneralInfo.Add("TotalMemory", (Get-WmiObject Win32_ComputerSystem | %{$_.TotalPhysicalMemory}));$GeneralInfo.Add("PercentProcessorTime", $($a = $CpuInfo | %{$_.PercentProcessorTime}; $a -join " "));$GeneralInfo.Add("CacheBytes", $MemInfo.CacheBytes);$GeneralInfo.Add("PercentUserTime", $($a = $CpuInfo | %{$_.PercentUserTime}; $a -join " "));$GeneralInfo.Add("CommittedBytes", $MemInfo.CommittedBytes);$GeneralInfo.GetEnumerator() | Sort-Object -Property Name | ForEach-Object {Write-Host -Object ($_.Name + ": ") -NoNewline; Write-Host -Object $_.Value};foreach($Service in $SvcInfo) {$ProcId = $Service.ProcessId.ToString();if($ProcId -ne "0") {if($ServiceTable.ContainsKey($ProcId)) {$Value = $ServiceTable.Get_Item($ProcId);$Value += $Service.Name;$ServiceTable.Set_Item($ProcId, $Value);} else {$ServiceTable.Add($ProcId, @($Service.Name));}}}foreach($proc in $PrcInfo) {$Obj = New-Object psobject;$Obj | Add-Member -MemberType NoteProperty -Name "Process" -Value $proc.Name;$Obj | Add-Member -MemberType NoteProperty -Name "CPU" -Value $proc.PercentProcessorTime;$Obj | Add-Member -MemberType NoteProperty -Name "Thread" -Value $proc.ThreadCount;$Obj | Add-Member -MemberType NoteProperty -Name "Handle" -Value $proc.HandleCount;$Obj | Add-Member -MemberType NoteProperty -Name "Services" -Value ($ServiceTable.Get_Item($proc.IDProcess.ToString()) -join ",");$ProcOutput += $Obj;}$ProcOutput | ft -AutoSize
Sort processes by mem usage.
get-wmiobject WIN32_PROCESS | Sort-Object -Property ws -Descending|select -first 20|Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.ws / 1mb)}},@{Name="ProcessID";Expression={[String]$_.ProcessID}},@{Name="UserID";Expression={$_.getowner().user}} | Ft -autosize | out-string -width 4096
total memory in machine
Get-WMIObject -class win32_physicalmemory | Format-Table devicelocator, capacity -a
how much memory is free in GB
$freemem = Get-WmiObject -Class Win32_OperatingSystem; echo ([math]::round(($freemem.FreePhysicalMemory / 1024 / 1024), 2))
disk usage
Get-PSDrive
tail
Get-Content [filename] | Select-Object -Last 10
wc count lines
Get-Content C:\temp\ERRORLOG.5 | Measure-Object -line
disable firewall
From the command line
netsh advfirewall set allprofiles state off
Using Powershell
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
which firewall profiles are available
get-netfirewallprofile | select name,DefaultInboundAction,DefaultOutBoundAction | ft -a
which firewall profile is being used
get-NetConnectionProfile
which ports are open
Get-NetFirewallRule | Where { $_.Enabled -eq "True" -and $_.Direction -eq "Inbound" }
which rules exist
Get-NetFirewallRule
open port in firewall
netsh advfirewall firewall add rule name="Open Port 80" dir=in action=allow protocol=TCP localport=80
firewall get more info about opening
get-netfirewallrule -DisplayName "Remote Desktop - User Mode (TCP-In)"
add administrative user
Create user
net user /add root [password]
This creates the user account.
net localgroup administrators root /add
Which process is using port
# Which process is using port. netstat -nao | findstr :22 TCP 0.0.0.0:22 0.0.0.0:0 LISTENING 1916 # Which process has pid. get-process | findstr 1916 355 40 48752 56056 621 6,45 1916 PowerShellServer # which process has pid. tasklist | findstr 1916 PowerShellServer.exe 1916 Services 0 56.072 K
which version is installed
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table -AutoSize
list drives
get-psdrive wmic logicaldisk get caption
svchost.exe what is happening
tasklist /svc /fi “IMAGENAME eq svchost.exe”
computer management
Start computer management
compmgmt.msc
msinfo32
Generate report.
msinfo32
licensing
Get-wmiobject SoftwareLicensingProduct -ComputerName localhost | Where-Object {$_.ApplicationID -eq '55c92734-d682-4d71-983e-d6ec3f16059f' -and $_.licensestatus -eq '1'} | Select name, description, @{Label='computer'; Expression = {$_.PscomputerName}} | Format-List name, description, computer
add line inbetween lines
$filePath=".\path_to_file" $textToAdd="`nText to put in file" $fileContent = Get-Content $filePath $fileContent[$lineNumber+2] += $textToAdd $fileContent | Set-Content $filePath
get network settings
Get among other things mtu
Get-NetIPInterface
start time of process
List start time from processes found with Get-Process.
get-process openvpn |select starttime