Posted on Leave a comment

Start windows service with powershell

Sometimes the windows services manager may not be enough for interaction with the services. Using the GUI you can set a service to start on startup by changing the status from Manual to Automatic but there could be cases that you want to execute this functionality with powershell. A reason for that could be a failure on the service startup that you want to check through code.

Using powershell you can check if a service is running with Get-Service. The below example checks if docker service is running and if not it will print a message on the output of the command line.

if (-not((Get-Service -Name "com.docker.service").Status -eq "Running")) { echo not running }

We can now check how to implement the start of the service using powershell. As shown below the docker desktop service is not running at the moment.

 if (-not((Get-Service -Name "com.docker.service").Status -eq "Running")) { Start-Service -Name "com.docker.service" }

After running the powershell above, we will get the service started.

Using the powershell you can create an automatic job with task scheduler and check this behavior on the computer startup.

Posted on Leave a comment

Powershell -Contains does not evaluate string with Get-Content

When using powershell contains method you should be aware of the type of the object that is used.

Lets examine the below string which was used with contains on a powershell script.

Processed 384 pages for database ‘restore’, file ‘restore’ on file 1.
Processed 2 pages for database ‘restore’, file ‘restore_log’ on file 1.
RESTORE DATABASE successfully processed 386 pages in 0.004 seconds (752.929 MB/sec).

The string was stored on $result variable and I wanted to capture if a specific string was included in the variable. Although the string is included in the variable the result was false.

After investigating I was able to figure that the object type of the $result variable was an object and Contains could not evaluate successfully

In this situation you would have to cast the object on a string data type to evaluate correctly.

For example when using Get-Content you could cast to a string like below.

[string]$result = Get-Content C:\Users\galexiou\Desktop\2.txt

Then the object type will be of type string

The evaluation will work as expected.