Monday, January 9, 2012

Spying on Parameters in Powershell

 

PowerTip of the Day, from PowerShell.com:

 

Your own PowerShell functions can have the same sophisticated parameters, parameter types and parameter sets that you know from cmdlets. However, it is not always obvious how to construct the param() block appropriately.

A clever way is to spy on cmdlets and look how they did it. For example, if you wonder how Get-EventLog made its -LogName parameter mandatory, check out its param() block:

PS> $cmd = Get-Command -commandType cmdlet Get-EventLog

PS> [System.Management.Automation.ProxyCommand]::GetParamBlock($cmd)

 

    [Parameter(ParameterSetName='LogName', Mandatory=$true, Position=0)]

    [Alias('LN')]

    [System.String]

    ${LogName},

 

    [Alias('Cn')]

    [ValidateNotNullOrEmpty()]

    [System.String[]]

    ${ComputerName},

 

    [Parameter(ParameterSetName='LogName')]

    [ValidateRange(0, 2147483647)]

    [System.Int32]

    ${Newest},

(...)

Not only will you discover that the keyword Mandatory=$true made -LogName mandatory. You also see all the hidden parameter aliases as well as validator attributes. The parameter -Newest for example will only accept a range between 0 and 2147483647, and your own parameters could do the same now, too

Thanks

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

Retrieve Exchange Rates using PowerShell

 

PowerTip of the Day, from PowerShell.com:

If you need up-to-date exchange rates, try loading the rates via XML from the European Central Bank. This sample gets you the latest exchange rates for USD-EUR conversion. It also has a link to other currency data. Just exchange the data link. We included a sample for Danish currency as well.

#Exchangerate feeds : http://www.ecb.int/home/html/rss.en.html

$url = 'http://www.ecb.int/rss/fxref-usd.html'

#$url = 'http://www.ecb.int/rss/fxref-dkk.html'

$xml = New-Object xml

$xml.Load($url)

$xml.RDF.Item |

      ForEach-Object {

            $rv = 1 | Select-Object Date, Currency, Rate, Description

            $rv.Date = [DateTime]$_.Date

            $rv.Description = $_.description.'#text'

            $rv.Currency = $_.statistics.exchangeRate.targetCurrency

            $rv.rate = $_.statistics.exchangeRate.value.'#text'

            $rv

      }

And this is what the output looks like (provided you have Internet access and no proxy is required):

Date                                          Currency Rate       Description

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

01.12.2011 14:15:00 USD               1.3492 1 EUR buys 1.3492 US dollar (USD) - The
...

30.11.2011 14:15:00 USD               1.3418 1 EUR buys 1.3418 US dollar (USD) - The
...

29.11.2011 14:15:00 USD               1.3336 1 EUR buys 1.3336 US dollar (USD) - The
...

28.11.2011 14:15:00 USD               1.3348 1 EUR buys 1.3348 US dollar (USD) - The
...

25.11.2011 14:15:00 USD               1.3229 1 EUR buys 1.3229 US dollar (USD) - The
...

 

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

Finding More Driver Information using PowerShell

 

PowerTip of the Day, from PowerShell.com:

 

Finding More Driver Information

In a previous tip you learned how you can convert raw CSV data from a console application such as driverquery.exe into real PS objects. Let's play some more.

Since the CSV data only returns the complete path to a driver (which is too long to display without being truncated), let's add a "calculated property". That's a hash table with two keys: Name and Expression.

The script block in Expression takes the long path name and extracts just the file name. Now we get valuable driver information that - due to its object nature - can easily be sorted as well:

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

PS> driverquery.exe /v /FO CSV | ConvertFrom-CSV | Select-Object 'Display Name',

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

 

Display Name                   Start Mode                            Paged Pool(bytes   File Name

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

ACPI-Energieanze... Manual                                    4.096                                         acpipmi.sys

adp94xx                                   Manual                                    0                                                   adp94xx.sys

adpahci                                   Manual                                    0                                                   adpahci.sys

adpu320                                   Manual                                    0                                                   adpu320.sys

Agere Systems So... Manual                                    20.480                                    agrsm64.sys

aliide                                     Manual                                    0                                                   aliide.sys

AMD K8 Processor... Manual                                    28.672                                     amdk8.sys

AMD Processor Dr... Manual                                    28.672                                     amdppm.sys

amdide                                     Manual                                    0                                                   amdide.sys

amdsata                                  Manual                                    0                                                   amdsata.sys

(...)

 

Thanks