
PowerShell
-
Check computer info
Get-ComputerInfo
-
Check account info
# windows detail
net config workstation
net users
net users administrator
-
Multiple lines command. by “. `”
$yourString = "HELLO world! POWERSHELL!". `
Replace("HELLO", "Hello"). `
Replace("POWERSHELL", "Powershell")
-
Zip for powershell
Compress-Archive -Path C:\Invoices -DestinationPath C:\Archives\Invoices
# Or
Compress-Archive
#Path[0]:{{xxx}}
#Path[1]:{{xxx}}
#DestinationPath:{{filename}}
-
Print file name as datetime
echo "HI" >> logfile$(get-date -f yyyy-MM-dd).log
-
Setting proxy
[Environment]::SetEnvironmentVariable("HTTP_PROXY", "http://adcproxy.trendmicro.com:8080/", [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("HTTPS_PROXY", "http://adcproxy.trendmicro.com:8080/", [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("NO_PROXY", "127.0.0.1,localhost,*.trendnet.org,*.trendmicro.com,10.0.0.0/8,172.16.30.0/16,172.16.31.0/16,\.\pipe\docker_engine", "Machine")
# PS. EnvironmentVariableTarget: Machine(2)/Process(0)/User(1)
-
Get env variables
[Environment]::GetEnvironmentVariable("HTTP_PROXY", [EnvironmentVariableTarget]::Machine)
[Environment]::GetEnvironmentVariable("HTTP_PROXY", [EnvironmentVariableTarget]::Process)
[Environment]::GetEnvironmentVariable("HTTP_PROXY", [EnvironmentVariableTarget]::User)
-
Calculate the esplase time
$StartTime = $(get-date)
$elapsedTime = $(get-date) - $StartTime
$totalTime = "{0:HH:mm:ss.fff}" -f ([datetime]$elapsedTime.Ticks)
Write-Host $totalTime
-
Enable remote scripting, “.ps1 is not digitally signed. The script will not execute on the system.”
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
=================
Get-ExecutionPolicy # Get current
-
Check IIS version
get-itemproperty HKLM:\SOFTWARE\Microsoft\InetStp\ | select setupstring,versionstring
-
Get CPU Memory usage
# CPU
(Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
# Memory (MB)
(Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue
-
Test SQL connect
$connectionString = "Server={{Server}};Database={{database}};uid={{user}}; pwd={{pwd}};Integrated Security=False;"
$connectionString = "data source={{Server}};Initial Catalog={{database}};Integrated Security=True;" # For windows auth
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $connectionString
$sqlConnection.Open() # stop here, if just for connection test
# With query
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $sqlConnection
$Command.CommandText = "SELECT 1"
$Reader = $Command.ExecuteReader()
# With response
$Datatable = New-Object System.Data.DataTable
$Datatable.Load($Reader)
foreach($row in $Datatable)
{
Write-Host $row.Item(0)
}
$sqlConnection.Close()
-
Download zip and unzip
Invoke-WebRequest -Uri "https://download...zip" -OutFile "{path}" | Extract-Archive -DestinationPath "{path}"
(Invoke-WebRequest https://your/url/...).Content | Extract-Archive -DestinationPath C:\Kellekek\Microsoft\PowerShell\6.0.0-beta.8
-
Get date string
$(Get-Date -Format "yyyyMMddTHHmmssZ")
# UTC
$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ"))
-
Get server name
PS C:\app> [System.Net.Dns]::GetHostName()
-
One line command to find and replace string
$file='c:\app\xxx.config'; (Get-Content $file).replace('Encryption enable="true"', 'Encryption enable="false"') | Set-Content $file
-
Loop execute each line-by-line
kubectl get pods --no-headers -o custom-columns=":metadata.name" | %{ echo '-------' $_ $(kubectl top pod $_) }
# %{} ------ loop all lines
# $_ ------ get var
-
Curl url without GUI
curl $url -UseBasicParsing
Invoke-WebRequest -Uri $url -UseBasicParsing
-
error msg: The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer’s first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.
-
Get Virtual memory setting
wmic computersystem get AutomaticManagedPagefile
-
Get Virtual memory
systeminfo | find "Virtual Memory"
-
Get drive usage
Get-PSDrive
-
Check powershell version
$Host.Version
-
Search specific word in EventLog
(Get-EventLog -LogName system -after (Get-Date).AddDays(-10) |
Select-Object -Property TimeGenerated,EntryType,Source,Message) -match "nxlog" |
Format-Table -wrap
-
Grant permission
C:\>icacls "D:\test" /grant John:(OI)(CI)F /T
According do MS documentation:
* F = Full Control
* CI = Container Inherit - This flag indicates that subordinate containers will inherit this ACE.
* OI = Object Inherit - This flag indicates that subordinate files will inherit the ACE.
* /T = Apply recursively to existing files and sub-folders. (OI and CI only apply to new files and sub-folders). Credit: comment by @AlexSpence.
========== Detail =========
icacls "<root folder>" /grant:r "Domain Admins":F /t
Full Control (F)
Modify (M)
Read & Execute (RX)
List Folder Contents (X,RD,RA,REA,RC)
Read (R)
Write (W)
Traverse folder / execute file (X)
List folder / read data (RD)
Read attributes (RA)
Read extended attributes (REA)
Create file / write data (WD)
Create folders / append data (AD)
Write attributes (WA)
Write extended attributes (WEA)
Delete subfolders and files (DC)
Delete (D)
Read permissions (RC)
Change permissions (WDAC)
Take ownership (WO)
You can also specify the inheritance for the folders:
This folder only
This folder, subfolders and files (OI)(CI)
This folder and subfolders (CI)
This folder and files (OI)
Subfolders and files only (OI)(CI)(NP)(IO)
Subfolders only (CI)(IO)
Files only (OI)(IO)
-
Get full column message
| format-table -wrap (-auto)
-
Check OS version
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
# Version 1709
ver
# By registry key:
reg query "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion" /v BuildLabEx
# Ref:
https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/version-compatibility?tabs=windows-server-1909%2Cwindows-10-1809#querying-version
-
Check shared folder connection
net use \\server\share /user:<domain\username> <password>
-
Check permission to file/folder
-
Get folder permission
(get-acl <folder name>).access | ft IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -auto
-
Get Disk usage
Get-PSDrive
-
Keep command updated (watch as linux)
while (1) {your_command; sleep 5}
-
Combine parameters with colon
echo ${aa}:$bb
-
Find command location
(get-command notepad.exe).Path
-
Connect and query to SQL
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "server=XXX;database=XXX;uid=XXX;pwd=XXX;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "SELECT TOP 1 * FROM XXX"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0]
-
Get the latest file in folder
$a = Dir | Sort CreationTime -Descending | Select Name -First 1
cd $a.name
-
Select string by regex pattern
Select-String -Path {name} -Pattern '^.*\"fail\"\:([0-9]+)\,\"label\"\:\"Critical Tests\"\,\"pass\"\:([0-9]+?)\}'
-
Get domain name by IP
nslookup {IP}
-
Connect to Network sharing 網路上的芳鄰
New-PSDrive -Name P -PSProvider FileSystem -Root \\{{folderPath}} -Credential domain\{{userName}}
Notice: can’t have the back slash at the end.
-
Get current folder path
$pwd
-
Disable firewall
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
-
Get AD user by identity
Get-ADUser -Identity {{userName}} -Properties *
-
Set/Update AD password
Set-ADAccountPassword -Identity john_jang -OldPassword (ConvertTo-SecureString -AsPlainText "{{password}}" -Force) -NewPassword (ConvertTo-SecureString -AsPlainText "{{password}}" -Force)
-
Install HyperV on Windows Server
Install-WindowsFeature Hyper-v
-
Enable hypervisor
bcdedit /set hypervisorlaunchtype Auto
-
Enable Nested HyperV – enable HyperV guest feature inside HyperV host. ref
Set-VMProcessor -VMName WinS_2019_rs5 -ExposeVirtualizationExtensions $true
-
Get current PowerShell version
$PSVersionTable.PSVersion
-
Remote scripting
Enter-PSSession -ComputerName {ServerName} -Credential {domain\name}
-
Start windows service
get-service *partOfServiceName*
start-service serviceName
stop-service serviceName
-
Operating windows service
Get-Service *keyword* # Search by keyword
# for PowerShellv5 and older version
$service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'"
$service.delete()
-
Operating the response from commands
XXcommand | Select-Object -Expand Conlumn
(XXcommand).ResponseColumn
-
Send mail
Send-MailMessage -From 'User01 <user01@fabrikam.com>' -To 'User02 <user02@fabrikam.com>' -Subject 'Sending the Attachment' -Body "Forgot to send the attachment. Sending now." -SmtpServer 'smtp.fabrikam.com'
# More
Send-MailMessage -From 'User01 <user01@fabrikam.com>' -To 'User02 <user02@fabrikam.com>', 'User03 <user03@fabrikam.com>' -Subject 'Sending the Attachment' -Body "Forgot to send the attachment. Sending now." -Attachments .\data.csv -Priority High -DeliveryNotificationOption OnSuccess, OnFailure -SmtpServer 'smtp.fabrikam.com'
-
Create symbolic link from folder to folder.
mklink /D {{folderPath_to_create_link_destination}} {{folderPath_to_link_from}}
PS. in PowerShell, use `cmd /c mklink xxxxx`
mklink /d \MyFolder \Users\User1\Documents # soft link for folder
mklink /h \MyFile.file \User1\Documents\example.file # hard link for file
-
Got path not exists
-
Error message:
“{path} No such file or directory“
-
Remove the “” on the path behind `cat` command.
git secrets –add-provider — cat ./folder/*
-
Got path not exists
-
Error message:
Windows Commands
-
Print datetime as log filename
echo off
set CUR_YYYY=%date:~10,4%
set CUR_MM=%date:~4,2%
set CUR_DD=%date:~7,2%
set CUR_HH=%time:~0,2%
if %CUR_HH% lss 10 (set CUR_HH=0%time:~1,1%)
set CUR_NN=%time:~3,2%
set CUR_SS=%time:~6,2%
set CUR_MS=%time:~9,2%
set SUBFILENAME=%CUR_YYYY%%CUR_MM%%CUR_DD%-%CUR_HH%%CUR_NN%%CUR_SS%
echo "HI" >> jj_%SUBFILENAME%.log ## Output: jj_20200902-110133.log
-
Calling execute file without hanging on it
start "" XXX.exe -p C:\Work
-
刪除 Windows service
SC delete {{serviceName}}
-
關閉 WSUS
"Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" > UseWUServer > 0
-------
$currentWU = Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" | select -ExpandProperty UseWUServer
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value 0
Restart-Service wuauserv
-
Install RSAT Tools
# install AD management tools (including the ADUC console):
Add-WindowsCapability –online –Name “Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0”
# install DNS management console, run:
Add-WindowsCapability –online –Name “Rsat.Dns.Tools~~~~0.0.1.0”
# Verify
Get-WindowsCapability -Name RSAT* -Online | Select-Object -Property DisplayName, State
# Etc.
Add-WindowsCapability -Online -Name Rsat.FileServices.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.GroupPolicy.Management.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.IPAM.Client.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.LLDP.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.NetworkController.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.NetworkLoadBalancing.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.BitLocker.Recovery.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.CertificateServices.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.DHCP.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.FailoverCluster.Management.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.RemoteAccess.Management.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.RemoteDesktop.Services.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.ServerManager.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.Shielded.VM.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.StorageMigrationService.Management.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.StorageReplica.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.SystemInsights.Management.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.VolumeActivation.Tools~~~~0.0.1.0
Add-WindowsCapability -Online -Name Rsat.WSUS.Tools~~~~0.0.1.0
# To install all the available RSAT tools at once, run:
Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability –Online
# To install only disabled RSAT components, run:
Get-WindowsCapability -Online |? {$_.Name -like "*RSAT*" -and $_.State -eq "NotPresent"} | Add-WindowsCapability -Online
Windows Others
-
Check current windows version (GUI)
Check your Windows version by selecting the Windows logo key + R, type winver
-
Loop script – foreach
set list=A B C D
for %%a in (%list%) do (
echo %%a
echo/
)
-
Auto newline to “press ENTER to continue” (or any key XXXX)
echo XXXX | YYYY
-
Add app to startup
-
Win + R > run “shell:startup”
-
Add app shortcut to folder.
-
Disable error reporting – “Hold on “
-
Win + R > run “services.msc”
-
Disable service: “Windows Error Reporting Service”
-
關閉 telnet
Ctrl + ]
telnet> quit(q)
Stromectol
Kamagra Free Sample
zithromax pediatric dose
Epivir
where to buy cialis cheap
Pain Meds Online Overnight
plaquenil side effects mayo clinic
Order Cheap Amoxicilina Flemoxon In Germany Free Shipping
lyrica vs gabapentin
Propecia Descanso
propecia pills for sale
Propecia Wirkt Nicht Mehr
100mg
buy zithromax with no prescription
For example superficial mouth lacera tions or hematemesis may be confused with hemoptysis. Coarty levitra annonce
Ersgft Dog Antibiotics Without Perscription Plaquenil Package Deal On Cialis And Levetra
Ktpeiy Prednisone
Plaquenil Mgwslv Priligy Brand
cialis pills – cialis 5mg us cialis australia
generic hydroxychloroquine 200mg – hydroxychloroquine over the counter oral hydroxychloroquine 200mg
ivermectin 3 mg stromectol – ivermectin for sale ivermectin 3mg online
sildenafil price – buy generic fildena 100mg purchase disulfiram
buy clomid 100mg – order ventolin 2mg purchase cetirizine online cheap
brand clarinex 5mg – order desloratadine triamcinolone 10mg drug
order cytotec online – prednisolone 5mg without prescription buy generic synthroid
buy viagra 150mg online – viagra 50mg gabapentin 800mg drug
levitra or cialis – cheap tadalafil online cenforce 50mg uk
diltiazem online buy – order zovirax without prescription acyclovir 800mg cheap
buy hydroxyzine 25mg for sale – cost atarax 10mg order rosuvastatin for sale
buy ezetimibe 10mg pill – buy citalopram without prescription celexa pills
viagra 150mg for sale – viagra 50mg pills for men brand viagra 50mg
nexium over the counter – brand nexium 20mg phenergan online buy
order tadalafil 40mg without prescription – Free cialis samples buy cialis 40mg for sale
order provigil 100mg generic – canadian online pharmacies buy ed pills sale
buy accutane 40mg – purchase accutane generic cost azithromycin 500mg
furosemide 40mg without prescription – order lasix 40mg generic viagra drug
cialis prices – tadalafil 5mg cheap sildenafil 200mg price
cost of cialis – buy cozaar generic warfarin 5mg ca
order topamax 100mg sale – topiramate 100mg brand sumatriptan 25mg tablet
viagra sildenafil – sildenafil 100mg oral tadalafil 10mg brand
isotretinoin 20mg cheap – amoxicillin 1000mg without prescription amoxicillin 250mg us
purchase doxycycline pill – chloroquine 250mg brand aralen us
real cialis – Buy now cialis sildenafil professional
order modafinil 200mg – viagra 100mg usa order generic sildenafil 50mg
order accutane 40mg online – buy celebrex online buy celebrex for sale
purchase tamsulosin online – buy aldactone 100mg without prescription spironolactone without prescription
zocor medication – cost valacyclovir 1000mg where can i buy a research paper
hollywood casino – help me write my research paper help writing a research paper
rivers casino – buy ampicillin 500mg for sale ampicillin 500mg cost
cipro buy online – purchase ciprofloxacin sale tadalafil 5mg generic
pfizer viagra – viagra 50 mg vardenafil 5 mg
order augmentin 375mg – order tadalafil 40mg without prescription order cialis 5mg
cheap trimethoprim – sildenafil uk sildenafil next day
cephalexin cost – cost cephalexin 500mg erythromycin 250mg brand
order fildena online cheap – ivermectin drug ivermectin 6 mg for humans for sale
budesonide online order – rhinocort allergy spray oral antabuse
cheap ceftin – methocarbamol brand cialis 20mg uk
oral ampicillin 500mg – cialis 5mg cheap cost tadalafil 10mg
amoxil over the counter – amoxil 1000mg brand levitra 10mg price
purchase doxycycline sale – order cialis 10mg generic buy tadalafil 40mg online cheap
order cialis 20mg pills – cialis 10mg ca provigil 100mg pills
prednisolone 10mg us – buy prednisolone 10mg generic sildenafil pharmacy
lasix over the counter – furosemide 40mg cost buy ivermectin pills
b6e4j
0n4yg
gf4b
buy plaquenil generic – baricitinib 4mg cheap order baricitinib 2mg without prescription
cost metformin – cheap glucophage 500mg amlodipine 5mg ca
lisinopril pills – lopressor 100mg cost order tenormin
vardenafil online order – buy methylprednisolone 8 mg online order clomiphene 50mg generic
order ventolin – i need a paper written for me order priligy 90mg sale
synthroid over the counter – levothyroxine over the counter plaquenil without prescription
cialis super active – sildenafil overnight sildenafil for women
azithromycin indication zithromax lowest price azithromycin 250 mg en espanol how long does it take azithromycin
levitra 20 mg tablet picture levitra levitra buy cheap levitra 20 mg prezzo
cenforce 50mg without prescription – ezetimibe 10mg uk domperidone online order
caverject vs viagra viagra need prescription australia what happens if a woman takes cialis where can i buy viagra online without a prescription
diltiazem teaching cardizem er 240 mg diltiazem side effects blood pressure ic diltiazem 24hr er how does it affect your sodium levels
order viagra 50mg sale – viagra pills 200mg order tadalafil 5mg for sale
order modafinil 200mg online cheap – oral modafinil 100mg buy budesonide online cheap
zanaflex pregnancy category zanaflex prescription price flexerill during day and zanaflex at bedtime what is the normal dose for zanaflex
priligy 5 htp generic super avana priligy news on usa priligy how to phase iii
order accutane 10mg online – azithromycin 250mg ca buy generic tetracycline 500mg
cyclobenzaprine ca – colchicine pill buy inderal 20mg generic
clomid after miscarriage clomid 100mg coupon how do you use clomid how is clomid administered
cialis generic australia cialis picture what happens when women take viagra what is cialis used for?
plavix 75mg drug – methotrexate pills metoclopramide order online
purchase cozaar pills – order topamax 200mg without prescription order phenergan generic
natural cialis cialis generic brand australia where can i buy viagra without where to get viagra without a prescription
propecia medicine propecia buy online canada should i take propecia daily how long for propecia side effects to wear off
viagra penis how long does it take for cialis to kick in how many cialis pills should i take how long before viagra works
cialis from canada – buy celebrex 100mg oral flomax
zofran 8mg us – purchase aldactone online buy valacyclovir 500mg online cheap
paxil cr coupon paxil 50 mg when did paxil come out how to ejaculate on paxil
diflucan dosage ringworm diflucan tablet australia yeast infection worse after diflucan how long is diflucan 150 mg in my system
finasteride 5mg brand – purchase finasteride online buy ciprofloxacin 500mg
doramectin and ivermectin ivermectin usa horse health equine ivermectin paste 1.87 how often can i take ivermectin for scabies
paxil grapefruit paroxetine 20 mg tablet cost what happens if you stop taking paxil when do the side effects of paxil wear off
flagyl over the counter – clavulanate usa buy cephalexin 250mg
cost zofran 4mg propecia brand
นั่งปั่น สล็อตPg คาเฟ่ชิล ร้านกาแฟ บรรยากาศ สุดฟิน แบบนี้ สามารถมานั่งปั่นสล็อต pg เพลิดเพลินสนุกไปกับมัน เหมาะสมกับการไปนั่งชิลล์ในวันสบายๆ ร้านกาแฟ อากาศร้อนๆแบบงี้ต้องการ
เกมส์สล็อต PGslot ที่สนุกเป็นระบบการเล่นสล็อตออนไลน์ที่ให้ผู้เล่นได้บริการกันทั่วโลก รวมทั้งเกมสล็อตที่มีระบบอัตโนมัติที่กำหนดความสนุกของแต่ละผู้เล่นใหม่ๆ เว็บของเรา pg slot
ทางเข้า PG แนะนำทางระบบ PG จะมีวิธีการเข้าสู่ระบบที่แตกต่างจากการเข้าสู่ระบบอื่นๆ เพราะระบบpg slot