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

Community
  • 1
  • 1
Binoj Antony
  • 15,886
  • 25
  • 88
  • 96
  • Polls should be Community WIKIs – JaredPar Mar 05 '09 at 15:36
  • 1
    And typically don't belong on SO anyway. – EBGreen Mar 05 '09 at 15:41
  • 1
    @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. – Joel Coehoorn Mar 05 '09 at 15:47
  • 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. – EBGreen Mar 05 '09 at 15:55
  • 2
    Yuck. Not a question. Stuff like this should go on http://wiki.poshcode.org or something – Jaykul Jun 01 '09 at 16:35
  • 4
    Just because you put A LOT of crap on one line does not really make it a one-liner. – Seb Nilsson Dec 18 '09 at 13:12

19 Answers19

21

At about 6:00 PM....

exit
Josh
  • 68,005
  • 14
  • 144
  • 156
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.

Jay Bazuzi
  • 45,157
  • 15
  • 111
  • 168
EBGreen
  • 36,735
  • 12
  • 65
  • 85
  • 3
    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. – Christian Witts Mar 05 '09 at 17:00
  • I usually do this using `start .`, `start myFile.xls`, or `start "" "My File.xls"`. How is Invoke-Item superior to the normal start command? – Hosam Aly Mar 05 '09 at 17:14
  • @Hosam, you use start myfile.xls in powershell? – EBGreen Mar 05 '09 at 17:53
  • @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 . – EBGreen Mar 05 '09 at 17:56
  • Nice! I had created a script that would do the same through the Shell.Application object, but that's a lot simpler! – zdan Mar 05 '09 at 20:16
  • @EBGreen: No, I use it in CMD, but wouldn't it work in PowerShell? – Hosam Aly Mar 07 '09 at 06:43
  • EB, I can fraps it if you like ;) – Christian Witts Mar 07 '09 at 13:03
  • @Christian, Please do. Then post to explain how and why you changed this basic functionality of powershell. – EBGreen Mar 07 '09 at 13:47
  • @EBGreen: Then please accept my apology. I used to think that all CMD commands were available in PowerShell. I was clearly wrong. – Hosam Aly Mar 07 '09 at 13:50
  • 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. – EBGreen Mar 07 '09 at 14:03
  • @EBGreen: start only exists in V2, persionally I created my own function for V1 – JasonMArcher Mar 24 '09 at 22:16
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
zdan
  • 28,667
  • 7
  • 60
  • 71
  • It makes better sense to declare `Where-UpdatedSince` as a function. Also `-before` parameter could be `[switch]`. – stej Apr 04 '10 at 22:22
  • @stej - 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. – zdan Apr 05 '10 at 20:05
  • I ment 'filter', not 'function' :) I just added comment to keep it up to date - for anybody comming along and reading your post. – stej Apr 06 '10 at 06:30
6

My favorite powershell one liner

gps programThatIsAnnoyingMe | kill
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
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 /.

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.

Community
  • 1
  • 1
C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91
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.

Greg D
  • 43,259
  • 14
  • 84
  • 117
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... :-)

Laurel
  • 5,965
  • 14
  • 31
  • 57
Michael Sorens
  • 35,361
  • 26
  • 116
  • 172
3

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

[enum]::getvalues([system.environment+specialfolder]) | foreach {"$_ maps to " + [system.Environment]::GetFolderPath($_)}
EdgeVB
  • 486
  • 2
  • 5
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)

stej
  • 28,745
  • 11
  • 71
  • 104
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
Keith Hill
  • 2,329
  • 1
  • 19
  • 7
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
Damien Ryan
  • 1,591
  • 1
  • 15
  • 34
1

pipe the output of something to the clipboard

ls | clip
Jason Jarrett
  • 3,857
  • 1
  • 27
  • 28
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.

Gerrit
  • 861
  • 6
  • 11
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.

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
jscott
  • 871
  • 1
  • 9
  • 18
rferrisx
  • 1,598
  • 2
  • 12
  • 14
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)
}
icnivad
  • 2,231
  • 8
  • 29
  • 35
  • 2
    In V2 there is easier way how to read performance counters: `Get-Counter System,"System Up Time"`. – stej Apr 04 '10 at 22:31
0

Copy some to the desktop:

Copy-Item $home\*.txt ([Environment]::GetFolderPath("Desktop"))
Kb.
  • 7,240
  • 13
  • 56
  • 75
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        
slipsec
  • 3,004
  • 3
  • 34
  • 46