Thursday, November 10, 2016

Powershell - print all files from a directory

This likely doesn't come up very often for folks these days, but someone out there may appreciate this script.

This script came from a business need to print off a few hundred text files from a directory on the network. With windows printers, you can drag files to a printer and "drop" them into it, to be able to print a lot of files at once, but there's still quite a bit of clicking involved.

This script when run, will prompt for selecting a directory from mapped drives on the machine, it will then print all contents of that directory to the default printer for the machine.

I could get fancier with this, but don't feel a need to as yet. Hopefully this may serve to help others as is / with some minor modifications.

**********Begin script***********

cls
echo " "
echo " "
write-host "Would you like to Print all the Txt files from a directory?" -foregroundcolor RED
echo " "
$Selection = read-host "Type y or n:"
echo " "
cls
If ($Selection -eq "y")
{
cls
Write-Host "Select where to pull the Txt files from..." -ForegroundColor yellow
function Read-FolderBrowserDialog([string]$Message, [string]$InitialDirectory)
{
$app = New-Object -ComObject Shell.Application
$folder = $app.BrowseForFolder(0, $Message, 0, $InitialDirectory)
if ($folder) { return $folder.Self.Path } else { return '' }
}
$directory = Read-FolderBrowserDialog ("Select the folder to print Txt files from","C:\")
$PrintFiles = Get-childItem $directory
ForEach ($PrintFile in $PrintFiles)
{
Start-Process -FilePath "$directory\$PrintFile" -Verb Print -PassThru |%{sleep 5;$_}|kill
echo " "
write-host "Printing $PrintFile..." -foregroundcolor Green
echo " "
}
echo " "
Write-host "All files from the selected directory have been Printed" -foregroundcolor Green
echo " "
read-host "Press enter to exit:"
}
ELSE
{
echo " "
write-host "You chose no, this script is exiting..."
echo " "
read-host "press enter to exit:"
}

**********End Script*******************