Celay Derp
Celay Derp

Reputation: 13

Powershell Background if Ping script

I have an old CMD Script which I want to convert into a Powershell Script which runs in the Background, the CMD Script:

@echo off
timeout /t 300 /nobreak
ping -n 1 -i 135 -w 130 192.168.1.250
if errorlevel 1 goto Ende
goto Program
:Program
start "" "C:\Program Files (x86)\XXX\XXX.exe"
Exit

:Ende
Exit

The Script checks if the Router is pingable, if yes it starts a program. I have completly zero experience with either CMD or Powershell(see Goto <.<), I tried to do it with google and found some solutions to run it in background but they didn't really work out for me.

The Sleep option should work with start-sleep -s 300, the Ping Check with if (test-connection -computername Server01 -quiet) but im not completly sure how to do an if-statement around the ping.

Greetings

Upvotes: 1

Views: 3498

Answers (2)

Jamie McNamara
Jamie McNamara

Reputation: 50

This is a post by IAMGr00t on community.spiceworks.com

"1. Deploy a policy that sets the execution policy to remote signing, you will have to sign your scripts. Have a look here on how to do that.

or

  1. Make a .bat file that when launched will open powershell and run the command. The caveat here is that it is very important you get your switches correctly. If these need to be specific to the user running the script do NOT use -noprofile. If you want it to run silently in the background your batch file would look something like this.

powershell.exe -executionpolicy bypass -windowstyle hidden -noninteractive -nologo -file "name_of_script.ps1"

EDIT: if your file is located on another UNC path the file would look like this. -file "\server\folder\script_name.ps1"

These toggles will allow the user to execute the PowerShell script by double clicking a batch file. There will be no window, no copyright logo, and no user interactivity. The perks of this, is the user does not see the background noise. I have had to do this recently. It works without muddling with all users' execution policies.

Really makes you wonder how secure your environment is if you can run a script with -bypass flags. Also keep in mind things that would need administrative write access. But, what I have said above should point you in the right direction. Just make a .bat file with the one line of opening PowerShell. It feels clunky (it is) but it works."

Upvotes: 0

sodawillow
sodawillow

Reputation: 13176

I'd try this:

Ping-AndLaunch.ps1:

Start-Sleep -Seconds 300

if(Test-Connection "192.168.1.250" -Count 1 -TimeToLive 135) {
    & "C:\Program Files (x86)\XXX\XXX.exe"
}

Launch command (to hide the PowerShell window):

powershell -File .\Ping-AndLaunch.ps1 -WindowStyle Hidden

Upvotes: 2

Related Questions