Page 1 of 1

Question | Powershell script as service

Posted: Tue Mar 06, 2018 10:01 pm
by v_2nas
Hi,
I am running PS 2017 x64 on Windows 10 x64.
I have a question regarding converting powershell scripts into Service.
I have a script which continuously probe VPN tunnel status using ICMP requests. The script using do while loop and runs infinitely.

Now, If i convert this script into service, will it run only once while the service is running or shall i modify the script to run once and once it's transformed into service, the service will run it infinitely ?

and would the script keep running irrespective of whether the user is logged on or not?

Regards,
Navdeep

Re: Question | Powershell script as service

Posted: Wed Mar 07, 2018 3:55 pm
by davidc
Please refer to the following articles on how to write a service script:

https://www.sapien.com/blog/2017/07/12/ ... owershell/

If you use the functions mentioned in the following article, you can respond to calls to close the service:

https://www.sapien.com/blog/2018/02/27/ ... ript-2018/

We hope to add the template to PowerShell Studio soon.

Re: Question | Powershell script as service

Posted: Wed Mar 07, 2018 10:25 pm
by v_2nas
Hi David,
I followed the first article and converted the following script into service. The service is running but i don't see any data coming in.
If i manually start the script, i can see the data coming in.

Code: Select all

### Create a MetricDatum .NET object
$Metric = New-Object -TypeName Amazon.CloudWatch.Model.MetricDatum
start-sleep -Seconds 1
$Metric.MetricName = 'TunnelState'

do
{
	Start-Sleep -Seconds 1
	
	if (Test-Connection -Count 1 172.18.2.14 -ErrorAction SilentlyContinue)
	{
		
		$Metric.Value = 1
		$Metric.Timestamp = [DateTime]::UtcNow
		$Metric
		Write-CWMetricData -ProfileName AWSCLI -Region ap-southeast-1 -Namespace VPNTunnelStatus -MetricData $Metric
	}
	
	else
	{
		
		$Metric.Value = 2
		$Metric.Timestamp = [DateTime]::UtcNow
		$Metric
		Write-CWMetricData -ProfileName AWSCLI -Region ap-southeast-1 -Namespace VPNTunnelStatus -MetricData $Metric
	}
}
while ($true)

Re: Question | Powershell script as service

Posted: Thu Mar 08, 2018 7:51 am
by davidc
Since services are UI-less, any output from a service will go into the event logs.

Alternatively, you have the option to tell PowerShell to redirect output to a log file.

https://docs.microsoft.com/en-us/powers ... rshell-5.1