Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invoke-expression doesnot throw an error in powershell

Tags:

powershell

I am creating custom forms and adding it to the printer server properties using forms.vbs and running it through cmd. The script is as follows

cscript 'C:\Tools\forms.vbs' -a -n "DD" -u inches -h 7.48 -w 7.48 -t 0 -e 0 -b 7.48 -r 7.48

This works fine when running in command prompt.

Now I invoked this code to the powershell as follows and it also works fine

  $formname = "DD"
  $cmd = "cscript 'C:\Tools\forms.vbs' -a -n " + '"' + $formname + '"' + " -u inches -h 7.48 -w 7.48 -t 0 -e 0 -b 7.48 -r 7.48 "
  Invoke-Expression  $cmd 

The issue started when I thought of checking the error handling thing for the powershell invoke expression.

In cmd when we give the expression as

cscript 'C:\Tools\forms.vbs' -a -n "DD" -u inches -h 7.48 -w 7.48 -t 0 -e 0 -b 0 -r 0

This will definitely throw error as per the notes given in the form.vbs and it will not create a form.

So when I invoked the same error-thrown script to my powershell, the form is not creating as well as it is not throwing any errors. So I request me to guide in this regard. Thanks in advance.

like image 857
Basati Naveen Avatar asked May 15 '26 01:05

Basati Naveen


1 Answers

Invoke-Expression only checks if it's possible to run the command at all. For example, if cscript.exe cannot be found, Invoke-Expression will throw an ObjectNotFound exception.

It doesn't check the exit code of the command or in any way parse its output. You should be able to see the output however.

Make sure you don't mix single and double quotes inside your expression:

$formname = "DD"
# Note double quotes around C:\Tools\forms.vbs
$cmd = 'cscript "C:\Tools\forms.vbs" -a -n ' + '"' + $formname + '"' `
    + ' -u inches -h 7.48 -w 7.48 -t 0 -e 0 -b 7.48 -r 7.48 '
Invoke-Expression $cmd

Output:

Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

Unable to add form DD, error code: 0x1A8. Object required

If you want your code to throw an exception, you need to parse the output manually, e.g.:

try {
    $output = Invoke-Expression $cmd 
    if ($output -like "*error code*") { throw $output }
}
catch [System.Exception] {
    $message = ($Error[0].Exception -split [System.Environment]::NewLine)[-1]
    $message
}

Output:

Unable to add form DD, error code: 0x1A8. Object required
like image 58
Alexander Obersht Avatar answered May 18 '26 14:05

Alexander Obersht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!