Posted on Leave a comment

Get powershell command result as string

Sometimes you may end up with wrong results on powershell because of the return object. A detailed demonstration can be located below where the return object is not a string and the evaluation of equals is not correct.

For example lets assume that we need to check docker status from powershell and catch this result through the string that is returned. When docker is not running you can expect a similar message like the below.

By getting the result of the docker info command into a variable we can see that the return object is of type Object in powershell.

When you try to use the contains functions with this object in order to evaluate the docker status you will end up with a false result as is not evaluated correctly.

In order to resolve this issue you should specify that the result should be a string with Out-String function.

Then when you evaluate the expression with Contains function this is performed as expected and the correct result is returned.

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.