为什么命令行执行为Powershell中的脚本执行提供了不同的结果

时间:2019-10-18 11:11:27

标签: powershell

在powershell命令提示符下运行以下命令的工作与我期望的一样:

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

但是,如果按照以下方式制作ps1 scritp,我的输出将不是我期望的。

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

*output*
my_service:  System.ServiceProcess.ServiceController 

为什么脚本不返回与命令相同的输出?

3 个答案:

答案 0 :(得分:2)

这里很简单:

echo "My Service Status:" $my_service_check

答案 1 :(得分:1)

使用以下脚本似乎可以根据需要输出结果:

$myService = Get-Service #SERVICE_NAME

Write-Host "My service: " $myService

Pause

输出:

  

我的服务:SERVICE_NAME

     

按Enter键继续...:

答案 2 :(得分:1)

与echo语句中带引号的位置有关。

在您的示例中,$ my_service_check是一个System.ServiceProcess.ServiceController对象-它不是仅包含您看到的数据的字符串。您可以在其上调用方法,例如-$ my_service_check.Start()。

现在就拥有

echo "My Service Status:" $my_service_check

PowerShell足够聪明,可以意识到您想要在该对象中输出人类可读的数据,并且可以获得漂亮的结果。

因为你有

echo "My Service Status: $my_service_check"

PowerShell将对象本身显示为字符串,这几乎从来都不是您真正想要的。