
PowerShell
-
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
$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)
$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-Acl -Path C:\inetpub\wwwroot\App_Data\MailSetting4Test.xm
l | Format-Table -Wrap
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
-
Install docker preview (support linux container) in Windows Server 2019 ref
# Enable Nested HyperV and install HyperV first
Uninstall-Package -Name docker -ProviderName DockerMSFTProvider
Install-Module DockerProvider
Install-Package Docker -ProviderName DockerProvider -RequiredVersion preview
# Switch to linux container
[Environment]::SetEnvironmentVariable("LCOW_SUPPORTED", "1", "Machine")
Restart-Service docker
# Switch to Windows container
[Environment]::SetEnvironmentVariable("LCOW_SUPPORTED", $null, "Machine")
Restart-Service docker
-
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>', '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.
move C:\ProgramData\docker\* D:\ProgramData\docker
cmd /c mklink /d C:\ProgramData\docker D:\ProgramData\docker
# /d for folder
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
-
刪除 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
-
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)
Viagra Generique Pharmacie when viagra patent expire
buy cialis online 20mg
plaquenil indications
dosis viagra
zithromax over the counter walmart
Azithromycin Vs Amoxicillin
buy cialis online with prescription
half life of plaquenil
Ditrim 480 Mg
cialis 40 mg
Bentyl Website Without Perscription
side effects of propecia
loss viagra prescription
kamagra en farmacias kamagra mal de altura kamagra alicante
Hormone replacement therapy is given when entire glands are removed or do not produce enough hormones. Petedick http://www.apriligyn.com – priligy over the counter usa
Propecia Caldea levitra acheter oberry
Hiqtql Buy Cephalexin On Line Prednisone Cialis Sublingual Review
pharmaceutical grade generic tadalafil cialis Ncsbjt what is plaquenil
uso viagra efectos Jepomd Plaquenil
ivermectin 12 stromectol for sale
sildenafil citrate alternative revatio sildenafil 20 mg
cipla tadalafil 20 mg how to make tadalafil
buy stromectol ivermectin generic
ivermectin for humans ivermectin cream cost
ivermectin for sale stromectol for humans
stromectol oral ivermectin new zealand
ivermectin 10 ml stromectol liquid
ivermectin 3 mg ivermectin syrup
ivermectin where to buy for humans ivermectin 0.08
ivermectin for humans cost for ivermectin 3mg
ivermectin 50mg/ml stromectol otc
ivermectin 10 ml ivermectin 10 ml
ivermectin price ivermectin 0.5
stromectol canada stromectol prices
cialis over the counter buy cialis online safely
cost of ivermectin pill ivermectin 0.1 uk
side effects of sildenafil generic viagra soft tabs
ivermectin tablet price cost of ivermectin 1% cream
buy cialis pro generic name for cialis
ivermectin buy nz ivermectin tablet price
is tadalafil from india safe tadalafil tab
vardenafil vs sildenafil cheap sildenafil
how much tadalafil to take average dose of tadalafil
viagra order viagra wiki
walmart pharmacy online canadianpharmacymeds
Biltricide walmart store locator pharmacy
tadalafil 20mg for sale tadalafil long term usage
cialis online fast free cialis voucher
levitra generic 10mg levitra professional reviews
world best pharmacy online store reviews erectile dysfunction medications
can you take sildenafil daily buy viagra online in australia
best viagra pills over the counter viagra cream australia
ivermectin/pyrantel for dogs worming goats with ivermectin
ivermectin guinea pig ivermectin cream before and after
cialis information viagra cialis
when will generic tadalafil be available tadalafil 30mg liquid
Shallaki online pharmacy reviews forum
levitra precio levitra generic canada
cialis paypal cialis windsor canada
celexa canadian pharmacy world pharmacy store
dominican republic pharmacy online is world pharmacy store legit
topical rx pharmacy wedgewood pharmacy pet rx
discount viagra canadian pharmacy opioid prescription drugs
reddit best online pharmacy go coupon
pharmacy mall online reviews legal canadian pharmacy online
rx pharmacy meaning pharmacy technician salary
metformin 1000 mg pill metformin 850 mg tablet
buy tadalafil india tadalafil price
lipitor rx cost cheapest generic lipitor
https://buynolvadex.store/# tamoxifen citrate pct
электроштабелеры
https://elektroshtabeler-kupit.ru/
furosemide lasix for sale
https://buylipitor.store/# lipitor prescription drug
lasix lasix
buy generic tadalafil online buy cheap tadalafil online
https://buytadalafil.men/# tadalafil online without prescription
https://cipro.best/# ciprofloxacin 500 mg tablet price
https://cipro.best/# ciprofloxacin order online
neurontin capsules 300mg neurontin online
https://diflucan.icu/# buy diflucan online india
ciprofloxacin 500mg buy online cipro pharmacy
diflucan uk online diflucan 6 tablets
diflucan otc diflucan tablet 500mg
https://gabapentin.icu/# neurontin tablets 300 mg
штабелер самоходный
https://www.shtabeler-elektricheskiy-samokhodnyy.ru/
buy prescription drugs online legally buy canadian drugs
generic propecia
buy propecia usa
drugs for ed non prescription ed drugs
https://gabapentin.icu/# neurontin 150 mg
https://withoutprescription.store/# prescription drugs online without
top ed pills best ed treatment
diflucan singapore pharmacy buy diflucan no prescription
https://diflucan.icu/# diflucan 50 mg capsule
buy prescription drugs without doctor amoxicillin without a doctor’s prescription
how to get prescription drugs without doctor buy prescription drugs without doctor
prescription drugs online without anti fungal pills without prescription
https://withoutprescription.store/# ed meds online without doctor prescription
https://cipro.best/# buy cipro online
what are ed drugs ed treatments
can i purchase diflucan over the counter cost of diflucan
medication for ed dysfunction best ed pill
https://stromectol.life/# stromectol
https://stromectol.life/# ivermectin cream cost
https://stromectol.life/# stromectol 12 mg tablets
treatments for ed amoxicillin without a doctor’s prescription
best erectile dysfunction pills ed medications list
stromectol 3mg tablets stromectol for sale