Hello. Today I would like to share with you guys some useful PowerShell commands. These are more complex. Why PowerShell? Because it’s easy and much faster than some GUI operations. I will keep this post up to date, so if I will use something new and cool I add it here.
If you want to know more about PowerShell check official PowerShell website, PowerShell Github repo and awesome PowerShell Survival Guide.
Count folder size
Sometimes checking size of folder in Explorer can take ages, especially when there is a lot of small files. Don’t wait! Just use open PowerShell, provide location you want to check and use command:
1 | "{0:N2} MB" -f ((Get-ChildItem C:\path_to_folder\ -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB) |
To see results in GB:
1 | "{0:N2} GB" -f ((Get-ChildItem C:\path_to_folder\ -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1GB) |
Mass extension change
If you want to change extension for many files in folder use this:
1 | Dir *.tiff | rename-item -newname { [io.path]::ChangeExtension($_.name, "tif") } |
In this example all files with tiff extension will be changed to tif.
Display specified number of lines
To get the first 10 lines:
1 | Get-Content ".\test.txt" | select -First 10 |
To get the last 10 lines:
1 | Get-Content ".\test.txt" | select -Last 10 |
Run Active Directory as different user
Use runas
command to run application or other command as different user
1 | runas /user:username@domain "mmc.exe dsa.msc" |
In this case Active Directory Users and Computers snap-in. Provide your user name and domain.
Search in file content
Linux Grep alternative.
1 | Get-ChildItem C:\Users\tes\Documents\ -Filter * -Recurse | Select-String "some_text" |
or
1 | Select-String -Path C:\Users\test\Documents\* -Pattern "some_word" |
Network statistics
Some useful commands to gather network statistics
1 | netsh interface ipv4 show ipstats |
TCP stats:
1 | netsh interface ipv4 show tcpstats |
NetAdapter module
1 | netsh interface ipv4 show tcpstats |
Execution policy
Of course how to bypass it, just for script by spawning a new PowerShell process:
1 | powershell.exe -ExecutionPolicy Bypass -File .\script.ps1 |
PowerShell offers the ability to run commands encoded as base64. To do this, you must encode the contents of the file and pass the resulting string to the -EncodedCommand
switch of PowerShell.
1 | $commands = Get-Content script.ps1 -Raw |
Check policy:
1 | Get-ExecutionPolicy |
Set it:
1 | Set-ExecutionPolicy Bypass |