Link to home
Start Free TrialLog in
Avatar of Dee
DeeFlag for United States of America

asked on

How to run a batch file in power shell and tell if it generates error

If I execute a batch file from Power Shell, how can I tell if it errors?
Avatar of tsaico
tsaico
Flag of Afghanistan image

Not exactly through powershell, but I always put an output to a TXT command for all the results in my batches for this reason.
Avatar of Dee

ASKER

Can I capture the results from the screen when the powershell script runs to a text file?
Avatar of Dan Craciun
yes, with
| Out-file "log.txt"
ASKER CERTIFIED SOLUTION
Avatar of footech
footech
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dee

ASKER

Dan, can I specify the log file in the script? When I specify it at the command line, I get an empty log file.  But need to be able to specify it in the script.

footech, This is what I really need.  Can I get $lastexitcode to write to a text file from the script?


script.ps1
-------------------
c:\test\batch.bat
//write last exit code to text file
It's just a variable.  You can write it's contents to a file just like any other string (e.g. piping it to Add-Content, Out-File, or other commands).
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dee

ASKER

Thanks.  I got what I need for the beginnings of my first PS script:

C:\Test\test.bat
$myfile = "c:\Test\log.txt"
Get-Date | Out-File $myfile -append
$lastexitcode | Out-File $myfile -append

Thanks!   Points coming!
Just as a curiosity: if you're learning powershell, why are you learning how to keep using bat files? :)

I would think a better learning exercise would be to transform your bat into a true powershell script.

my 2¢
Avatar of Dee

ASKER

I agree.  The call to the batch file will be replaced by calling an exe file.  This is just a test script to get me started coding.
Thanks again
BTW, it's great to see someone new to PS scripting asking how to do something vs. just "please write a script that does this", so kudos to you.
I think you'll find quite a few people in the PowerShell TA here that are willing to explain things when you have questions.
Avatar of Dee

ASKER

Thanks footech!  I'm looking forward to my journey through PowerShell.  I love my experts here.
Second on that!  I troll the forum all the time reading other people's questions and the responses...
Avatar of Dee

ASKER

:)