Monday, January 9, 2012

Creating a "Better" More in PowerShell

 

PowerTip of the Day, from PowerShell.com:

 

In a previous tip you learned that using "more" to paginate output can be dangerous, and instead you should use Out-Host -Paging. To "update" more.com and make it behave like Out-Host with the -Paging parameter set, use a proxy function like this one:

function more {

 param(

 [Parameter(ValueFromPipeline=$true)]

 [System.Management.Automation.PSObject]

 $InputObject

 )

 

 begin

 {

  $type = [System.Management.Automation.CommandTypes]::Cmdlet

  $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Out-Host', $type)

  $scriptCmd = {& $wrappedCmd @PSBoundParameters -Paging }

  $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)

  $steppablePipeline.Begin($PSCmdlet)

 }

 process { $steppablePipeline.Process($_) }

 end { $steppablePipeline.End() }

#.ForwardHelpTargetName Out-Host

#.ForwardHelpCategory Cmdlet

}

Once you run it, whenever you use "more", behind the scenes PowerShell will now call "Out-Host -Paging" instead. That's why now, with the new "more" in place, you can safely use lines like this:

PS> Get-EventLog -LogName System | more

Note that your new "more" now works anywhere. The built-in "help" function, for example, also uses the outdated "more.com" and now will work faster, too.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.