Powershell命令Get-Service和Get-WmiObject在Jenkins文件中返回false

时间:2020-10-02 15:09:39

标签: powershell jenkins

我必须在Jenkins管道中运行Powershell脚本。我们正在使用的Powershell版本是5.1。 脚本中的大多数命令都没有问题。 我试图确定是否存在窗口服务。如果是这样,那么我不需要复制exe,如果不是,我想将exe复制到窗口服务器。 这是问题所在的代码部分:

 Write-Host "Unzipped the folder"

 if(Get-WmiObject -Class Win32_Service -Filter "Name='TMWTMSListener'")
 {
    Write-Host "TMWTMSListener Service exists"
    Stop-Service -Name "TMWTMSListener" -NoWait
    Write-Host "TMWTMSListener Service stopped"
                    
    Copy-Item -Path "$tempDeployExtractPath\*.jar" -Destination "$deployPath" -Force
    Copy-Item -Path "$tempDeployExtractPath\*.xml" -Destination "$deployPath" -Force 
 }
 else {
    Write-Host "TMWTMSListener Service does not exist"
    Copy-Item -Path "$tempDeployExtractPath\*.jar" -Destination "$deployPath" -Force
    Copy-Item -Path "$tempDeployExtractPath\*.exe" -Destination "$deployPath" -Force
    Copy-Item -Path "$tempDeployExtractPath\*.xml" -Destination "$deployPath" -Force    

}

我也在if语句中尝试过此命令:

if(Get-Service -DisplayName "TMWTMSListener" -ErrorAction Ignore)

即使我在Powershell中的服务器上测试这两个命令时,if语句也始终为false。 即使我停止了该服务,在Powershell中的服务器上运行时,命令也会返回true。它可以找到服务。

有没有解决此问题的方法? 如何在Jenkins中存储Get-Service或Get-WmiObject命令的结果?

1 个答案:

答案 0 :(得分:0)

我解决了上述问题。我需要在命令中设置ComputerName。它正在寻找服务的构建箱。它需要查看远程服务器。 这是我用来确定服务是否存在的命令

$ServiceResult = Get-Service -ComputerName "C0016581" -DisplayName "TMWTMSListener" -ErrorAction Ignore