Give Powershell the output of a command as if it was a string

2

I'm using Powershell to script the deletion of printers and their drivers. I'm calling the Printing_admin_scripts that are located in the System32 folder on Windows 7+. These scripts generate a LOT of output, and I'd like to capture the output (throw away most of it), and generate my own output, depending on the status.

Why can't you use $LASTEXITCODE?

Cause these scripts do not generate any exit codes! They always represent 0.

My goal is to look for "0x80041002" in the output of the command. If so, do this... If not, do that. Below is what I've tried, but failed:

.\prnmngr.vbs -d -p "$_" | findstr "0x80041002" | out-null
        If ($LASTEXITCODE = 0) {
            Write-Host "$_ does not exist"
        } else {
            Write-Host "$_ removed"
        }

I also tried:

& .\prnmngr.vbs -d -p "$_".ToString() | findstr "0x80041002" | out-null
        If ($LASTEXITCODE = 0) {
            Write-Host "$_ does not exist"
        } else {
            Write-Host "$_ removed"
        }

This hides the output, but always prints that the printer was removed, even if it did not exist (which normally outputs "0x80041002"). My goal is to find that string, even though it's not written to the host (hopefully), then write my own text in place, and continue on.

windows
powershell
asked on Super User Apr 3, 2018 by Canadian Luke • edited Apr 3, 2018 by Canadian Luke

2 Answers

1

Simply change the PowerShell logic to use -eq rather than = within the if condition. Doing this will help ensure your conditional commands execute as expected based on the $LASTEXITCODE.

If Command Syntax

If ($LASTEXITCODE -eq 0) {
    Write-Host "$_ does not exist"
} else {
    Write-Host "$_ removed"
}

Further Resources

answered on Super User Apr 4, 2018 by Pillsbury IT Doughboy
1

Storing the result in an array is working for me:

$script = "C:\Windows\System32\Printing_Admin_Scripts\en-US\prnmngr.vbs"

$result = cscript $script -g

if($result -match 'foo') {
    write-host "match"
}
else {
    write-host "no match"
}
answered on Super User Apr 4, 2018 by root

User contributions licensed under CC BY-SA 3.0