Search code examples
windowspowershellprintingwindows-shellshell-verbs

How to invoke a verb on multiple files


Using PowerShell I would like to invoke the print verb on multiple files. In Windows Explorer I can go into a folder, select a number of files, right-click and choose the print options. This opens up the Print Pictures dialog with all the selected files. I am able to do this for one file using:

$path = "C:\person.jpg";
Start-Process -FilePath $path -Verb Print | Out-Null;
Start-Sleep -s 150;

But was wondering how I could do it for a number of files.


Solution

  • You can use COM to invoke a verb on multiple files in one operation.

    Assuming...

    $folderPath = 'X:\Test'
    $verbName = 'print'
    $verbArguments = ''
    

    ...you can print all objects in a folder with...

    $application = New-Object -ComObject 'Shell.Application'
    $folder = $application.NameSpace($folderPath)
    $folderItems = $folder.Items()
    Write-Verbose "Folder ""$($folder.Self.Name)"" contains $($folderItems.Count) item(s)."
    $folderItems.InvokeVerbEx($verbName, $verbArguments)
    

    I say "objects" because $folderItems will contain both files and folders. The default appears to be enumerate subfolders and ignore hidden objects, while verbs are ignored on objects that don't support them.

    If, for example, you wanted to only print files with a certain extension that are immediate children and include hidden files, you can do so using the Filter() method...

    New-Variable -Name 'SHCONTF_NONFOLDERS'    -Option 'Constant' -Value 0x00040
    New-Variable -Name 'SHCONTF_INCLUDEHIDDEN' -Option 'Constant' -Value 0x00080
    
    $application = New-Object -ComObject 'Shell.Application'
    $folder = $application.NameSpace($folderPath)
    $folderItems = $folder.Items()
    $folderItems.Filter($SHCONTF_NONFOLDERS -bor $SHCONTF_INCLUDEHIDDEN, '*.jpg')
    Write-Verbose "Filtered folder ""$($folder.Self.Name)"" contains $($folderItems.Count) item(s)."
    $folderItems.InvokeVerbEx($verbName, $verbArguments)
    

    If you want to print some custom set of files that don't nicely align by extension, visibility, etc. then I'm not seeing a way to do that. That would seem to require modifying $folderItems or creating a new FolderItems3 instance, and neither appears to be possible. I see there is a ShellFolderView type that supports item selection, but that looks like it's for interacting with an Explorer(-like) window.

    Documentation for types and constants used above: