for-loopbatch-filenewlineprinters

How to use printui.exe with a value containing the printer name


Im trying to make a small script that will automatically remove all printers except the ones that are part of the OS (Microsoft to PDF, OneNote, etc).

I tried to filter them one by one in a for loop but for some reasons, it say that it wont recognise the printer name.

I echoed the result instead to see what goes in and the name of the printer seemed to be right.

So im thinking that there could be a newline character at the end of my value and I would like to know how to make sure that the name is correctly outputed in the printui.exe command.

REM Loop that will go through all printer name that are installed on the computer
for /f "tokens=*" %%a in ('wmic printer get name') do (
    REM Verify if the printer name contain "Microsoft", "OneNote" or "Name"
    echo %%a | findstr /i "Microsoft OneNote Name" > nul
    if errorlevel 1 (
        REM Delete the printer that dosent contain any of the word mentionned before
        echo %%a
        printui.exe /dl /n %%a
    ) else (
        REM Delete nothing
    )
)

The code above resulted in a error messagebox saying that it don't recognise the printer, that it might be disconnected or the printer name is wrong. (which is not right to me)

I expected the command to work without error and say that the process was completed.


Solution

  • @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION 
    for /f "delims=" %%b in ('wmic printer get name') do for /f "delims=" %%B in ("%%b") do (
    
     REM Verify if the printer name contain "Microsoft", "OneNote" or "Name"
     echo %%B | findstr /i "Microsoft OneNote Name" > nul
     if errorlevel 1 (
     REM Delete the printer that dosent contain any of the word mentionned before
     SET "myprinter=%%B"
     CALL :mangle
     echo %%B --- !myprinter! ---
     printui.exe /p /n !myprinter!
     ) else (
      REM Delete nothing
     )
    )
    GOTO :EOF
    
    :: IF the printername myprinter contains spaces, replace with `" "`
    :mangle
    IF "%myprinter:~-1%"==" " SET "myprinter=%myprinter:~0,-1%"&GOTO mangle
    SET "myprinter=!myprinter: =" "!"
    GOTO :eof
    

    Always verify against a test directory before applying to real data.

    This is a strange one. If the printer name eg HP LaserJet CP 1025 contains spaces, then it must be entered as HP" "LaserJet" "CP" "1025 - and yes, I've double-checked that. Reference to off-site URL: Spiceworks - set up printer

    I've used the /p option as I don't want to delete printers.