Results 1 to 6 of 6
  1. #1
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    6,415
    Thanks
    208
    Thanked 836 Times in 769 Posts

    PowerShell and SendTo

    Hey Y'all,

    Happy New Year!

    I'm experimenting with a PS Script to add to my SendTo context menu to send a file to my PDF printer. I've tested this script and it works from the command line. However When I try to place a shortcut in the SendTo menu I can't get it to pass the file parameter correctly.

    Here's the Target of the Shortcut:
    C:\WINDOWS\system32\WindowsPowerShell\v1.0\powersh ell.exe -File G:\BEKDocs\Scripts\SendToPDF.ps1 -FPFileName %1

    I've tried various combinations of quotes and such w/o any luck. Any Ideas?

    For those who might be interested here's my script:
    Code:
    param (
      [Parameter(Mandatory=$True)]
        [string]$FPFileName 
      )
    
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
    
    Function Show-Msg {
      Param ( [Parameter(Mandatory=$True, 
               HelpMessage="Message box content.")]
                [string]$Msg ,
              [Parameter(Mandatory=$False,
               HelpMessage="Message box title.")]
                [string]$Title = "Information"
            )          
    [Windows.Forms.MessageBox]::Show("$Msg", "$Title", 
         [Windows.Forms.MessageBoxButtons]::OK , 
         [Windows.Forms.MessageBoxIcon]::Information) 
    
    }  #End Function Show-Msg
    
    Clear-Host
    $DefaultPtr = Get-WMIObject -query `
      "Select * From Win32_Printer Where Name = 'Nitro PDF Creator (Reader 3)'"
    $DefaultPtr.SetDefaultPrinter()
    
    Start-Process -FilePath $FPFileName –Verb Print 
    
    $DefaultPtr = Get-WMIObject -query `
      "Select * From Win32_Printer Where Name = 'Brother HL-5370DW series Printer'"
    $DefaultPtr.SetDefaultPrinter()
    
    Show-Msg "$FPFileName.pdf Printed" "Completion Status"
    May the Forces of good computing be with you!

    RG

    VBA Rules!

    My Systems: Desktop Specs
    Laptop Specs


  2. #2
    4 Star Lounger access-mdb's Avatar
    Join Date
    Dec 2009
    Location
    Oxfordshire, UK
    Posts
    574
    Thanks
    52
    Thanked 42 Times in 39 Posts
    I don't know anything about Powershell, but would like to learn. However, does it have a debug feature like VBA has, so you can step into it and look at the contents of variables? I guess not as I assume you would have tried it! (Hey man, just saying)

  3. #3
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    6,415
    Thanks
    208
    Thanked 836 Times in 769 Posts
    Hey Y'all,

    Interestingly enough I found that this works as the Target of the Shortcut:
    C:\WINDOWS\system32\WindowsPowerShell\v1.0\powersh ell.exe -File G:\BEKDocs\Scripts\SendToPDF.ps1 -FPFileName

    By dropping the %1 entirely the SendTo shortcut appends the fully qualified filename to the end of the target.

    Now on to the next problem...you knew there had to be another one right?

    Well this now works fine with .txt files and Excel files but if I feed it a Word file it just sends it to the PRINTER! I even tried setting the Default printer to the PDF Printer BEFORE invoking the SendToPDF and it still went to the physical printer.

    I've also done a repair on my office installation to make sure all the file associations were correct and still no love with the Word files. As I watch the screen you can see it start Word and it just exits and sends it to the printer. Any Ideas?
    May the Forces of good computing be with you!

    RG

    VBA Rules!

    My Systems: Desktop Specs
    Laptop Specs


  4. #4
    Lounger
    Join Date
    May 2011
    Posts
    35
    Thanks
    0
    Thanked 1 Time in 1 Post
    Hello RG,

    I am no PowerShell expert and you may already have solved your problem, but don't you have to wait for the application doing the actual printing (Word in this case) to complete before you set the default printer back to the real, physical printer? I believe that Start-Process has a -Wait parameter for this, see http://technet.microsoft.com/en-us/l.../hh849848.aspx

    Regards,
    mo.eu

  5. #5
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    6,415
    Thanks
    208
    Thanked 836 Times in 769 Posts
    mo.eu,

    Right ON! Works like a charm. Funny it wasn't necessary for Excel files, must be a timing thing. Thanks.
    May the Forces of good computing be with you!

    RG

    VBA Rules!

    My Systems: Desktop Specs
    Laptop Specs


  6. #6
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    6,415
    Thanks
    208
    Thanked 836 Times in 769 Posts
    Hey Y'all,

    Just in case you're interested here's the final script with some new features:
    Code:
    <# +-------------------------------------------+
       | Program Name: SendToPDF.ps1               |
       | Programmed by: RetiredGeek                |
       | Created      : 12/31/2013                 |
       | Last Update  : 01/18/2014                 |
       | Version No.  : 1.3                        |
       +-------------------------------------------+
    
    Calling Shortcut Target:
    C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -File 
              G:\BEKDocs\Scripts\SendToPDF.ps1 -FPFileName
    
    Note 1: When the user clicks on a file in File Explorer the fully
            qualified d:\path\filename.ext will be appended to the Target
    Note 2: Shortcut is located in the Shell:SendTo folder so it is on the
            Right-Click menu in File Explorer!
    Note 3: This works with .txt, .csv files & Excel files but NOT Word Files!
    Note 4: Uses the script found here: http://poshcode.org/1837 to set the msgbox
            as the top most window so user doesn't miss the message.
            The file needs to be named TopMostWindow.ps1 or you need to change
            its dot sourcing call below!
    #>
    param (
      [Parameter(Mandatory=$True)]
        [string]$FPFileName 
      )
    
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
    
    #Dot Sourced file change filename only as appropriate!
    . ".\TopMostWindow.ps1"
    
    Function Show-Msg {
      Param ( [Parameter(Mandatory=$True, 
               HelpMessage="Message box content.")]
                [string]$Msg ,
              [Parameter(Mandatory=$False,
               HelpMessage="Message box title.")]
                [string]$Title = "Information"
            )          
    [Windows.Forms.MessageBox]::Show("$Msg", "$Title", 
         [Windows.Forms.MessageBoxButtons]::OK , 
         [Windows.Forms.MessageBoxIcon]::Information) 
    
    Get-WindowByTitle "$Title" | Set-TopMost
    
    }  #End Function Show-Msg
    
    Function Parse-Path {
    <# +----------------------------------------+
       | Function:        Parse-Path            |
       | Programmed by:                         |
       |    RetiredGeek@windowssecrets.com aka  |
       |    The Computer Mentor                 |
       | Current Version: 1.1                   |
       | Created:         01/05/2014            |
       | Updated:         01/19/2014            |
       +----------------------------------------+
    
    Notes: 
      1. returns a single dimensioned array with each segment
         of a fully qualified file reference in an element of
         the array with the 1st (zero element) containing the
         count of segments.
      2. One REQUIRED parameter, a fully qualified filespec.
      3. Upon return you can access fixed items via:
         Drive Letter: $Variable[1]
         Filename:     $Variable[$Variable[0]-1]
         Extension:    $Variable[$Variable[0]]
         Where: $Variable = your return value variable name.
      4. Note: If you wish to access these within a string use:
               $($Variable[$Variable[0]-1])
    #>
      Param ( [Parameter(Mandatory=$True)]
                [string]$TestPath 
            )          
    
      $Elements = New-Object 'object[]' 10
      $SegCnt = 0
      $PathRegX = [regex] "[0-9,A-Z,a-z,#,_, ,-]+|\|:"
      $Result = $PathRegX.match($TestPath)
     
      While ($Result.Success) {
           $Elements[++$SegCnt] = $Result.value
           $Result = $Result.nextmatch()
      }   #End While Loop
    
      $Elements[0] = $SegCnt
      Return $Elements
    
    }  #End Function Parse-Path
    
    Clear-Host
    
    $CurDir = Get-Location
    
    $PathSegs = Parse-Path -TestPath "$FPFileName"
    $NewFn = $PathSegs[$($PathSegs[0]-1)] + ".pdf"
    $NewPath = $PathSegs[1] + ":"  #Drive Letter
    
    # Assemble Path
    For ($Cnt = 2 ; $Cnt -le $($PathSegs[0]-2); $Cnt++) {
      $NewPath = "$NewPath" + "\" + $PathSegs[$($Cnt)] 
    }
    
    #Change default Path for PDF programs that write to default!
    Set-Location -Path "$NewPath"
    
    #Change Default printer to PDF printer
    $DefaultPtr = Get-WMIObject -query `
      "Select * From Win32_Printer Where Name = 'Nitro PDF Creator (Reader 3)'"
    [void] $DefaultPtr.SetDefaultPrinter()
    
    Start-Process -FilePath $FPFileName –Verb Print -Wait
    
    #Return Default Printer to previous value
    $DefaultPtr = Get-WMIObject -query `
      "Select * From Win32_Printer Where Name = 'Brother HL-5370DW series Printer'"
    [void] $DefaultPtr.SetDefaultPrinter()
    
    Set-Location -Path "$curdir"       #Reset default path
    Show-Msg "$NewFn Created" "Completion Status" > Null
    Get-WindowByTitle "Completion Status" | Set-TopMost -Disable
    I found an interesting thing while working on the path parsing function.
    This RegEx Does NOT work: $PathRegX = [regex] "[0-9,A-Z,a-z,#,_,-, ]+|\|:"
    This RegEx works: $PathRegX = [regex] "[0-9,A-Z,a-z,#,_, ,-]+|\|:"
    Notice the placement of the term for the - (dash). Using the 1 version the function would split the file name if it had a dash in it. Using the second syntax it behaves correctly. I hope this little piece of knowledge will save someone else the time it took me to figure it out.
    May the Forces of good computing be with you!

    RG

    VBA Rules!

    My Systems: Desktop Specs
    Laptop Specs


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •