PowerShell Script not getting right PDF filename for Recent?

  1. Posts : 61

    PowerShell Script not getting right PDF filename for Recent?

    I need help to troubleshoot following PowerShell Script not working because it found wrong file in Recent Items of Windows 10.
    This is to open PDF with Word when Adobe is default App.

    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
    PowerShell Script not getting right PDF filename for Recent?-powershell-script-open-recent-pdf-word-fails-2023-06-06-110355.gif
    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.
    How to enable execution of PowerShell scripts?
    set-executionpolicy remotesigned -Scope CurrentUser
    Add-Type @"
        using System;
        using System.Runtime.InteropServices;
        public class WinAp {
            [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) {
    $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
      My Computer

  2. Posts : 17,049
    Windows 10 Home x64 Version 22H2 Build 19045.4170
      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 18:18.
Find Us

Windows 10 Forums