Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Monday, January 9, 2012

Best Practice for PowerShell Functions

 

PowerTip of the Day, from PowerShell.com:

This is a best-practice message: when you create your own function, here are some things you should consider:

- Function name: use cmdlet naming syntax (Verb-Noun), and for verbs, stick to the list of approved verbs. For the noun part, use a meaningful English term, and use singular, not plural. So, don't call a function 'ListNetworkCards' but rather 'Get-NetworkCard'


- Company Prefix: To avoid name collisions, all public functions should use your very own noun-prefix. So don't call your function "Get-NetworkCard" because this generic name might be used elsewhere, too. Instead, pick a prefix for your company. If you work for, let's say, 'Global International', a prefix could be 'GI', and your function name would be "Get-GINetworkCard".


- Standard Parameter Names: Stick to meaningful standard parameter names. Don't call a parameter -PC. Instead, call it


-ComputerName. Don't call it -File. Instead, call it -Path. While there is no official list of approved parameter names, you should get familiar with the parameter names used by the built-in cmdlets to get a feeling for it.

 

Thanks

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.

Sending Text to Clipboard Everywhere using Powershell

In a previous tip you learned how to use clip.exe to send results to the clipboard. But what if you don't have clip.exe (let's say on Windows XP) or don't want dependencies?

Here's a clever alternative:

function Out-Clipboard {

 param(

  $text

 )

 Add-Type -AssemblyName System.Windows.Forms

 $tb = New-Object System.Windows.Forms.TextBox

 $tb.Multiline = $true

     

 if ($Input -ne $null) {

  $Input.Reset()

  $tb.Text = $Input | Out-String

 } else {

  $tb.Text = $text

 }

 $tb.SelectAll()

 $tb.Copy()

}

Use it like this:

PS> Get-Process | Out-Clipboard

It solely uses .NET Framework functionality that is available in all versions and modes of PowerShell

Reading the Clipboard using Powershell

 

PowerTip of the Day, from PowerShell.com:

 

What if you wanted to paste information from the clipboard? No sweat, here is a Get-Clipboard function that outputs any text held by the clipboard:

function Get-Clipboard {

 Add-Type -AssemblyName System.Windows.Forms

 $tb = New-Object System.Windows.Forms.TextBox

 $tb.Multiline = $true

 $tb.Paste()

 $tb.Text

}

In a previous tip we presented the corresponding Out-Clipboard function, so now you could send information to the clipboard in one PowerShell session and read it back from another.

Thanks

Aman

Bulk-Creating PDF Files from Word

 

PowerTip of the Day, from PowerShell.com:

 

To convert a whole folder full of MS Word documents to PDF, here's a function that might help:

function Export-WordToPDF {

  param(

  [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]

  [Alias("FullName")]

  $path,

  $pdfpath = $null)

  process {

    if (!$pdfpath) {

      $pdfpath = [System.IO.Path]::ChangeExtension($path, '.pdf')

    }

    $word = New-Object -ComObject Word.Application

    $word.displayAlerts = $false

   

    $word.Visible = $true

    $doc = $word.Documents.Open($path)

    #$doc.TrackRevisions = $false

    $null = $word.ActiveDocument.ExportAsFixedFormat($pdfpath, 17, $false, 1)

    $word.ActiveDocument.Close()

    $word.Quit()

  }

}

Use it like this:

PS> Dir c:\folder -Filter *.doc | Export-WordToPDF

Thanks

Creating Your Own Get-Driver Tool using PowerShell

 

PowerTip of the Day, from PowerShell.com:

 

Creating Your Own Get-Driver Tool

Some code snippets are really valuable, so you should turn them into functions to keep around as new PowerShell commands. Here's a sample function:

function Get-Driver {

  param(

    $Keyword = '*'

  )

  $col1 = @{Name='File Name'; Expression={ Split-Path $_.Path -Leaf } }

  driverquery.exe /v /FO CSV |

    ConvertFrom-CSV |

    Select-Object 'Display Name',  'Start Mode', 'Paged Pool(bytes)', $col1 |

    Where-Object { ($_ | Out-String -Width 300) -like "*$Keyword*" }

}

You now have a function called Get-Driver which lists you all drivers. With just one parameter, you can also easily filter the driver list:

PS> Get-Driver mount

 

Display Name                     Start Mode          Paged Pool(bytes)          File Name

------------                     ----------          -----------------      ---------

Mount Point Manager Boot                         65.536                                         mountmgr.sys

WIMMount                                Manual                    4.096                                           wimmount.sys

 

 

PS> Get-Driver disable

 

Display Name                     Start Mode          Paged Pool(bytes)            File Name

------------                     ----------          -----------------            ---------

CD/DVD File Syst... Disabled               69.632                                         cdfs.sys

Crcdisk filter D... Disabled               4.096                                            crcdisk.sys

udfs                                           Disabled              180.224                                       udfs.sys

Winsock IFS Driver      Disabled              12.288                                          ws2ifsl.sys

It is a grep-like filter feature which returns all drivers that have your keyword in one of its properties.

 

Thanks

Tuesday, November 22, 2011

Outputting Text Reports without Truncating

 

PowerTip of the Day, from PowerShell.com:

If you want to capture PowerShell results in a text file, you can redirect the results or pipe them to Out-File. In any case, what you capture is the exact representation of what would have been displayed in your PowerShell console. So, depending on the amount of data, columns may be missing or truncated.
Here is a function called Out-Report. You can pipe any result to it to create a text file that does not truncate columns. In addition, with the –Open switch parameter, you can open the resulting text file, too:
   1: function Out-Report {
   2:  
   3:  param(
   4:  
   5:   $Path = "$env:temp\report.txt",
   6:  
   7:   [switch]$Open
   8:  
   9:  )
  10:  
  11:  
  12:  
  13:  $Input |
  14:  
  15:   Format-Table -AutoSize |
  16:  
  17:   Out-File $Path -Width 10000
  18:  
  19:  
  20:  
  21:   if($Open) { Invoke-Item $Path }
  22:  
  23: }

Try it:

Get-Process | Out-Report -Open

Thanks

Aman