How to use PowerShell to switch default app (from pre-determined list)

Page 1 of 2 12 LastLast

  1. Posts : 61
    10
       #1

    How to use PowerShell to switch default app (from pre-determined list)


    How to use PowerShell to switch default app (from pre-determined list) for a given file type? Windows 10
    I frequently switch App to open PDFs and wish for shortcut. Without Admin Right, can PowerShell Script change default App from pre-determined list:
    1. Open PowerShell Window
    2. Show current Default
    3. Press Enter if OK
    4. Press Spacebar (non-graphical interface) to show next App in List
    5. Press Enter to change Default
    6. Above Script to show in Windows 10 Taskbar
    As-Is, because Word is my only Enterprise Translation tool for PDF, it is very cumbersome for Word (when not default App) to open PDF.
    Solutions that require Admin Rights
    1. Set default app for .PDF file extension to Adobe or Edge? powershell - Set default app for .PDF file extension to Adobe or Edge? - Super User
    2. How to Set Default Apps on Windows 10 with a script? batch - How to Set Default Apps on Windows 10 with a script? - Super User
    3. How to Export and Import Custom Default App Associations for New Users in Windows 10 Export and Import Default App Associations for New Users in Windows
      My Computer


  2. Posts : 1,749
    Windows 10 Pro (+ Windows 10 Home VMs for testing)
       #2

    Wouldn't it just be easier to have your different PDF apps as options in the 'Open with' right-click context menu to save all the messing about with scripting? Then you could just right-click on a PDF file in File Explorer and make your choice.

    There's several free context menu editors out there to make things easier. For example, have a look at 15 Best Context Menu Editors For Windows 10, 11 in 2023.

    One that I've used several times and which is often recommended here is sordum.org's Easy Context Menu.

    Hope this helps.
      My Computer


  3. Posts : 42,890
    Win 10 Pro (22H2) (2nd PC is 22H2)
       #3

    If you wished to quickly open a pdf with a different program than the default, you could have shortcuts to all your different pdf viewers in the Sendto folder, then simply

    right click your pdf, hover briefly over Send to, then click on the pdf viewer you wish to use.

    To access the Sendto folder:
    Press the Windows Key + R to trigger the Run window. At the Open field in the window, type shell:SendTo and then click OK. File Explorer opens to the SendTo folder for your user account
      My Computers


  4. Posts : 1,749
    Windows 10 Pro (+ Windows 10 Home VMs for testing)
       #4

    dalchina said:
    If you wished to quickly open a pdf with a different program than the default, you could have shortcuts to all your different pdf viewers in the Sendto folder, then simply right click your pdf, hover briefly over Send to, then click on the pdf viewer you wish to use.
    That's an even quicker and better solution than my suggestion.
      My Computer


  5. Posts : 61
    10
    Thread Starter
       #5

    When Word has following limitation with PDF
    1. when not set as default App for PDF
    2. does not show PDF it exported
    3. cannot Open PDF navigated by Recent Items
    I am using PowerShell Script to have Word open most recent PDF; I need help how to modify following script to bring Window (opened PDF) to the frontmost - as would be activated if alt-tabbed to the application.
    Code:
    $PDF = "2023-04-27\To Translate\Staging\Otis Gen2Core with Ultra Drive ACD3 & UD\Screenshot\P1. MS Export.pdf"
    $desktop_path = [Environment]::GetFolderPath("Desktop")
    $latestPDF = Get-ChildItem -Attributes !Directory *.pdf | Sort-Object -Descending -Property LastWriteTime | select -First 1
    $word = New-Object -ComObject word.application
    $word.Visible = $true
    $fullpath = Join-Path -Path $desktop_path -ChildPath $PDF
    $doc = $word.Documents.Open("$latestPDF")
    $hwnd = $doc.ActiveWindow.Hwnd
    [Void]$User32::SetWindowPos($hwnd, -1, 0, 0, 0, 0, 0x53)
    <#
    https://superuser.com/questions/1784845/how-to-make-the-word-open-dialog-visible-and-frontmost
    https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-show-documents-not-yet-opened-and-saved/1937da76-8b06-4681-82b6-d6042c344754
    https://support.microsoft.com/en-us/office/command-line-switches-for-microsoft-office-products-079164cd-4ef5-4178-b235-441737deb3a6
    https://answers.microsoft.com/en-us/msoffice/forum/all/for-translating-pdf-how-to-open-pdf-in-recent/0ab3a6dd-53d5-423f-97ae-ea41eb2530a5
    <#
    <#
    $latestfile = Get-ChildItem -Attributes !Directory . | Sort-Object -Descending -Property LastWriteTime | select -First 1
    $word.visible = $true
    $workbook = $word.open
    # $doc = $word.Documents.Open("$desktop_path" + "$PDF") - need to add slash
    #>
    <#
    cmd - Run command with drag and drop onto batch file - Stack Overflow
    https://superuser.com/questions/1419800/how-a-running-application-can-be-set-as-active-window-via-powershell
    https://stackoverflow.com/questions/51985708/correct-way-to-bring-window-to-foreground
    https://www.thecodebuzz.com/powershell-get-most-recent-file-in-directory-folder/#:~:text=PowerShell-%20Get%20the%20most%20recent%20file%20in%20Directory,%7C%20select%20-First%201%20PS%20C%3ATest%3E%20%24latestfile.Name%20TheCodeBuzz.png
    https://stackoverflow.com/questions/52074362/how-to-connect-powershell-script-to-an-already-opened-document
    https://stackoverflow.com/questions/76275880/how-run-excel-command-lines-from-batch-file
    #>
      My Computer


  6. Posts : 759
    Windows 7
       #6

    I solved your problem using a different approach:

    1. Open the Recent Folder, and look for the last opened *.pdf filename.
    2. Set DisableConvertPDFWarning reg value = 1, if needed.
    3. Run Word using the normal window size, and open the PDF file.
    4. Wait until conversion (file open) is done, then resize Word to full screen and set to foreground.

    Code:
    Add-Type @"
        using System;
        using System.Runtime.InteropServices;
        public class WinAp {
            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool SetForegroundWindow(IntPtr hWnd);
        }
    "@
    
    $objShell = New-Object -ComObject WScript.Shell
    
    $Last_PDF = (Get-ChildItem $env:APPDATA\Microsoft\Windows\Recent -Filter *.lnk | Sort-Object LastAccessTime -Descending |`
        ForEach-Object {
            $Target = $objShell.CreateShortcut($_.FullName).TargetPath
    
            if ($Target -match ".pdf$") { $Target }
        } | select -First 1)
    
    if ($Last_PDF -eq $null) {
        exit
    }
    
    $objWord = New-Object -ComObject Word.Application
    $objWord.Visible = $true
    $objWord.WindowState = "wdWindowStateNormal"
    
    $Version = $objWord.Version
    $RegPath = "HKCU:\SOFTWARE\Microsoft\Office\$Version\Word\Options"
    
    if ((Get-ItemPropertyValue -Path $RegPath -Name DisableConvertPDFWarning -ErrorAction Ignore) -eq 0) {
        $null = New-ItemProperty -Path $RegPath -Name DisableConvertPDFWarning -Value 1 -PropertyType DWORD -Force
    }
    
    $def = [Type]::Missing
    $Doc = $objWord.Documents.Open($Last_PDF, $false, $def, $false)
    $objWord.WindowState = "wdWindowStateMaximize"
    
    $Proc = Get-Process | where { $_.ProcessName -match "WINWORD" }
    
    $hwnd = $Proc.MainWindowHandle
    [void][WinAp]::SetForegroundWindow($hwnd)

    Note: You will get a locked file error if you run the script twice in a row, and end up opening the same PDF file. I hope this is what you wanted. None of this requires any admin privileges.
      My Computer


  7. Posts : 61
    10
    Thread Starter
       #7

    Thanks, but I need further help because $Last_PDF returns file name that is not shown in File Explorer Recent;
    Word reports no such file.
    PS C:\Users\ThisUser\OneDrive - ThisCompany\Desktop> $Last_PDF
    C:\Users\ThisUserOneDrive - ThisCompany\Desktop\2023-04-27\To Translate\Staging\Otis Gen2Core with Ultra Drive ACD3 & UD\Screenshot\Color\B&W\2023-06-05\B&W A3.pdf
    How to use PowerShell to switch default app (from pre-determined list)-powershell-script-open-recent-pdf-word-fails-2023-06-06-110355.gif
      My Computer


  8. Posts : 759
    Windows 7
       #8

    When you say "most recent" PDF, which one is it?
    - Most recent *.pdf in Recent folder? Do you delete any PDF? The current sort order is by last opened, do you need the last written PDF?
    - Most recent PDF opened by Word?
    - Most recent PDF opened by Adobe?
      My Computer


  9. Posts : 61
    10
    Thread Starter
       #9

    Recent Items in File Explorer


    I need help to return last PDF in Recent Items of File Explorer
    Code:
    (Get-ChildItem $env:APPDATA\Microsoft\Windows\Recent -Filter *.lnk | Sort-Object LastAccessTime -Descending |`
        ForEach-Object {
            $Target = $objShell.CreateShortcut($_.FullName).TargetPath
    
            if ($Target -match ".pdf$") { $Target }
        } | select -First 1)
    
    if ($Last_PDF -eq $null) {
        exit
    }
      My Computer


  10. Posts : 759
    Windows 7
       #10

    Recent Items is reverse sorted by last access time, and the first *.pdf match is provided. This should be the last PDF file opened. I have tested it by opening other PDF files outside of Word.

    Can you explain why you expect a different file to be listed?

    - - - Updated - - -

    This code uses the target's file Last Access time, instead of checking the *.lnk file's time.
    Code:
    $objShell = New-Object -ComObject WScript.Shell
    
    $Last_PDF = (Get-ChildItem $env:APPDATA\Microsoft\Windows\Recent -Filter *.lnk |`
        ForEach-Object {
            $Target = $objShell.CreateShortcut($_.FullName).TargetPath
    
            if ($Target -match ".pdf$") {
                [PSCustomObject]@{
                    Filename = $Target
                    LastAccess = (Get-ChildItem $Target).LastAccessTime
                }
            }
        } | Sort-Object LastAccess -Descending | select Filename -First 1)
    
    if ($Last_PDF -eq $null) {
        exit
    }
      My Computer


 

  Related Discussions
Our Sites
Site Links
About Us
Windows 10 Forums is an independent web site and has not been authorized, sponsored, or otherwise approved by Microsoft Corporation. "Windows 10" and related materials are trademarks of Microsoft Corp.

© Designer Media Ltd
All times are GMT -5. The time now is 23:49.
Find Us




Windows 10 Forums