Last active
July 23, 2017 03:51
-
-
Save loonison123/10012708 to your computer and use it in GitHub Desktop.
Useful PowerShell Commands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Get powershell version | |
| $PSVersionTable.PSVersion | |
| # Get .NET version source: http://stackoverflow.com/questions/3487265/powershell-to-return-versions-of-net-framework-on-a-machine | |
| Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | | |
| Get-ItemProperty -name Version -EA 0 | | |
| Where { $_.PSChildName -match '^(?!S)\p{L}'} | | |
| Select PSChildName, Version | |
| # Get windows version | |
| [System.Environment]::OSVersion.Version | |
| # Don't truncate long fields when powershell returns content | |
| ... | format-table -autosize | |
| # Get System Restore points (Only on Client OSs) | |
| get-computerrestorepoint | format-table -autosize | |
| # Create System Restore point | |
| checkpoint-computer -description "Installing questionable software" | |
| # When viewing multiple files with different file extensions, group by file extension (i.e. when you cleaning your desktop) | |
| ls | group Extension | sort Count -Descending | |
| # Find number of lines in a file (cat) | |
| get-content file.txt | measure-object | |
| # Find directories that are empty | |
| Get-ChildItem -Recurse -Directory | Where-Object {$_.GetFiles().Count -eq 0} | |
| # Get CPU Load | |
| Get-WmiObject win32_processor | select LoadPercentage | fl | |
| # Get processes by wmi and searching for processes by command arguments | |
| Get-WmiObject win32_process -filter "name = '$processName'" -Property commandline, processid ` | |
| | where { $_.commandline -match $commandLineMatch } ` | |
| | select processid | |
| # For each foreach for-each example | |
| Get-Process | ForEach-Object {Write-Host $_.name -foregroundcolor cyan} | |
| # start a process with arguments | |
| $args = "/v:1.0 /nowait" | |
| $exe ="notepad.exe" | |
| start-process $exe $args | |
| # Prompt the user before commiting an action | |
| -whatif or -confirm | |
| #Exit or kill the currently executing script and exit powershell | |
| Exit | |
| # break wil break out of function or script | |
| Break | |
| # Access arguments in a function and pass arguments to function (spaces) | |
| &doStuff 1 5 | |
| function doStuff | |
| { | |
| return args[0] + args[1]; | |
| } | |
| # View your command history (first 32 by defult out of 64) | |
| get-history | |
| # View first 32 commands | |
| get-hisotry 32 -count 32 | |
| # Set maximum history commands saved | |
| $MaximumHistoryCount = 500 | |
| # Enable remote access via WinRM (Windows Remote Mangement) | |
| # http://technet.microsoft.com/en-us/magazine/ff700227.aspx | |
| get-service winrm # Needs to be running | |
| enable-psremoting -force | |
| winrm s winrm/config/client '@{TrustedHosts="*"}' # Allow anyone to access | |
| # Client remote commands | |
| $a = new-pssession -computername dev-portal | |
| get-pssession | |
| enter-pssession -id 1 # enter-pssession $a | |
| # Replace file content (only for V3) | |
| (gc c:\temp\test.txt).replace('[MYID]','MyValue')|sc c:\temp\test.txt | |
| # Escaping characters | |
| # Single quotes - double single quotes | |
| "he'll'o".Replace('he''ll''o','hi') | |
| # Find difference between two dates | |
| $startDate = get-date | |
| $endDate = [datetime]"01/01/2016 00:00" | |
| new-timespan -start $startDate -end $endDate | |
| # Get current directory of currently running script | |
| $scriptPath = $MyInvocation.MyCommand.Path | |
| $dir = split-path $scriptPath | |
| # Pass arguments to remote commands | |
| $arg1 = "x:\\sites\site1" | |
| $a = new-pssession -computer remotename | |
| invoke-command -session $a -script {param($whatyouwant) cd $whatyouwant} -Args $arg1 | |
| # Check for null | |
| $a = $null | |
| if ($a) { | |
| # NOT NULL | |
| } else { | |
| # NULL | |
| } | |
| # Map drive | |
| new-psdrive -name "k" -psprovider FileSystem -Root "\\api-01\c$" -Persist | |
| # Read a JSON file | |
| (Get-Content JsonFile.JSON) -join "`n" | ConvertFrom-Json | |
| # Turn PS-Drive path into UNC path for .NET file operation classes | |
| (Resolve-Path $file).ProviderPath | |
| # i.e. - (Resolve-Path "nodeBox:\sites\node1").ProviderPath --> \\node-01\sites\node1 | |
| # Copy file with buffer and progress bar | |
| # http://stackoverflow.com/questions/2434133/progress-during-large-file-copy-copy-item-write-progress | |
| function Copy-File { | |
| param( [string]$from, [string]$to) | |
| $ffile = [io.file]::OpenRead($from) | |
| $tofile = [io.file]::OpenWrite($to) | |
| Write-Progress -Activity "Copying file" -status "$from -> $to" -PercentComplete 0 | |
| try { | |
| [byte[]]$buff = new-object byte[] 4096 | |
| [int]$total = [int]$count = 0 | |
| do { | |
| $count = $ffile.Read($buff, 0, $buff.Length) | |
| $tofile.Write($buff, 0, $count) | |
| $total += $count | |
| if ($total % 1mb -eq 0) { | |
| Write-Progress -Activity "Copying file" -status "$from -> $to" ` | |
| -PercentComplete ([int]($total/$ffile.Length* 100)) | |
| } | |
| } while ($count -gt 0) | |
| } | |
| finally { | |
| $ffile.Dispose() | |
| $tofile.Dispose() | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment