Miscellaneous PowerShell Command, which are used in our day to day Jobs.
Find remaining Terminal Services Grace Period using Get-WmiObject
(Invoke-WmiMethod -PATH (gwmi -namespace
root\cimv2\terminalservices -class win32_terminalservicesetting).__PATH -name
GetGracePeriodDays).daysleft
Find remaining Terminal Services Grace Period using using Get-CimInstance
(Invoke-CimMethod -InputObject (Get-CimInstance -Namespace root/CIMV2/TerminalServices -ClassName Win32_TerminalServiceSetting) -MethodName GetGracePeriodDays).DaysLeft
List all wmi classes or under WMI Namespace
Get-WmiObject -namespace root\cimv2 -List
Get-WMIObject -List| Where{$_.name -match "^Win32_"} | Sort Name | Format-Table Name
List FileSystem utilization
get-wmiobject -Class Win32_Logicaldisk |where { $_.Drivetype -eq 3 }
get-wmiobject -Class Win32_Logicaldisk -filter "drivetype=3"
get-wmiobject -Class Win32_Logicaldisk -filter "drivetype=3" | Format-Table -Property DeviceID,Name,Freespace -autosize
get-wmiobject -Class Win32_Logicaldisk -filter "drivetype=3" | Format-Table -Property DeviceID,Name,@{name='Freespace';Expression={$_.Freespace /1GB }} -Autosize
get-wmiobject -Class Win32_Logicaldisk -filter "drivetype=3" | Format-Table -Property DeviceID,Name,@{name='Freespace';Expression={$_.Freespace /1GB };FormatString='F2'} -Autosize
get-wmiobject -Class Win32_Logicaldisk -filter "drivetype=3" | Format-Table -Property DeviceID,Name,@{name='Freespace';Expression={$_.Freespace /1GB };FormatString='F2'},@{name='Size';Expression={$_.Size /1GB};FormatString='F2'} -Autosize
Export information in neat/simple looking GUI with filtering options.
Get-Process | Out-GridView
It will ask for alternate credentials to be used to process the command
Get-WmiObject -Class win32_logicaldisk -Credential Administrator
Sample WQL (Wmi Query Language)
Get-Wmiobject -query "SELECT * FROM Win32_Bios"
List all jobs
Get-job
list all child jobs
get-job id 2 | select-object -expandProperty Childitem
retreive the job results
receive-job -id 3 (will delete the result from memory after showing it)
receive-job -id 3 -keep (Will keep the copy even after showing the result)
remove-job id 2 (to remove the jobs from memory)
stop-job id 8
Set special variable.
[int]$age = read-host "enter your age"
[string]$name = read-host "Enter your Name"
Get List of users/Groups under Local Administrators
([ADSI]"WinNT://Localhost/Administrators").Members() | Select-Object @{n='Name';e={ $_.GetType().InvokeMember('Name', 'GetProperty', $Null, $_, $Null) }},@{n='ADSPath';e={ $_.GetType().InvokeMember('ADSPath', 'GetProperty', $Null, $_, $Null) }},@{n='Class';e={ $_.GetType().InvokeMember('class', 'GetProperty', $Null, $_, $Null) }} |fl
Sample Loop in PowerShell
for ($i=0; $i -le 99; $i++) { write-host $i }
Get Server BootUp Time
Get-WmiObject win32_operatingsystem -computername localhost | select CsName,@{N='LastBootUpTime';E={$_.ConverttoDateTime($_.lastbootuptime)}}
Speakout a Text message , Speak , Voice
(new-object -com SAPI.SpVoice).speak("Sir! Your file-copy operation completed successfully, Thank you!!")
Ping with timestamp
Test-Connection 192.168.192.1 -count 999 |format-table -property Address,buffersize,ipv4address,ResponseTime,TimeToLive,@{N='Timestamp';E={get-date -uformat %T}}
Get installed driver versions
Get-WmiObject Win32_PnPSignedDriver| select devicename, driverversion
List only directories
Get-ChildItem c:\media |Where-Object {$_.PSIsContainer -eq $True}
List of Disabled Userd from AD using Windows Powershell
Get-ADUser -Filter {Enabled -eq "False"}
List of Disabled Userd from AD using Quest Powershell
Get-QADUser -sizelimit 0 -Disabled
Get Process information on remote computers.
get-WmiObject -class win32_process -computername ServerName | Select-Object -prop __Server,Name,WorkingSetSize,@{n='Owner';e={$_.getowner().user}} |ft -AutoSize
MemberOf of a User
(Get-ADUser UserID -Properties MemberOf | Select-Object MemberOf).MemberOf |Get-ADGroup |select Name
Average CPU Usage Memory Usage
Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average
Get-WmiObject -Class win32_operatingsystem |Select-Object @{Name = "MemoryUsage"; Expression = {“{0:N2}” -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize) }}
Get top 10 process, utilizing max CPU:
gwmi -computer XXXXXXXXX Win32_PerfFormattedData_PerfProc_Process| sort PercentProcessorTime -desc | select Name,PercentProcessorTime | Select -First 10 | ft -auto
Counters to get CPU usage:
"\Processor(*)\% Processor Time" | Get-Counter -Computer XXXXXXXXX -MaxSamples 2 -SampleInterval 10
Counters to get virtual processor utilization:
"\VM Processor(*)\% Processor Time" | Get-Counter -Computer XXXXXXXXX -MaxSamples 2 -SampleInterval 10
Counters to get Virtual Memory Usage:
"\Memory\% Committed Bytes In Use" | Get-Counter -Computer XXXXXXXXX -MaxSamples 2 -SampleInterval 10
Counters to get Paging File Usage:
"\Paging File(*)\% Usage" | Get-Counter -Computer XXXXXXXXX -MaxSamples 2 -SampleInterval 10
Counters to get Number of Interrupts:
"\Processor(*)\Interrupts/sec" | Get-Counter -Computer XXXXXXXXX -MaxSamples 2 -SampleInterval 10
Telnet to a port
(New-Object System.Net.Sockets.TcpClient).Connect("HostName", Port)
filter by parameters
get-process |where handles -gt 900 | sort handles
get-process |where {$_.handles -ge 1000}
Invoke command on / from remote computers.
invoke-command -computername dc1,dc2,serv1,serv2 {get-eventlog -logname system -new 3}
GetMemory Usage Stats
gwmi -Class win32_operatingsystem| select CSname, @{N='TotalMemory';E={$_.TotalVisibleMemorySize /1MB}},@{N='FreeMemory';E={$_.FreePhysicalMemory/1MB}} |ft -AutoSize
return number of services stored in the $services variable
$Services=Get-service
$services[1..5] #will return 5 services stored in the $services variable
$services.Count
Sample IF Else Condition on PowerShell
if (Test-Connection -ComputerName Localhost -quiet -count 1) {Write-Host "Server is alive"} Else {Write-Warning "Server is Offline"}
Get output of a command from remote machine
Invoke-Command -ComputerName servername { hostname }
Add days to before days
[DateTime]::Today.AddDays(350)
[DateTime]::Today.AddDays(-350)
Get Disk Space usage
Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq "3" } | Select-Object SystemName, @{ Name = "Drive" ; Expression = { ( $_.DeviceID ) } }, @{ Name = "Size (GB)" ; Expression = {"{0:N1}" -f( $_.Size / 1gb)}}, @{ Name = "FreeSpace (GB)" ; Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) } }, @{ Name = "PercentFree" ; Expression = {"{0:P1}" -f( $_.FreeSpace / $_.Size ) } } | Format-Table -AutoSize
Get-WmiObject -Class win32_volume | Where-Object { $_.Name -match "c:" } | select-object Systemname,@{Name = "Drive" ; Expression = {$_.Name}},@{ Name = "Size (GB)"; Expression = {"{0:N1}" -f( $_.Capacity / 1gb)}}, @{ Name = "FreeSpce (GB)"; Expression = {"{0:N1}" -f( $_.FreeSpace / 1gb)}},@{ Name = "PercentFree" ; Expression = {"{0:P1}" -f( $_.FreeSpace / $_.Capacity) } } | format-table -AutoSize
Write Blank Line
Write-Host " `r"
Get Diskspace C:
Get-WmiObject Win32_LogicalDisk -computername <ServerName> | Where-Object { $_.DeviceID -clike "C:" } | Select-Object SystemName, @{ Name = "Drive" ; Expression = { ( $_.DeviceID ) } }, @{ Name = "Size (GB)" ; Expression = {"{0:N1}" -f( $_.Size / 1gb)}}, @{ Name = "FreeSpace (GB)" ; Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) } }, @{ Name = "PercentFree" ; Expression = {"{0:P1}" -f( $_.FreeSpace / $_.Size ) } }
Get Local ComputerName
$env:computername
$(Get-WmiObject Win32_Computersystem).name
Legacy Command Outputs to Powershell Objects
driverquery /fo csv |ConvertFrom-Csv
Display lines containing a string or text.
nbtstat /n |select-string "<"
Trim blank / empty lines:
$data = nbtstat /n |select-string "<"
$Lines = $data |foreach {$_.Line.Trim()}
OR
nbtstat /n |Select-String "<" |foreach { $_.Line.Trim()}
net user replace string
net user | where {$_ -notmatch "command" -and $_ -notmatch "-"}
Print Ascii Charactor
[char]120
Print a range of Ascii charactor
[char[]](1..120)
Print Ascii Value
[int][char]'A'
Print Ascii Value array
[int[]][char[]]'Hello'
Random Password Generator
$randomObj = New-Object System.Random
$NewPassword=""
1..20 | ForEach { $NewPassword = $NewPassword + [char]$randomObj.next(33,126) }
$NewPassword
OR
Add-Type -AssemblyName System.Web
$pass = [System.Web.Security.Membership]::GeneratePassword(16,2)
Write-Output $pass
Print output and send to variable
get-process | tee-object -Variable procs
Get username and Password from stored Credential
$cred.getnetworkcredential().password
$cred.getnetworkcredential().username
Create multiline String/Variable
$x = 'Start
Step
End'
Create Multiline String/Variable
$Var1=”@
String1
String2
String3
“@
Interactive Command input
show-command get-childitem
Create Alias
New-Alias -Name test -Value Get-ChildItem
List all the commands which accept -Computername as parameter
Get-Command –ParameterName ComputerName
Filter
Get-Adcomputer -filter {name -like '2012*'} |ft -autosize
Create Simple/Sample Function
function Get-SystemInfo {
Get-Volume | Sort-Object SizeRemaining –Descending
Get-NetAdapter | Select-Object –Property Name, Interface*, Status
}
OR
Function Get-SystemInfo { param($machineName)
$session = New-CimSession –ComputerName $machineName
Get-Volume –cimsession $session
Get-NetAdapter –cimsession $session |
Select-Object –Property Name, InterfaceIndex, Status, PSComputerName
}
Make alias permanent, Initialize upon new console opening, add all the items to below file and save it:
Location $Profile
C:\Users\prakakum\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Filter Objects
Get-service -Name A* |where-object Status -eq Stopped
Read file and process objects
get-content -path c:\temp\services.txt | stop-service
List services by status:
Get-Service | group-object -Property Status
Measure-object count
gci -Path C:\Windows -File |Measure-Object
Measure-object (average)
gci -Path C:\Windows -File |Measure-Object -Average -Property Length
Format List with selected values
Get-Process powershell | Format-List -Property *
Invoke-command remotely and get result.
Invoke-Command {start-process notepad.exe -passthru}
Store Command output to Variable
Get-Volume -OutVariable volInfo
Invoke-Command –ComputerName 2012R2-MS –Scriptblock {Get-Volume –OutVariable volInfo}
Retrieve Variable info from remote computer
Invoke-Command –ComputerName 2012R2-MS –Scriptblock {Get-Variable –Name volInfo}
Disable Automatic Updates on remote computers:
Invoke-Command –ComputerName 2012R2-MS, 2012R2-DC, WIN8-WS –Scriptblock {
Get-Service –DisplayName “Windows Update” | Set-Service –StartupType Disabled
Get-Service –DisplayName “Windows Update” | Stop-Service }
Change color of powershell console
$host.UI.RawUI
$host.UI.RawUI.ForegroundColor
Run a script which contains Space
& c:\Test Folder\sysinfo.ps1 # & tells the console to treat the string as command.
Define Parameters
Param ($name, $Param2)
get-service -name $name
#use get-service -name messenger
Return all .exe files in C:\Windows\System32 whose names start with the letter “d”, “g” or “n”.
Get-ChildItem C:\Windows\System32\[dgn]*
Get all folders whose name ends with the character “n” in C:\Windows\System32
Get-ChildItem C:\Windows\System32\*n -Directory
Find all .txt files in C:\Windows\System32\WindowsPowerShell\v1.0, recursively. Use the Get-ChildItem Cmdlet’s –filter parameter.
gci C:\Windows\System32\WindowsPowerShell\v1.0\ -Recurse -File -Filter *.txt
Convert to MB Megabyte
$total = (Get-ChildItem C:\windows\System32 -file | Measure-Object -Property length –sum).Sum
Convert to GB GigaBytes
$total = (Get-ChildItem -Recurse C:\Windows\System32 -ErrorAction SilentlyContinue | Measure-Object -Property length -sum).Sum
Filter object:
Get-Service -Name a* | Where-Object -FilterScript { $_.Status -eq 'Running' }
Get-Service -Name a* | ? { $_.Status -eq 'Running' }
Loop Process
Get-Service -Name a* | ? { $_.Status -eq 'Running' } | ForEach-Object -process {$_.start;$_}
Get-Service -Name a* | ? { $_.Status -eq 'Running' } | ForEach-Object -process {$_.start(); Start-Sleep 5; $_}
Users whose AccountExpirationDate property is less than or equal to 6 months from today’s date.
$userList | where-object {$_.accountexpiration -le (get-date).AddDays(180)} |select Name,AccountExpirationDate
Count Items
Get-Service | foreach -Begin {"Counting Services..." ; $count=0} -Process {$count++} -End {“$count services were found”}
Process from Pipeline
Server1,Server2 | Select-Object @{name="ComputerName";Expression={$_}} | Get-Service -Name BITS | Format-Table MachineName, Name, Status -autosize
Read Registry Values: (Registry Key = Item; Registry Value = ItemProperty)
(Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\2\').Description
Map Network Path as Share
New-SmbShare -CimSession (New-CimSession -ComputerName 2012R2-MS) -Path C:\DocumentBackup -Name Backup -FullAccess "Contoso\Domain Users"
Find and Replace in filename
Get-ChildItem -Path d:\Archive\Finance -File -Recurse | Rename-Item -NewName { $_.fullname.replace(".log",".old") }
Share a folder as 'Backup'
New-SmbShare -CimSession (New-CimSession -ComputerName 2012R2-MS) -Path C:\DocumentBackup -Name Backup -FullAccess "Contoso\Domain Users" -ErrorAction SilentlyContinue
Set the LastWriteTime file property to 60 days in the past for local files Get-ChildItem -Path
$docs\Finance -Recurse |Set-ItemProperty -Name LastWriteTime -Value (Get-Date).AddDays(-60)
Get all files modified more than a month ago
Get-Childitem -File -Path $docs\Finance -Recurse | Where LastWriteTime -lt (Get-Date).addDays(-30)
Rename file extensions from '.log' to '.old'
Get-ChildItem -Path $docs\Archive\Finance -File -Recurse | Rename-Item -NewName { $_.fullname.replace(".log",".old") }
Special Character Description
`0 Null
`a Alert
`b Backspace
`f Form feed
`n New line
`r Carriage return
`t Horizontal tab
`v Vertical tab
" `r" Write-Host Blank Like
Default Split operator looks for Spaces
-split “I am a space delimited string”
The binary form allows the use of a delimiter character.
“Split,me,on,all,commas” –split “,”
The delimiter can be preserved, and output, by enclosing it in smooth parentheses.
“Split,me,on,all,commas” –split “(,)”
control the maximum number of separate substrings returned. In the last array position, the remaining strings are collected.
“Finance,Marketing,IT,Sales,Support,Operations” –split “,”, 4
Specify delimiter ranges within square braces [ ].
"Split;me,on.lots'of:characters” –split “[;,:.']"
Replace string
“Hello name” –replace “name”, “Matt”
Create Empty Hash Table
$hash = @{}
Create Empty Array
$array = @()
Verify Empty Array for members
$emptyArray.Count
Add Items (Members) to empty Array:
$emptyArray += “PC”
$emptyArray += “Phone”
Extend Array
$users = "Johan","Chris","Luke"
$users += "Gary"
Combine Arrays:
$users = "Johan","Chris","Luke"
$users2 = "Russel","Sean","Amit",”Pat”,”Matt”,”Darren”
$users3 = $users + $users2
Sort and Save Array
$aryUsers = $aryUsers | Sort-Object
$aryUsers | Select-Object -First 10
Sort and Reverse Array:
[array]::Reverse($aryUsers) $aryUsers | Select-Object -First 10
[array]::Sort($aryUsers) $aryUsers | Select-Object -First 10
Clear Array content:
$aryUsers.Clear()
$aryUsers.GetType()
Create PSobJect: PS 2.0
$props = @{
Division = 'IT' Laptop = 'Surface' Ferrari = $false
}
$object = New-Object PSObject -Property $props
$object | Format-List -Property *
Customize ISE Environment
$PSIse.Options
$psISE.Options.ConsolePaneBackgroundColor="orange"
$psISE.Options.RestoreDefaults()
Color Output of result
Get-Service | Foreach {
if($_.status -imatch "running"){write-host $_.name ':' $_.displayname ':' $_.Status -foreground Green }
if($_.status -imatch "stopped"){write-host $_.name ':' $_.displayname ':' $_.Status -foreground Red }
}
Export Windows drivers:
Export-WindowsDriver -Destination c:\temp\ -Online
Mount ISO Image
Mount-DiskImage -ImagePath C:\Data\en_office_professional_plus_2016_x86_x64_dvd.iso
invoke PowerShell command with hidden window
powershell.exe -windowstyle hidden -file C:\lock.ps1
System Sounds.
[System.Media.SystemSounds]::Beep.Play()
[System.Media.SystemSounds]::Hand.Play()
[System.Media.SystemSounds]::Asterisk.Play()
[System.Media.SystemSounds]::Exclamation.Play()
System Beep
[console]::beep(1600,200)
[system.console]::Beep(440,1000)
Read host to Array
[string[]] $servers = (Read-Host "Enter User(s) separate with comma if more than one").split(',') | % {$_.trim()}
Get list of certificates expiring in 30 days:
Get-ChildItem Cert:\LocalMachine\My\ -ExpiringInDays 30 | Select-Object Thumbprint, Subject, NotAfter
Get-Console settings color forground background error etc..
Get-PssessionConfiguration
Password from File: Password to file
read-host -assecurestring | convertfrom-securestring | out-file C:\cred.txt
$password = get-content C:\cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "myusername",$pass
Services running under specific user name
gwmi win32_service -Filter { Startname = "LocalSystem"} |ft name,state,startmode,Startname
Difference between two dates:
$begin = [datetime]'02/10/2011'
$end = [datetime]'01/10/2013'
$monthdiff = $end.month - $begin.month + (($end.Year - $begin.year) * 12)
Get Last Reboot Log
Get-EventLog -Source user32 -LogName System -Newest 2|fL MachineName,TimeWritten,Source, Message
Fun With Colors on Powershell Console"
1..255 | foreach {Write-Host " " -BackgroundColor (Get-Random 'Black', 'DarkBlue','DarkGreen','DarkCyan', 'DarkRed','DarkMagenta','DarkYellow','Gray','DarkGray','Blue','Green','Cyan','Red','Magenta','Yellow','White') -NoNewline}
Get Random color
([System.ConsoleColor] | Get-Member -MemberType Property -Static).Name | Get-Random
Next Available Drive Letter
[char[]]'CDEFGHIJKLMNOPQRSTUVWXYZ' | ? { (Get-PSDrive $_ -ErrorAction 'SilentlyContinue') -eq $null } |select -First 1
Existing Drive Letters in Use
fsutil fsinfo drives
Get Disk Drives, Size, Scsi ID, Target ID Etc on Windows Server
Get-WmiObject Win32_DiskDrive | select-object DeviceID,@{N="Size GB";E={ "{0:N0}" -f ($_.size/1GB)}},scsiport,scsibus,scsitargetid,scsilogicalunit
UnCompress / UnZip using PowerShell
powershell.exe -nologo -noprofile -command "& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('C:\Windows\Zabbix_win64\zabbix_agents_3.2.0.win.zip', 'C:\Windows\Zabbix_win64\zabbix\'); }"
Change Password of Logon account on a Service
sc config remoteregistry obj= .\TestUser password= Password@123
Watch equivalent in PowerShell as in Linux
1..9 |foreach {get-date -Format G; net user; Write-Host " `n";start-sleep 10}
Create Random 50 AD Computer Accounts (Computer1..Computer50)
1..50 |foreach {New-ADComputer -name computer$_}
Compress/Zip a Folder defined in $InputDir as $OutArchiveName
Add-Type -A 'System.IO.Compression.Filesystem'; [IO.Compression.ZipFile]::CreateFromDirectory(($InputDir), $OutArchiveName)
Decompress/UnZip an Archive defined in $InputArchive to $OutPath
Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory($InputArchive, $OutPath)
Generate Self Signed Certificate:
New-SelfSignedCertificate -DnsName zabbixtest.com -CertStoreLocation Cert:\CurrentUser\
Read Keyboard Keys
while($true){[Console]::ReadKey($true)}
Compress using WMI
$file = Get-WmiObject -Query "SELECT * FROM CIM_DataFile WHERE Name='C:\\scripts\\test.vhd'"
$file.Compress()
UnCompress using WMI
$file = Get-WmiObject -Query "SELECT * FROM CIM_DataFile WHERE Name='C:\\scripts\\test.vhd'"
$file.Uncompress()
Clear Console output
[CONSOLE]::Clear()
File Browser using Powershell
Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
Multiselect = $false # Multiple files can be chosen
}
[void]$FileBrowser.ShowDialog()
$file = $FileBrowser.FileName;
File Browser Using PowerShell
Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{ InitialDirectory = [Environment]::GetFolderPath('Desktop') }
$null = $FileBrowser.ShowDialog()
$FileBrowser.FileName
Server Core to Gui and Gui to Server Core
Uninstall-WindowsFeature Server-Gui-Mgmt-Infra,Server-Gui-Shell
Install-WindowsFeature Server-Gui-Mgmt-Infra,Server-Gui-Shell
Import-Module Dism;Enable-WindowsOptionalFeature -online -Featurename ServerCore-FullServer,Server-Gui-Shell,Server-Gui-Mgmt
Read Password as SecureString masked
$password = Read-host "Drac root password?" -AsSecureString
$PSWD = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
Remove blank Lines:
-match '\S'
| where {$_ -ne ""}
Get Volume Details
Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq "3" } | Select-Object SystemName, @{ Name = "Drive" ; Expression = { ( $_.DeviceID ) } }, @{ Name = "Size(GB)" ; Expression = {"{0:N1}" -f( $_.Size / 1gb)}}, @{ Name = "FreeSpace(GB)" ; Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) } }, @{ Name = "PercentFree" ; Expression = {"{0:P1}" -f( $_.FreeSpace / $_.Size ) } }, @{ Name = "VolumeName" ; Expression = { ( $_.VolumeName ) } }
Get Physical Disk Details
Get-WmiObject -Class Win32_diskdrive |select PSComputerName, NeedsCleaning, Status, DeviceID, Partitions, InterfaceType, SectorsPerTrack,@{N="Size (GB)";E={"{0:N1}"-f( $_.Size/1gb)}}, CapabilityDescriptions, Caption, Description, Manufacturer, MediaType, Model, Name, SCSIBus, SCSILogicalUnit, SCSIPort, SCSITargetId, SerialNumber, Signature
Get FQDN of remote servers:
[System.Net.Dns]::GetHostByName(“ComputerName”)
Dialogue Box
[System.Windows.Forms.MessageBox]::Show('text', 'title')
[System.Windows.Forms.MessageBox]::Show("Cannot find drivers on computer: $ComputerName", 'Driver fetch error')
Dialogue Box
[reflection.assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Windows.Forms.Application]::EnableVisualStyles()
[System.Windows.Forms.MessageBox]::Show("Would you like a MessageBox popup ?","This is a question !", "YesNoCancel”)
Save Module from PowerShell Gallery for Oflline install on a server with no internet and copy the content to :C:\Windows\System32\WindowsPowerShell\v1.0\Modules
Save-Module -Name PowerShellGet -Path C:\temp\PSGet -Repository PSGallery
Save-Module -Name MicrosoftPowerBIMgmt -Path C:\temp\PSGet\ -Repository PSGallery
TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Run as Administrator command window
function GoAdmin { start-process cmd.exe –verb runAs }
PowerShell Command history
notepad "$env:APPDATA\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt"
Create a Credential Object:
PS C:\> $creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "rlywin@adobe.com", ($ABC |ConvertTo-SecureString -AsPlainText -Force)
Get Resolution:
Add-Type -AssemblyName System.Windows.Forms ;[System.Windows.Forms.Screen]::AllScreens
Encode XML Password
$UnEncodedText = 'IamAdminPassword'
$EncodedText =[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($UnEncodedText))
write-host "Encoded_String_is:" $EncodedText
Decode XML Password
$EncodedText = 'SQBhAG0AQQBkAG0AaQBuAFAAYQBzAHMAdwBvAHIAZAA='
$DecodedText = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($EncodedText))
write-host "Decoded_Text_is:" $DecodedText
PowerShell Headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36")
$States = Invoke-RestMethod 'https://cdn-api.co-vin.in/api/v2/admin/location/states' -Method GET -Headers $headers
$States.states
Create Random folders with Date Format
1..30| foreach {$a = "c:\temp\2\"+(Get-Date).AddDays(-$_).ToString('yyyy-MM-dd');$a; mkdir $a}
Resolve DNS and open new Firefox Tabs for each URL/IP
101..105 |foreach {(Resolve-DnsName 10.51.187.$_).namehost} |foreach {start firefox $_}
check if Laptop is on Power
(Get-WmiObject -Class BatteryStatus -Namespace root\wmi).PowerOnLine
Replace Content in file:
$RDPFiles = Get-ChildItem C:\work\RDPFiles\*.rdp
$RDPFiles | foreach {
$RDPFILE = $_.Name
Write-host Working on `t $RDPFILE -ForegroundColor Green
(Get-Content C:\work\RDPFiles\$RDPFILE -Raw) -replace "desktopwidth:i:1920","desktopwidth:i:1916" -replace "desktopheight:i:1080","desktopheight:i:964" |Set-Content C:\work\RDPFiles\$RDPFILE
}
Set IP Address
netsh int ip set address name=NIC1 static 10.20.20.20 255.255.252.0 10.10.10.1
Set Primary DNS
netsh int ip set dns NIC1 set 10.20.30.40
Set Secondary DNS
netsh int ip add dns NIC1 8.8.8.8
Set DNS Suffixes
reg add "HKLM\System\CurrentControlSet\Services\TCPIP\Parameters" /V Searchlist /T REG_SZ /D "mydomain.com,domain.com,subdomain.com"
Set Firewall Policies to Allow communiation.
netsh advfirewall set allprofile firewallpolicy allowinbound,allowoutbound
Assign IP address on the FIRST NIC which is Online.
powershell -command "$NIC = (Get-NetAdapter |where status -eq up |select -First 1).name; netsh int ip set address name=$NIC static 10.10.10.10 255.255.255.252 10.10.10.1"
Assign Primary DNS on the FIRST NIC which is Online.
powershell -command "$NIC = (Get-NetAdapter |where status -eq up |select -First 1).name; netsh int ip set dns $NIC set 10.10.10.53
Assign Secondary DNS on the FIRST NIC which is Online.
powershell -command "$NIC = (Get-NetAdapter |where status -eq up |select -First 1).name; netsh int ip add dns $NIC 8.8.8.8
Enable logging on with Saved credentials.
Computer Configuration > Administrative Templates > Windows Components > Remote Desktop Services > Remote Desktop Session Host > Security.
Set ‘Always prompt for password upon connection‘ to disabled.
SMB1 v1 Detect:
Get-WindowsFeature FS-SMB1
SMB1 v1 Disable:
Disable-WindowsOptionalFeature -Online -FeatureName smb1protocol
SMB1 v1 Enable:
Enable-WindowsOptionalFeature -Online -FeatureName smb1protocol
SMB2 v2/v3 Detect:
Get-SmbServerConfiguration | Select EnableSMB2Protocol
SMB2 v2/v3 Disable:
Set-SmbServerConfiguration -EnableSMB2Protocol $false
SMB2 v2/v3 Enable:
Set-SmbServerConfiguration -EnableSMB2Protocol $true
List Trusted Domains by the system
nltest /server:localhost /trusted_domains
Get Domain name of the Computername:
wmic computersystem get domain
(Get-WmiObject -Class Win32_ComputerSystem).domain
$env:USERDNSDOMAIN
Set Time Sync with Domain
w32tm /config /syncfromflags:domhier /update & w32tm /resync & w32tm /query /status /verbose
Set TLS Version
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
OR
[Net.ServicePointManager]::SecurityProtocol =
[Net.SecurityProtocolType]::Tls12 -bor `
[Net.SecurityProtocolType]::Tls11 -bor `
[Net.SecurityProtocolType]::Tls
Reset iDRAC root Password Local Racadm
racadm set iDRAC.Users.2.Password Pa55W0rd@Here
Terminal Server Licensing mode Settings:
'reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /T REG_SZ /V LicenseServers /D tscalserver.domain.com'
'reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /T REG_DWORD /V MaxInstanceCount /D 10'
'reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /T REG_DWORD /V LicensingMode /D 2'