views:

2452

answers:

13

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
  1. Retrieves and displays the paths to the system's Special Folder's

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

  2. Copy Environment value to clipboard (so now u know how to use clipboard!)

    $env:appdata | % { [windows.forms.clipboard]::SetText($input) }

With SnapIns

  1. Files between two changeset numbers in TFS

    Get-TfsItemHistory -Recurse -Version ~ | % { $(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

+5  A: 

My favorite powershell one liner

gps programThatIsAnnoyingMe | kill
JaredPar
+8  A: 

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.

EBGreen
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
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
@Hosam, you use start myfile.xls in powershell?
EBGreen
@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
Nice! I had created a script that would do the same through the Shell.Application object, but that's a lot simpler!
zdan
@EBGreen: No, I use it in CMD, but wouldn't it work in PowerShell?
Hosam Aly
EB, I can fraps it if you like ;)
Christian Witts
@Hosam, No it wouldn't.
EBGreen
@Christian, Please do. Then post to explain how and why you changed this basic functionality of powershell.
EBGreen
@EBGreen: Then please accept my apology. I used to think that all CMD commands were available in PowerShell. I was clearly wrong.
Hosam Aly
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
@EBGreen: start only exists in V2, persionally I created my own function for V1
JasonMArcher
+8  A: 

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
It makes better sense to declare `Where-UpdatedSince` as a function. Also `-before` parameter could be `[switch]`.
stej
@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
@zdan I ment 'filter', not 'function' :) I just added comment to keep it up to date - for anybody comming along and reading your post.
stej
+3  A: 

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

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

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
+1  A: 

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
+2  A: 

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
+1  A: 

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
+7  A: 

At about 6:00 PM....

exit
Josh Einstein
ha ha ha ha ha!
Binoj Antony
A: 

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
In V2 there is easier way how to read performance counters: `Get-Counter System,"System Up Time"`.
stej
+1  A: 

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
A: 

Copy some to the desktop:

Copy-Item $home\*.txt ([Environment]::GetFolderPath("Desktop"))
Kb