a.smith
a.smith

Reputation: 315

why does command line execution gives different result to script execution in powershell

Running the following command in powershell command prompt works as i would expect:

Get-Service "my_service"
*output*
 Status   Name               DisplayName                           
------   ----               -----------                           
Running  my_service          My_SERVICE   

However if make a ps1 scritp as follows my output is not what i would expect.

$my_service_check = Get-Service "my_service"
echo "My Service Status: $my_service_check"

*output*
my_service:  System.ServiceProcess.ServiceController 

why does the script not return the same output as the command?

Upvotes: 2

Views: 563

Answers (3)

Mark
Mark

Reputation: 434

It's more to do with where you have the quotation marks in the echo statement.

In your example, $my_service_check is a System.ServiceProcess.ServiceController object- it's not a string that just contains the data you see. You could call methods on it, for example- $my_service_check.Start().

Now if you had

echo "My Service Status:" $my_service_check

PowerShell is smart enough to realize you want to output the human-readable data in that object- and you get the pretty results.

Because you have

echo "My Service Status: $my_service_check"

PowerShell is displaying the object itself as a string- which is almost never what you actually want.

Upvotes: 1

vbhosale
vbhosale

Reputation: 96

Here is simple one:

echo "My Service Status:" $my_service_check

Upvotes: 2

Mark Harwood
Mark Harwood

Reputation: 2415

Using the below script seems to output the results as you want it:

$myService = Get-Service #SERVICE_NAME

Write-Host "My service: " $myService

Pause

Output:

My service: SERVICE_NAME

Press Enter to cotinue...:

Upvotes: 1

Related Questions