Reputation: 16186
Provide one line PowerShell script that you found useful, one script per answer please.
There is a similar question here, but this one gives only links to pages with scripts, lets answers one by one here and have a contributed list of most frequently used or most useful scripts.
List most recent version of files
ls -r -fi *.lis | sort @{expression={$_.Name}}, @{expression={$_.LastWriteTime};Descending=$true} | select Directory, Name, lastwritetime | Group-Object Name | %{$_.Group | Select -first 1}
gps programThatIsAnnoyingMe | kill
Open a file with its registered program (like start
e.g start foo.xls
)
ii foo.xls
Retrieves and displays the paths to the system's Special Folder's
[enum]::getvalues([system.environment+specialfolder]) | foreach {"$_ maps to " + [system.Environment]::GetFolderPath($_)}
Copy Environment value to clipboard (so now u know how to use clipboard!)
$env:appdata | % { [windows.forms.clipboard]::SetText($input) }
OR
ls | clip
With SnapIns
Files between two changeset numbers in TFS
Get-TfsItemHistory <location> -Recurse -Version <label1>~<label2> |
% { $(Get-TfsChangeset $_.ChangeSetID).Changes } |
% { $_.Item.ServerItem } | Sort-Object -Unique
Gets queue messages with errors over all Hub servers in exchange 200
Get-ExchangeServer | ?{$_.IsHubTransportServer -eq $true} | Get-Queue
| ?{$_.LastError -ne $null} | Sort-Object -Descending -Property MessageCount
| ft -Property NextHopDomain,@{l="Count";e={$_.MessageCount}},@{l="Last Try";e={$_.LastRetryTime.tosting("M/dd hh:mm")}},@{l="Retry";e={$_.NextRetryTime.tostring("M/dd hh:mm")}},Status,LastError -AutoSize
Upvotes: 19
Views: 11990
Reputation: 36688
I hesitate to enumerate my list of PowerShell one-liners one by one as the list numbers just about 400 entries at present! :-) But here are a few of my favorites, to pique your interest:
[accelerators]::get
[xml]"<root><a>...</a></root>"
$PWD | ConvertTo-Json -Depth 2
#cd
[System.Text.RegularExpressions.RegexOptions]::Singleline
ls . | select name,length | Out-ConsoleGraph -prop length -grid
The whole collection is publicly available in a 4-part series published on Simple-Talk.com -- I hope that these will be useful to SO readers!
I wanted to call the series "Do Anything in One Line of PowerShell" but my editor wanted something more terse, so we went with PowerShell One-Liners. Though in the interests of full disclosure, only 98% or so are really one-liners in the true spirit of the term; I thought that was close enough with rounding... :-)
Upvotes: 3
Reputation: 126
cls
Get rid of all the intractable, -verbose red marks after each of my attempted commands, letting me resume with a nice posh clear looking screen.
Upvotes: 1
Reputation: 881
Generate some pseudo random bytes in a file.
[Byte[]]$out=@(); 0..9 | %{$out += Get-Random -Minimum 0 -Maximum 255}; [System.IO.File]::WriteAllBytes("random",$out)
The Get-Random algorithm takes a seed from the system clock, so don't use this for serious cryptographic needs.
Upvotes: 1
Reputation: 1728
List all Windows Providers in alpha order:
get-winevent -listprovider microsoft-windows* | % {$_.Name} | sort
Actually you can use this with a wildcard for any specific group of Providers:
get-winevent -listprovider microsoft-windows-Securit* | % {$_.Name} | sort
Upvotes: 1
Reputation: 27818
Suppress Visual Studio 2012 ALL CAPS Menus - The very first thing I do after installing VS2012.
Set-ItemProperty -Path HKCU:\Software\Microsoft\VisualStudio\11.0\General -Name SuppressUppercaseConversion -Type DWord -Value 1
Thanks to Richard Banks who discovered the registry value.
Upvotes: 3
Reputation: 29450
List all the files that I've updated today:
dir | ?{$_.LastWriteTime -ge [DateTime]::Today}
Use it so often that I've actually created a little function in my profile:
function Where-UpdatedSince{
Param([DateTime]$date = [DateTime]::Today,
[switch]$before=$False)
Process
{
if (($_.LastWriteTime -ge $date) -xor $before)
{
Write-Output $_
}
}
}; set-item -path alias:wus -value Where-UpdatedSince
So I can say:
dir | wus
dir | wus "1/1/2009"
To see stuff updated before today:
dir | wus -before
Upvotes: 13
Reputation: 7400
Copy some to the desktop:
Copy-Item $home\*.txt ([Environment]::GetFolderPath("Desktop"))
Upvotes: 0
Reputation: 29449
I found it useful to show values of environment variables
dir env:
And you can copy an env value as well to the clipboard
$env:appdata | % { [windows.forms.clipboard]::SetText($input) }
(you need to have windows.forms loaded before the call: Add-Type –a system.windows.forms; and run PowerShell with -STA switch)
Upvotes: 3
Reputation: 44066
I don't like complicated applications for counting lines of code, especially because I consider it to be a bogus metric in the first place. I end up using a PS one-liner instead:
PS C:\Path> (dir -include *.cs,*.xaml -recurse | select-string .).Count
I just include the extensions of the files I want to include in the line count and go for it from the project's root directory.
Upvotes: 3
Reputation: 2291
Function display's System Uptime I use this for my accounting spreadsheet
function get-uptime
{
$PCounter = "System.Diagnostics.PerformanceCounter"
$counter = new-object $PCounter System,"System Up Time"
$value = $counter.NextValue()
$uptime = [System.TimeSpan]::FromSeconds($counter.NextValue())
"Uptime: $uptime"
"System Boot: " + ((get-date) - $uptime)
}
Upvotes: 0
Reputation: 3062
Gets queue messages with errors over all Hub servers in exchange 2007 (with some formatting)
Get-ExchangeServer | ?{$_.IsHubTransportServer -eq $true} | Get-Queue | ?{$_.LastError -ne $null} | Sort-Object -Descending -Property MessageCount | ft -Property NextHopDomain,@{l="Count";e={$_.MessageCount}},@{l="Last Try";e={$_.LastRetryTime.tosting("M/dd hh:mm")}},@{l="Retry";e={$_.NextRetryTime.tostring("M/dd hh:mm")}},Status,LastError -AutoSize
Upvotes: 0
Reputation: 1591
It may be cheating since I have the TFS PowerTools snap installed but this is quite useful for finding out which files have changed between two changesets, versions, or labels.
Get-TfsItemHistory <location> -Recurse -Version <label1>~<label2> |
% { $(Get-TfsChangeset $_.ChangeSetID).Changes } |
% { $_.Item.ServerItem } | Sort-Object -Unique
Upvotes: 2
Reputation: 2389
This shows which processes are using which versions of the MS CRT DLLs:
gps | select ProcessName -exp Modules -ea 0 |
where {$_.modulename -match 'msvc'} | sort ModuleName |
Format-Table ProcessName -GroupBy ModuleName
Upvotes: 2
Reputation:
($x=new-object xml).Load("http://rss.slashdot.org/Slashdot/slashdot");$x.RDF.item|?{$_.creator-ne"kdawson"}|fl descr*
My favorite: It's a slashdot reader sans the horrible submissions by mr. kdawson. It's designed to be fewer than 120 chars which allows it to be used as signature on /.
Upvotes: 4
Reputation: 496
Retrieves and displays the paths to the system's Special Folder's
[enum]::getvalues([system.environment+specialfolder]) | foreach {"$_ maps to " + [system.Environment]::GetFolderPath($_)}
Upvotes: 3
Reputation: 37720
Well, here is one I use often along with some explanation.
ii .
The ii is an alias for Invoke-Item. This commandlet essentially invokes whatever command is registered in windows for the following item. So this:
ii foo.xls
Would open foo.xls
in Excel (assuming you have Excel installed and .xls files are associated to Excel).
In ii .
the .
refers to the current working directory, so the command would cause windows explorer to open at the current directory.
Upvotes: 13
Reputation: 754565
My favorite powershell one liner
gps programThatIsAnnoyingMe | kill
Upvotes: 6