studiojanck ([info]studiojanck) wrote,
@ 2009-10-21 08:58:00
Previous Entry  Add to memories!  Tell a Friend  Next Entry
Entry tags:alias, cmdlet, filter, include, module, powershell, script

Cog's PowerShell Corner
I've been getting into PowerShell recently. It's awesome. But sometimes it doesn't seem to have all the functions that one would want. So I made my own. I've decided to dust off the ol' blog to tell you about how awesome I am some of the more useful functions. There's no guarantee that these won't malfunction when used in extreme ways (a pipe in a ForEach-Object in a pipe in a function), but there you go.

Dual Filter


(PowerShell 2.0 CTP 1 only, as far as I can tell)
Will automatically generate a Cmdlet from a script block. It's an easy way to make a filter that doubles as a function, or a function that accepts pipeline input. It all depends on how you look at it.

Code:
function DualFilter ([string]$name, [string]$params, [scriptblock]$filter)
{
  if ($params -ne "") {$params = ", $params"}
  $params = "param( [ValueFromPipeline][object]`$_ $params )"
  invoke-expression "cmdlet global:$name {$params process {$filter}}"
}


It can then be used like so:
DualFilter Write-Colored '[ConsoleColor]$color' {
  Write-Host $_ -foregroundcolor $color
}

Note that the opening brace must be on the same line as the DualFilter statement.

Including Scripts


With the advent of "Modules" in PowerShell 2.0 CTP 2, this may not be necessary for much longer.

Code:
function include ([string]$path)
{
  get-item "$path.ps1" | foreach-object {. $_.FullName}
}


Usage:
. include "c:\ps\*"

Scripts can be included by an absolute path or by wildcard. The ".ps1" extension should be omitted.

Tip of the Day


You can make an alias for a script file by writing Set-Alias <name> <path>



Create an Account
Forgot your login or password?
Login w/ OpenID
English • Español • Deutsch • Русский…