Blogroll

Search

Print-File Function

November 10th, 2009 by Karl

Here is a simple function that will ask the associated program to print any file you pass in. It can work with a file as a parameter, or multiple files. How well this works, especially with multiple files at a time, depends on the associated application, first whether it supports the print verb, and secondly how it handles it – more importantly how it handles opening many files at once. I haven’t yet been brave enough to try it on PDFs with adobe reader.

function print-file($file)
{
 begin  {
    function internal-printfile($thefile)
    {
        if ($thefile -is [string]) {$filename = $thefile }
        else {
                if ($thefile.FullName -is [string] ) { $filename = $THEfile.FullName }
             }
        $start = new-object System.Diagnostics.ProcessStartInfo $filename
        $start.Verb = "print"
        [System.Diagnostics.Process]::Start($start)
    } 

if ($file -ne $null) {
                $filespecified = $true;
                internal-printfile $file
            }
       }
process{if (!$filespecified) { write-Host process ; internal-printfile $_ } } 

}

@poshcode | download

Here you can pass in a path to the file , or a fileobject that you get as a response from get-childitem (dir)

Here are a few examples

#look recursively through a folder and print all word documents
dir *.doc -r | print-file 

#print one particular pdf file
print-file c:\downloads\myfile.pdf

Warning, this isn’t up to being a shrink wrapped deliverable. It doesn’t do any error handling, isn’t a nice V2 advanced function or anything, but that’s a beauty of PowerShell, you can just hack out something that fits your needs in a few minutes. With V2 parameter binding, this would be more elegant and actually simpler as i have to do some duplication of logic in my function to get it to work accepting the file both through the pipeline and as a parameter.

-Enjoy.

Posted in PSV2, Powershell, script | 2 Comments »