PowerShell/Windows commands (updating)


  • 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",  ",localhost,*.trendnet.org,*.trendmicro.com,,,,\.\pipe\docker_engine", "Machine")

# PS. EnvironmentVariableTarget: Machine(2)/Process(0)/User(1)
  • 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

(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
foreach($row in $Datatable)
    Write-Host $row.Item(0)

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

  • 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

  • Check powershell 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
# By registry key:
reg query "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion" /v BuildLabEx

# Ref:
  • 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

  • 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
  • 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

  • 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

  • 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'"   

  • Operating the response from commands

XXcommand | Select-Object -Expand Conlumn
  • 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.

  • 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%

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~~~~”
# install DNS management console, run:
Add-WindowsCapability –online –Name “Rsat.Dns.Tools~~~~”
# Verify
Get-WindowsCapability -Name RSAT* -Online | Select-Object -Property DisplayName, State

# Etc.
Add-WindowsCapability -Online -Name Rsat.FileServices.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.GroupPolicy.Management.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.IPAM.Client.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.LLDP.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.NetworkController.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.NetworkLoadBalancing.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.BitLocker.Recovery.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.CertificateServices.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.DHCP.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.FailoverCluster.Management.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.RemoteAccess.Management.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.RemoteDesktop.Services.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.ServerManager.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.Shielded.VM.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.StorageMigrationService.Management.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.StorageReplica.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.SystemInsights.Management.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.VolumeActivation.Tools~~~~
Add-WindowsCapability -Online -Name Rsat.WSUS.Tools~~~~

# 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
  • 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)  

Be the first to comment

Leave a Reply

Your email address will not be published.