Windows: Difference between revisions

From Halfface
Jump to navigation Jump to search
 
(157 intermediate revisions by the same user not shown)
Line 1: Line 1:
==hibernate==
=connect to windows from windows(rdp)=
mstsc /v:172.30.142.11
Login with password.
# Create credentials
cmdkey /generic:"<servername>" /user:"<username>" /pass:"<password>"
# Connect MSTSC with servername and credentials created before
mstsc /v:<servername>
# Delete the credentials after MSTSC session is done
cmdkey /delete:TERMSRV/<servername>
 
=which version of powershell is installed=
$PSVersionTable
 
=hibernate=
  powercfg.exe -h off
  powercfg.exe -h off


==enable powershell==
=enable powershell=
  set-executionpolicy unrestricted
  set-executionpolicy unrestricted


==Configure network==
=Configure network=
# Static ip.
# 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
  netsh interface ip set address name="Local Area Connection" static 192.168.122.41 255.255.255.0 192.168.122.1 1
# Dhcp
# Dhcp
  netsh interface is set address name="Local Area Connection" dhcp
  netsh interface is set address name="Local Area Connection" dhcp
# extract msi
# Verify mtu settings.
netsh interface ipv4 show subinterfaces
# Set correct mtu.
netsh interface ipv4 set subinterface "Ethernet 2" mtu=1000
 
=extract msi=
  msiexec /a "C:\software.msi" /qb TARGETDIR="C:\Folder"
  msiexec /a "C:\software.msi" /qb TARGETDIR="C:\Folder"


==restart network==
=restart network=
  route -f
  netsh interface set interface extbond admin = disabled
  ipconfig /release
  ping 127.0.0.1 -n 6
ipconfig /renew
  netsh interface set interface extbond admin = enabled
arp -d *
  nbtstat -R
nbtstat -RR
ipconfig /flushdns
ipconfig /registerdns


==Profile==
=Profile=
# Profile
# Profile
  C:\Users\abjorklund\AppData\Roaming\Microsoft\Windows\Start Menu
  C:\Users\abjorklund\AppData\Roaming\Microsoft\Windows\Start Menu


==restart via rdesktop==
=restart via rdesktop=
  CTRL + ALT + END
  CTRL + ALT + END
==alternative shutdown==
=alternative shutdown=
Shutdown with restart
Shutdown with restart
  shutdown /t 0 /r /f
  shutdown /t 0 /r /f
Shutdown
Shutdown
  shutdown /t 0 /s /f
  shutdown /t 0 /s /f
==change password==
logoff/logout
shutdown /l /f
 
=change password=
Start a command prompt as administrator.
Start a command prompt as administrator.
  net user username password
  net user username password
==is your account locked. bat file==
=activate account=
net user username /active:yes
 
=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
  @echo off
  :again
  :again
Line 45: Line 70:
  timeout 10
  timeout 10
  goto again
  goto again
==Browse active dirctory structure==
 
=unlock account=
Net user username /DOMAIN /active:YES
 
=Browse active dirctory structure=
  adsiedit.msc
  adsiedit.msc
==time zone conversion==
=time zone conversion=
Here you can convert from Windows to unix time zones tz.
Here you can convert from Windows to unix time zones tz.
  http://www.unicode.org/cldr/charts/latest/supplemental/zone_tzid.html
  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=
=PowerShell=
==gc==
=gc=
Get-content. Print content of file.
Get-content. Print content of file.
  gc c:\temp\file.txt
  gc c:\temp\file.txt
==Set-content==
=Set-content=
  Set-Content -path REMOTE\Filename.txt
  Set-Content -path REMOTE\Filename.txt
==Out-File==
=Out-File=
  Out-File -Encoding UTF8
  Out-File -Encoding UTF8


==replace text in file==
=replace text in file=
  Get-Content REMOTE\Filename.txt | foreach-object { $_ -replace "OLD", "NEW" } | Set-Content REMOTE\Filename.txt
  Get-Content REMOTE\Filename.txt | foreach-object { $_ -replace "OLD", "NEW" } | Set-Content REMOTE\Filename.txt




==get-service==
=get-service=
Status of one service.
get-service ipeventwatcher
status of all services. list services.
Get-Service
find service
get-service *service_to_find* | select -expand name


get-service ipeventwatcher
=stop-service=
==stop-service==
  stop-service ipeventwatcher
  stop-service ipeventwatcher
==restart-service==
=restart-service=
  restart-service ipremote -force
  restart-service ipremote -force
==start-service==
restart-service check_mk_agent -force
Restart-Service -Force -Name "TermService"
 
=start-service=
  start-service ipeventwatcher
  start-service ipeventwatcher
==variable==
=autostart service=
Set-Service -Name sshd -StartupType Automatic
 
=variable=
Set variable to content of file.
Set variable to content of file.
  $a = gc IPremote.exe.config
  $a = gc IPremote.exe.config
==md5sum==
=md5sum=
  [CmdletBinding(SupportsShouldProcess=$False)]
  [CmdletBinding(SupportsShouldProcess=$False)]
  param([string]$File)
  param([string]$File)
Line 99: Line 168:
  }
  }


==tcp connect==
Get md5sum of all files.
nc
gci * | Get-FileHash -Algorithm md5 | ft Hash,@{n="File";e={(Get-item $_.Path).Name}}
  (New-Object Net.Sockets.TcpClient).Connect("81.236.32.200",80)
 
=tcp connect port=
netcat nc  
  (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==
=What is using tcp connections=
Get-NetTCPConnection | Group-Object -Property State, OwningProcess | Select -Property Count, Name, @{Name="ProcessName";Expression={(Get-Process -PID ($_.Name.Split(',')[-1].Trim(' '))).Name}}, Group | Sort Count -Descending
=grep=
  gc IPremoteDebug.log | select-string "ip2date"
  gc IPremoteDebug.log | select-string "ip2date"
==list processes==
 
=List all processes. Grep for string=
Get-Process -IncludeUserName |  findstr dkarlslatt
 
=grep recursive=
dir -Recurse | Select-String -pattern "192.168.19.102"
 
=list processes=
  Get-Process
  Get-Process
==clear content==
=kill processes from user=
Get-Process -IncludeUserName | Where UserName -match joe | Stop-Process -force
 
=restart processes=
get-process -name powershellserver | stop-process
 
=clear content=
  Clear-Content filename.doc
  Clear-Content filename.doc
==dir recursive==
=dir recursive=
dir /a/s/b filename.txt
=dir recursive=
  'Get-ChildItem "c:\program files\" -rec | ForEach-Object -Process {$_.FullName}'
  'Get-ChildItem "c:\program files\" -rec | ForEach-Object -Process {$_.FullName}'
'Get-ChildItem . -recurse -force | ForEach-Object -Process {$_.FullName}'
=locate a file=
List recursive look for file with file name.
Get-Childitem -Path C:\ -Include *filename* -Recurse -ErrorAction SilentlyContinue
=dir filename size=
'get-childitem "C:\Program Files\directory" -rec | where {!$_.PSIsContainer} | select-object Name, Length'
=find old files=
Get-ChildItem | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)}
=find old files and remove them=
$Folder = "G:\Downloads"
#Delete files older than 6 months
Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-180)} |
  ForEach-Object {
    $_ | del -Force
    $_.FullName | Out-File C:\log\deletedlog.txt -Append
}
=calculate size of directory=
Value returned is in Scientific notation format. Add number of zeroes to value. 1.00E-6 is 1000000.
'(gci "D:\data\db" | measure Length -s).Sum /1GB'
=remove directory=
rd /s /q $DIRECTORY
=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==
=base64=
decode base64 string
decode base64 string
  [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
  [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
==troubleshooting network==
decode content of file.
ssh ip_address_hostname '$Text=(get-content "C:\Program Files\application\application.log") ; $Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text) ; $EncodedText =[Convert]::ToBase64String($Bytes) ; $EncodedText' | base64 -d
 
=troubleshooting network=
  netstat -ano | findstr <ipremote-pid>
  netstat -ano | findstr <ipremote-pid>
==diff==
 
=diff=
Compare two files.
Compare two files.
  compare-object (get-content one.txt) (get-content two.txt)
  compare-object (get-content one.txt) (get-content two.txt)
==log file. Eventlog==
=log file. Eventlog=
List event logs.
List event logs.
  Get-EventLog -list
  Get-EventLog -list
Line 127: Line 264:
List events sins date.
List events sins date.
  Get-EventLog -LogName Application -after "den 5 november 2014 10:00:00"
  Get-EventLog -LogName Application -after "den 5 november 2014 10:00:00"
==date==
=get-winevent=
# List event logs.
Get-WinEvent -ListLog * | where {$_.RecordCount -gt 0}
# Get latest rdp log entries.
Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | select * -first 1 | fl
 
=date=
  Get-Date
  Get-Date
Date in iso format.
Get-Date -UFormat '+%Y-%m-%d %H:%M:%S.000Z'


==full output==
=full output=
Print all variable with full output
Print all variable with full output
  '(Get-Variable).StdOut'
  '(Get-Variable).StdOut'
==restart services via samba==
Send output to line like the following to get more output.
| Ft -autosize | out-string -width 4096
 
=restart services via samba=
install samba-common
install samba-common
  yum install samba-common
  yum install samba-common
Line 142: Line 290:
Start service.
Start service.
  net rpc service start ipeventwatcher -I IPADDRESS -U 'user%password'
  net rpc service start ipeventwatcher -I IPADDRESS -U 'user%password'
==Windows version==
=Windows version=
  [System.Environment]::OSVersion.Version
  [System.Environment]::OSVersion.Version
  http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833%28v=vs.85%29.aspx
  http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833%28v=vs.85%29.aspx
  (Get-WmiObject -class Win32_OperatingSystem).Caption
  (Get-WmiObject -class Win32_OperatingSystem).Caption
==Is proxy bypassed==
Which architecture.
gwmi win32_operatingsystem | select osarchitecture
 
=set windows proxy=
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyEnable -Value 1
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyServer -Value proxy.int.redbridge.se":"3128
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyOverride -Value "*.redbridge.se"
Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' | findstr Proxy
 
=Is proxy bypassed=
  $url = "http://10.127.12.10";$webclient = New-Object System.Net.WebClient; $webclient.Proxy.IsBypassed($url)
  $url = "http://10.127.12.10";$webclient = New-Object System.Net.WebClient; $webclient.Proxy.IsBypassed($url)
==turn of index services when computer is not used==
 
=curl=
(Invoke-WebRequest http://localhost/Requests -UseBasicParsing).content
curl -TimeoutSec 1 https://halfface.se
 
=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
In stopindexer enter the line
  net stop wsearch
  net stop wsearch
In the startindexer enter the line
In the startindexer enter the line
  net start wsearch
  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 last 10 lines
Get-Content [filename] | Select-Object -Last 10
tail -f
Get-Content filename.log -Wait
Since PowerShell 3.
gc -Tail 10 log.txt
=head=
get first 10 lines of file.
gc log.txt | select -first 10
get first 10 lines of file.
gc -TotalCount 10 log.txt
=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]
Add user to local group.
net localgroup administrators root /add
=list local groups=
Get-LocalGroup
=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
=add line to end of file=
Add-Content c:\scripts\test.txt "The End"
=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
=list local users=
Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'"
=list logged in users=
query user /server:$SERVER
=list permissions for users=
Accesschk "NKS01579\ipwinpsr" -accepteula -a *
=create windows boot media under linux=
woeusb  --target-filesystem NTFS --device /install/system/win10/Win10_1909_EnglishInternational_x64.iso  /dev/sdb
=rename computer=
$NewName="alva"
$ComputerInfo = Get-WmiObject -Class Win32_ComputerSystem
$ComputerInfo.Rename($NewName)
Restart-Computer
=startup dir=
The All Users Startup Folder is located at the following path:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
The Current User Startup Folder is located here:
C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
=cmd scroll mode=
Alt+Space -> E -> L
=rdp allow many sessions=
https://github.com/stascorp/rdpwrap/releases/download/v1.6.2/RDPWrap-v1.6.2.zip
=disable defender=
Set-MpPreference -DisableRealtimeMonitoring $true
REG ADD "hklm\software\policies\microsoft\windows defender" /v DisableAntiSpyware /t REG_DWORD /d 1 /F
=list scheduled tasks=
'Get-ScheduledTask | Ft -autosize | out-string -width 4096'
=scheduled tasks enable disable=
Get-ScheduledTask -taskname Hive*
TaskPath                                      TaskName                          State   
--------                                      --------                          -----   
\Microsoft\Windows\User Profile Service\      HiveUploadTask                    Disabled 
=Enable scheduled task=
Get-ScheduledTask -taskname Hive* | Enable-ScheduledTask
=Disable scheduled task=
Get-ScheduledTask -taskname Hive* | Disable-ScheduledTask
=Start scheduled task=
Get-ScheduledTask -taskname Hive* | Start-ScheduledTask
=Get output from last scheduled command execution=
Get-ScheduledTask -taskname Hive* | Get-ScheduledTaskInfo
=scheduled task add=
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "net user /add special_user PassW0rd ; net localgroup administrators special_user /add"'
$trigger = New-ScheduledTaskTrigger -Daily -At 12am
$task = Register-ScheduledTask -RunLevel "Highest" -TaskName "Add special_user" -Trigger $trigger -Action $action
$task.Triggers.Repetition.Duration = "P1D" # Repeat for a duration of one day
$task.Triggers.Repetition.Interval = "PT1H" # Repeat every 30 minutes, use PT1H for every hour
$task.Principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$task | Set-ScheduledTask
=touch=
echo $null >> filename
=bitlocker read from linux=
https://www.ceos3c.com/open-source/open-bitlocker-drive-linux/
=runas(sudo)=
Run command as other user.
runas /user:%computername%\root cmd
=install sshd=
On Windows 10 version 1803 and newer
In Settings app, go to Apps > Apps & features > Manage optional features.
Locate "OpenSSH server" feature, expand it, and select Install.
Binaries are installed to %WINDIR%\System32\OpenSSH. Configuration file (sshd_config) and host keys are installed to %ProgramData%\ssh (only after the server is started for the first time).
You may still want to use the following manual installation, if you want to install a newer version of OpenSSH than the one built into Windows 10.
https://github.com/PowerShell/Win32-OpenSSH/releases (package OpenSSH-Win64.zip or OpenSSH-Win32.zip)
As the Administrator, extract the package to C:\Program Files\OpenSSH
powershell.exe -ExecutionPolicy Bypass -File install-sshd.ps1
Configuring SSH server
Allow incoming connections to SSH server in Windows Firewall:
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH SSH Server' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
or go to Control Panel > System and Security > Windows Firewall1 > Advanced Settings > Inbound Rules and add a new rule for port 22.
Start the service and/or configure automatic start:
start-service "OpenSSH SSH Server"
Set-Service -Name sshd -StartupType Automatic
=show routes=
Get-NetRoute -InterfaceIndex 12
cmd
route print -4
Add route
New-NetRoute -DestinationPrefix "10.0.0.0/24" -InterfaceIndex 12 -NextHop 192.168.0.1
cmd
route -p ADD 10.255.240.0 MASK 255.255.255.0 172.30.103.4
route -p add 0.0.0.0 mask 0.0.0.0 172.30.103.10
Get routing information.
Find-NetRoute -RemoteIPAddress "10.0.0.34" | Select-Object ifIndex,DestinationPrefix,NextHop,RouteMetric -Last 1
=last login on local machine=
get-localuser | Select Name,LastLogon | sort LastLogon
=last logged in user and grep for user=
Function Get-LoginEvents {
    Param (
        [Parameter(
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true
        )]
        [Alias('Name')]
        [string]$ComputerName = $env:ComputerName
        ,
        [datetime]$StartTime
        ,
        [datetime]$EndTime
    )
    Begin {
        enum LogonTypes {
            Interactive = 2
            Network = 3
            Batch = 4
            Service = 5
            Unlock = 7
            NetworkClearText = 8
            NewCredentials = 9
            RemoteInteractive = 10
            CachedInteractive = 11
        }
        $filterHt = @{
            LogName = 'Security'
            ID = 4624
        }
        if ($PSBoundParameters.ContainsKey('StartTime')){
            $filterHt['StartTime'] = $StartTime
        }
        if ($PSBoundParameters.ContainsKey('EndTime')){
            $filterHt['EndTime'] = $EndTime
        }
    }
    Process {
        Get-WinEvent -MaxEvents 100 -ComputerName $ComputerName -FilterHashtable $filterHt | foreach-Object {
            [pscustomobject]@{
                ComputerName = $ComputerName
                UserAccount = $_.Properties.Value[5]
                UserDomain = $_.Properties.Value[6]
                LogonType = [LogonTypes]$_.Properties.Value[8]
                WorkstationName = $_.Properties.Value[11]
                SourceNetworkAddress = $_.Properties.Value[19]
                TimeStamp = $_.TimeCreated
            }
        }
    }
    End{}
}
Get-LoginEvents > login
gc login | select-string dabuzaid -Context 5
=powersave disable=
powercfg /x -hibernate-timeout-ac 0
powercfg /x -hibernate-timeout-dc 0
powercfg /x -disk-timeout-ac 0
powercfg /x -disk-timeout-dc 0
powercfg /x -monitor-timeout-ac 0
powercfg /x -monitor-timeout-dc 0
Powercfg /x -standby-timeout-ac 0
powercfg /x -standby-timeout-dc 0
=hostname=
Get fqdn
[System.Net.Dns]::GetHostByName($env:computerName).HostName
"$env:computername.$env:userdnsdomain"
=resolve hostname=
Resolve-DnsName -server 8.8.8.8 smtp.google.com | Format-Table Name, IPAddress -HideTableHeaders
=clear screen reset=
cls
=top=
While(1) {ps | sort -des cpu | select -f 15 | ft -a; sleep 1; cls}
=get users sid=
wmic useraccount where name='dkarlslatt' get sid
=traceroute=
Test-NetConnection "IPaddress/HOSTaname" -TraceRoute
=name of ad servers=
nslookup -type=srv _ldap._tcp.dc._msdcs.${AD}
=iis logfiles=
Read last lines from iis log.
gc -Tail 10 "C:\InetPub\Logs\LogFiles\W3SVC1\u_ex$(Get-Date -F 'yyMMdd').log"
=join domain=
netdom join %computername% /domain:your.ADDomainToJoin.net /UserD:LoginWithJoinPermissions /PasswordD:%password%
=windows update info=
wmic qfe list
=patch=
Update release area Windows.
servicepack.exe -s:z:\w2k3
=get date in iso format=
Get-Date (Get-Date) -UFormat '+%Y-%m-%d %H:%M:%S'
=format-list(fl)=
Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | select * -first 1 | fl
=whoami=
echo "$env:UserDomain $env:UserName $env:ComputerName"
=group=
(New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=User)(samAccountName=$($env:username)))")).FindOne().GetDirectoryEntry().memberOf
=unzip=
Expand-Archive C:\a.zip
=take ownership and remove=
Remove-Item -Recurse -Force <directory>
takeown /a /r /d Y /f <directory>
=print info to remove directories=
Prepare with two lists. One with users who are suitable to have their directories removed. And one list with the output from dir in c:\users.
cat uc-remote01_login.txt | while read WIN_USER WIN_DATE ; do echo '#' $WIN_USER $WIN_DATE ; DIRECTORY=$(grep " $WIN_USER" uc-remote01_users.txt) ; if [ "${DIRECTORY}" ] ; then echo Remove-Item -Recurse -Force $WIN_USER \; takeown /a /r /d Y /f $WIN_USER \; Remove-Item -Recurse -Force $WIN_USER ; fi ; done
=list environments variables=
dir env:
=list shares=
Get-SmbShare

Latest revision as of 09:36, 12 February 2024

connect to windows from windows(rdp)

mstsc /v:172.30.142.11

Login with password.

# Create credentials
cmdkey /generic:"<servername>" /user:"<username>" /pass:"<password>"
# Connect MSTSC with servername and credentials created before
mstsc /v:<servername>
# Delete the credentials after MSTSC session is done
cmdkey /delete:TERMSRV/<servername>

which version of powershell is installed

$PSVersionTable

hibernate

powercfg.exe -h off

enable powershell

set-executionpolicy unrestricted

Configure network

  1. 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
  1. Dhcp
netsh interface is set address name="Local Area Connection" dhcp
  1. Verify mtu settings.
netsh interface ipv4 show subinterfaces
  1. Set correct mtu.
netsh interface ipv4 set subinterface "Ethernet 2" mtu=1000

extract msi

msiexec /a "C:\software.msi" /qb TARGETDIR="C:\Folder"

restart network

netsh interface set interface extbond admin = disabled
ping 127.0.0.1 -n 6
netsh interface set interface extbond admin = enabled

Profile

  1. 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/logout

shutdown /l /f

change password

Start a command prompt as administrator.

net user username password

activate account

net user username /active:yes

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. list services.

Get-Service

find service

get-service *service_to_find* | select -expand name

stop-service

stop-service ipeventwatcher

restart-service

restart-service ipremote -force
restart-service check_mk_agent -force
Restart-Service -Force -Name "TermService"

start-service

start-service ipeventwatcher

autostart service

Set-Service -Name sshd -StartupType Automatic

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 port

netcat nc

(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();

What is using tcp connections

Get-NetTCPConnection | Group-Object -Property State, OwningProcess | Select -Property Count, Name, @{Name="ProcessName";Expression={(Get-Process -PID ($_.Name.Split(',')[-1].Trim(' '))).Name}}, Group | Sort Count -Descending

grep

gc IPremoteDebug.log | select-string "ip2date"

List all processes. Grep for string

Get-Process -IncludeUserName |  findstr dkarlslatt

grep recursive

dir -Recurse | Select-String -pattern "192.168.19.102"

list processes

Get-Process

kill processes from user

Get-Process -IncludeUserName | Where UserName -match joe | Stop-Process -force

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}'

locate a file

List recursive look for file with file name.

Get-Childitem -Path C:\ -Include *filename* -Recurse -ErrorAction SilentlyContinue

dir filename size

'get-childitem "C:\Program Files\directory" -rec | where {!$_.PSIsContainer} | select-object Name, Length'

find old files

Get-ChildItem | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)}

find old files and remove them

$Folder = "G:\Downloads"
#Delete files older than 6 months
Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-180)} |
 ForEach-Object {
   $_ | del -Force
   $_.FullName | Out-File C:\log\deletedlog.txt -Append
}

calculate size of directory

Value returned is in Scientific notation format. Add number of zeroes to value. 1.00E-6 is 1000000.

'(gci "D:\data\db" | measure Length -s).Sum /1GB'

remove directory

rd /s /q $DIRECTORY

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="))

decode content of file.

ssh ip_address_hostname '$Text=(get-content "C:\Program Files\application\application.log") ; $Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text) ; $EncodedText =[Convert]::ToBase64String($Bytes) ; $EncodedText' | base64 -d

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"

get-winevent

# List event logs.
Get-WinEvent -ListLog * | where {$_.RecordCount -gt 0}
# Get latest rdp log entries.
Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | select * -first 1 | fl

date

Get-Date

Date in iso format.

Get-Date -UFormat '+%Y-%m-%d %H:%M:%S.000Z'

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

set windows proxy

Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyEnable -Value 1
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyServer -Value proxy.int.redbridge.se":"3128
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyOverride -Value "*.redbridge.se"
Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' | findstr Proxy

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
curl -TimeoutSec 1 https://halfface.se

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 last 10 lines

Get-Content [filename] | Select-Object -Last 10

tail -f

Get-Content filename.log -Wait

Since PowerShell 3.

gc -Tail 10 log.txt 

head

get first 10 lines of file.

gc log.txt | select -first 10

get first 10 lines of file.

gc -TotalCount 10 log.txt

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]

Add user to local group.

net localgroup administrators root /add

list local groups

Get-LocalGroup

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

add line to end of file

Add-Content c:\scripts\test.txt "The End"

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

list local users

Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'"

list logged in users

query user /server:$SERVER

list permissions for users

Accesschk "NKS01579\ipwinpsr" -accepteula -a *

create windows boot media under linux

woeusb  --target-filesystem NTFS --device /install/system/win10/Win10_1909_EnglishInternational_x64.iso  /dev/sdb

rename computer

$NewName="alva"
$ComputerInfo = Get-WmiObject -Class Win32_ComputerSystem
$ComputerInfo.Rename($NewName)
Restart-Computer

startup dir

The All Users Startup Folder is located at the following path:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

The Current User Startup Folder is located here:

C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

cmd scroll mode

Alt+Space -> E -> L

rdp allow many sessions

https://github.com/stascorp/rdpwrap/releases/download/v1.6.2/RDPWrap-v1.6.2.zip

disable defender

Set-MpPreference -DisableRealtimeMonitoring $true
REG ADD "hklm\software\policies\microsoft\windows defender" /v DisableAntiSpyware /t REG_DWORD /d 1 /F

list scheduled tasks

'Get-ScheduledTask | Ft -autosize | out-string -width 4096'

scheduled tasks enable disable

Get-ScheduledTask -taskname Hive*
TaskPath                                       TaskName                          State     
--------                                       --------                          -----     
\Microsoft\Windows\User Profile Service\       HiveUploadTask                    Disabled  

Enable scheduled task

Get-ScheduledTask -taskname Hive* | Enable-ScheduledTask

Disable scheduled task

Get-ScheduledTask -taskname Hive* | Disable-ScheduledTask

Start scheduled task

Get-ScheduledTask -taskname Hive* | Start-ScheduledTask

Get output from last scheduled command execution

Get-ScheduledTask -taskname Hive* | Get-ScheduledTaskInfo

scheduled task add

$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "net user /add special_user PassW0rd ; net localgroup administrators special_user /add"'
$trigger = New-ScheduledTaskTrigger -Daily -At 12am
$task = Register-ScheduledTask -RunLevel "Highest" -TaskName "Add special_user" -Trigger $trigger -Action $action
$task.Triggers.Repetition.Duration = "P1D" # Repeat for a duration of one day
$task.Triggers.Repetition.Interval = "PT1H" # Repeat every 30 minutes, use PT1H for every hour
$task.Principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$task | Set-ScheduledTask

touch

echo $null >> filename

bitlocker read from linux

https://www.ceos3c.com/open-source/open-bitlocker-drive-linux/

runas(sudo)

Run command as other user.

runas /user:%computername%\root cmd

install sshd

On Windows 10 version 1803 and newer
In Settings app, go to Apps > Apps & features > Manage optional features.
Locate "OpenSSH server" feature, expand it, and select Install.
Binaries are installed to %WINDIR%\System32\OpenSSH. Configuration file (sshd_config) and host keys are installed to %ProgramData%\ssh (only after the server is started for the first time).

You may still want to use the following manual installation, if you want to install a newer version of OpenSSH than the one built into Windows 10.

https://github.com/PowerShell/Win32-OpenSSH/releases (package OpenSSH-Win64.zip or OpenSSH-Win32.zip)
As the Administrator, extract the package to C:\Program Files\OpenSSH
powershell.exe -ExecutionPolicy Bypass -File install-sshd.ps1

Configuring SSH server Allow incoming connections to SSH server in Windows Firewall:

New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH SSH Server' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22

or go to Control Panel > System and Security > Windows Firewall1 > Advanced Settings > Inbound Rules and add a new rule for port 22. Start the service and/or configure automatic start:

start-service "OpenSSH SSH Server"
Set-Service -Name sshd -StartupType Automatic

show routes

Get-NetRoute -InterfaceIndex 12

cmd

route print -4

Add route

New-NetRoute -DestinationPrefix "10.0.0.0/24" -InterfaceIndex 12 -NextHop 192.168.0.1

cmd

route -p ADD 10.255.240.0 MASK 255.255.255.0 172.30.103.4
route -p add 0.0.0.0 mask 0.0.0.0 172.30.103.10

Get routing information.

Find-NetRoute -RemoteIPAddress "10.0.0.34" | Select-Object ifIndex,DestinationPrefix,NextHop,RouteMetric -Last 1

last login on local machine

get-localuser | Select Name,LastLogon | sort LastLogon

last logged in user and grep for user

Function Get-LoginEvents {
   Param (
       [Parameter(
           ValueFromPipeline = $true,
           ValueFromPipelineByPropertyName = $true
       )]
       [Alias('Name')]
       [string]$ComputerName = $env:ComputerName
       ,
       [datetime]$StartTime
       ,
       [datetime]$EndTime
   )
   Begin {
       enum LogonTypes {
           Interactive = 2
           Network = 3
           Batch = 4
           Service = 5
           Unlock = 7
           NetworkClearText = 8
           NewCredentials = 9
           RemoteInteractive = 10
           CachedInteractive = 11
       }
       $filterHt = @{
           LogName = 'Security'
           ID = 4624
       }
       if ($PSBoundParameters.ContainsKey('StartTime')){
           $filterHt['StartTime'] = $StartTime
       }
       if ($PSBoundParameters.ContainsKey('EndTime')){
           $filterHt['EndTime'] = $EndTime
       }
   }
   Process {
       Get-WinEvent -MaxEvents 100 -ComputerName $ComputerName -FilterHashtable $filterHt | foreach-Object {
           [pscustomobject]@{
               ComputerName = $ComputerName
               UserAccount = $_.Properties.Value[5]
               UserDomain = $_.Properties.Value[6]
               LogonType = [LogonTypes]$_.Properties.Value[8]
               WorkstationName = $_.Properties.Value[11]
               SourceNetworkAddress = $_.Properties.Value[19]
               TimeStamp = $_.TimeCreated
           }
       }
   }
   End{}
}
Get-LoginEvents > login
gc login | select-string dabuzaid -Context 5

powersave disable

powercfg /x -hibernate-timeout-ac 0
powercfg /x -hibernate-timeout-dc 0
powercfg /x -disk-timeout-ac 0
powercfg /x -disk-timeout-dc 0
powercfg /x -monitor-timeout-ac 0
powercfg /x -monitor-timeout-dc 0
Powercfg /x -standby-timeout-ac 0
powercfg /x -standby-timeout-dc 0

hostname

Get fqdn

[System.Net.Dns]::GetHostByName($env:computerName).HostName
"$env:computername.$env:userdnsdomain"

resolve hostname

Resolve-DnsName -server 8.8.8.8 smtp.google.com | Format-Table Name, IPAddress -HideTableHeaders

clear screen reset

cls

top

While(1) {ps | sort -des cpu | select -f 15 | ft -a; sleep 1; cls}

get users sid

wmic useraccount where name='dkarlslatt' get sid

traceroute

Test-NetConnection "IPaddress/HOSTaname" -TraceRoute

name of ad servers

nslookup -type=srv _ldap._tcp.dc._msdcs.${AD}

iis logfiles

Read last lines from iis log.

gc -Tail 10 "C:\InetPub\Logs\LogFiles\W3SVC1\u_ex$(Get-Date -F 'yyMMdd').log"

join domain

netdom join %computername% /domain:your.ADDomainToJoin.net /UserD:LoginWithJoinPermissions /PasswordD:%password%

windows update info

wmic qfe list

patch

Update release area Windows.

servicepack.exe -s:z:\w2k3

get date in iso format

Get-Date (Get-Date) -UFormat '+%Y-%m-%d %H:%M:%S'

format-list(fl)

Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | select * -first 1 | fl

whoami

echo "$env:UserDomain $env:UserName $env:ComputerName"

group

(New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=User)(samAccountName=$($env:username)))")).FindOne().GetDirectoryEntry().memberOf

unzip

Expand-Archive C:\a.zip

take ownership and remove

Remove-Item -Recurse -Force <directory>
takeown /a /r /d Y /f <directory>

print info to remove directories

Prepare with two lists. One with users who are suitable to have their directories removed. And one list with the output from dir in c:\users.

cat uc-remote01_login.txt | while read WIN_USER WIN_DATE ; do echo '#' $WIN_USER $WIN_DATE ; DIRECTORY=$(grep " $WIN_USER" uc-remote01_users.txt) ; if [ "${DIRECTORY}" ] ; then echo Remove-Item -Recurse -Force $WIN_USER \; takeown /a /r /d Y /f $WIN_USER \; Remove-Item -Recurse -Force $WIN_USER ; fi ; done

list environments variables

dir env:

list shares

Get-SmbShare