2

I want to call a simple Powershell script file that should return either 0 or 1 upon the ps script failure or pass respectively, from a batch file . And based upon the return value, I want to continue further or quit.

The following illustrates what I have tried out:

startup.bat:-

@ECHO OFF
SET x = powershell C:\Users\saravind\Desktop\pingping.ps1
if "%x%" == 1 then (
    doSomething1
    ECHO Ran project 1
)

pingping.ps1:-

$someIP = '192.168.173.299'
$result = $true
try { Test-Connection $someIP -Source localhost -ErrorAction Stop }
catch { $result = $false }

What I'm trying to achieve is that on the execution of pingping.ps1 if it can successfully ping the '192.168.173.299', it should return some value, say 1 to the batch file from which it was being called. And if the ping fails, it should return 0 so that the batch file will not proceed with 'doSomething' Eventhough the pingping fails, it proceeds with doSomething with my code. What's wrong with my code.

Thanks in advance.

a4aravind
  • 1,202
  • 1
  • 14
  • 25
  • That's a duplicate question. Check that one: http://stackoverflow.com/questions/6180572/execute-powershell-script-inside-batch-file – Rami Oct 24 '13 at 06:56
  • I think it's not a duplicate of that. There he say's the ps1 file does exist. And he's just tryin to execute a powershell statement. – a4aravind Oct 24 '13 at 07:07
  • Have a look here: http://stackoverflow.com/questions/932291/calling-powershell-cmdlets-from-windows-batch-file – Rami Oct 24 '13 at 07:12
  • Aplogies, I am not that clear whether the call SET x = powershell C:\Users\saravind\Desktop\pingping.ps1 can be altered to return something. I'm getting the value of as "" always. Thanks for your patience – a4aravind Oct 24 '13 at 07:25
  • Why don't you try something like: powershell -ExecutionPolicy RemoteSigned -File "C:\Users\saravind\Desktop\pingping.ps1" – Rami Oct 24 '13 at 07:29

2 Answers2

3

The followign works for me, I used 0 to indicate the powershell script succeeded and 1 for error happened.

startup.bat:

@echo off
powershell C:\Users\saravind\Desktop\pingping.ps1

if %errorlevel% equ 0 (
    doSomething1
    ECHO Ran project 1
)

pingping.ps1:

$someIP = '192.168.173.299'
try {
    Test-Connection $someIP -Source localhost -ErrorAction Stop
}
catch {
    exit 1
}
exit 0
poiu2000
  • 960
  • 2
  • 14
  • 30
1

Why not test if the 'ping' have success?

your ps1 file should be:

$someIP = '192.168.173.299'
it ( Test-Connection $someIP )
{ 1 }
Else
{ 0 }

your batch file should be:

@echo off
FOR /f  %%i IN ('powershell -noprofile C:\Users\saravind\Desktop\pingping.ps1') DO set x=%%i
if "%x%" == 1 (
doSomething1
@echo  Ran project 1
)
CB.
  • 58,865
  • 9
  • 159
  • 159
  • Thanks a lot @C.B, but in both the cases(for 1 & o), the doSomething is getting executed. – a4aravind Oct 24 '13 at 08:51
  • @user2234700 oops.. remove the `then` after the if statment.. have fixed it in my answer.. try now. – CB. Oct 24 '13 at 09:03