PowerShell/Windows commands (updating)

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)  

107 Comments

Leave a Reply

Your email address will not be published.


*