Useful PowerShell one liners
Asked Answered
M

19

19

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.

  1. 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}

  2. gps programThatIsAnnoyingMe | kill

  3. Open a file with its registered program (like start e.g start foo.xls)

    ii foo.xls

  4. Retrieves and displays the paths to the system's Special Folder's

    [enum]::getvalues([system.environment+specialfolder]) | foreach {"$_ maps to " + [system.Environment]::GetFolderPath($_)}

  5. 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

  1. Files between two changeset numbers in TFS

    Get-TfsItemHistory <location> -Recurse -Version <label1>~<label2> | % { $(Get-TfsChangeset $_.ChangeSetID).Changes } | % { $_.Item.ServerItem } | Sort-Object -Unique

  2. 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

Marlie answered 5/3, 2009 at 15:33 Comment(6)
Polls should be Community WIKIsBenbena
And typically don't belong on SO anyway.Onfre
@EBGreen: often no, they don't. I think this one is pretty good, though (if we clear up the wording some). It can server as a good PS introduction.Agricola
I agree that this particular poll might fit better tan most. To be honest though, I think a group of one liners would be a terrible introduction to PS. There will be all kinds of aliases and assumed knowledge involved. For instance one of my favorites is "ii." no way that would help a beginner.Onfre
Yuck. Not a question. Stuff like this should go on wiki.poshcode.org or somethingPoverty
Just because you put A LOT of crap on one line does not really make it a one-liner.Broadspectrum
L
21

At about 6:00 PM....

exit
Laspisa answered 5/3, 2009 at 15:33 Comment(0)
O
13

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.

Onfre answered 5/3, 2009 at 16:33 Comment(11)
You can do that in a normal prompt, just type foo.xls and it will start Excel/OpenOffice/Whatever you have associated. Type Explorer and it will start a windows explorer session at that location.Crapshooter
I usually do this using start ., start myFile.xls, or start "" "My File.xls". How is Invoke-Item superior to the normal start command?Cathrin
@Hosam, you use start myfile.xls in powershell?Onfre
@Christian, to be pedantically correct, typing foo.xls will not work, you would have to type .\foo.xls. Also, you are correct that typing Explorer will work, but that is 8 characters compared to the 4 characters of ii .Onfre
Nice! I had created a script that would do the same through the Shell.Application object, but that's a lot simpler!Leesaleese
@EBGreen: No, I use it in CMD, but wouldn't it work in PowerShell?Cathrin
EB, I can fraps it if you like ;)Crapshooter
@Christian, Please do. Then post to explain how and why you changed this basic functionality of powershell.Onfre
@EBGreen: Then please accept my apology. I used to think that all CMD commands were available in PowerShell. I was clearly wrong.Cathrin
There are some aliases to give you essentially the same functionality but not all of the commands are covered. Start in PS is an alias for Start-Process. a .xls file is not an exe so it will fail.Onfre
@EBGreen: start only exists in V2, persionally I created my own function for V1Toothlike
L
13

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
Leesaleese answered 5/3, 2009 at 20:30 Comment(3)
It makes better sense to declare Where-UpdatedSince as a function. Also -before parameter could be [switch].Beast
@Beast - Where-UpdatedSince is a function. I've update the -before parameter to a switch. That wasn't around in PS v1 when I originally wrote this.Leesaleese
I ment 'filter', not 'function' :) I just added comment to keep it up to date - for anybody comming along and reading your post.Beast
B
6

My favorite powershell one liner

gps programThatIsAnnoyingMe | kill
Benbena answered 5/3, 2009 at 15:33 Comment(0)
I
4
($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 /.

Intrusion answered 5/3, 2009 at 15:33 Comment(0)
S
3

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:

  • List all type accelerators (requires PSCX): [accelerators]::get
  • Convert a string representation of XML to actual XML: [xml]"<root><a>...</a></root>"
  • Dump an object (increase depth for more detail): $PWD | ConvertTo-Json -Depth 2
  • Recall command from history by substring (looking up earlier 'cd' cmd): #cd
  • Access C# enum value: [System.Text.RegularExpressions.RegexOptions]::Singleline
  • Generate bar chart (requires Jeff Hicks' cmdlet): 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... :-)

Salas answered 5/3, 2009 at 15:33 Comment(1)
Awesome article @Michael, it is a one stop reference for everything PowerShell!Marlie
C
3

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.

Condenser answered 5/3, 2009 at 15:33 Comment(0)
O
3

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.

Orphism answered 5/3, 2009 at 15:33 Comment(1)
I usually do (gci -r -inc *.cs,*.xaml|gc)-ne''|measureSorrel
B
3

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)

Beast answered 5/3, 2009 at 15:33 Comment(0)
G
3

Retrieves and displays the paths to the system's Special Folder's

[enum]::getvalues([system.environment+specialfolder]) | foreach {"$_ maps to " + [system.Environment]::GetFolderPath($_)}
Guam answered 5/3, 2009 at 15:33 Comment(0)
W
2

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
Wrest answered 5/3, 2009 at 15:33 Comment(0)
V
2

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
Vaisya answered 5/3, 2009 at 15:33 Comment(0)
A
1
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.

Antipathy answered 5/3, 2009 at 15:33 Comment(0)
F
1

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.

Fealty answered 5/3, 2009 at 15:33 Comment(0)
B
1

pipe the output of something to the clipboard

ls | clip
Biernat answered 5/3, 2009 at 15:33 Comment(0)
L
1

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
Loyceloyd answered 5/3, 2009 at 15:33 Comment(0)
L
0

Copy some to the desktop:

Copy-Item $home\*.txt ([Environment]::GetFolderPath("Desktop"))
Lettyletup answered 5/3, 2009 at 15:33 Comment(0)
P
0

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)
}
Pourboire answered 5/3, 2009 at 15:33 Comment(1)
In V2 there is easier way how to read performance counters: Get-Counter System,"System Up Time".Beast
C
0

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        
Charmion answered 5/3, 2009 at 15:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.