簡體   English   中英

電源 Shell 獲取服務問題

[英]Power Shell Get Service Issue

嗨,我需要一個腳本來執行以下操作:

  1. 檢查服務是否存在
  2. 如果服務不存在運行我的腳本
  3. 如果服務存在,什么也不做

這是我所擁有的,但它對我不起作用:

    $service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'"
if($service.Status -eq $NULL)
{
$CLID = $inclid
New-Item -Path "c:\" -Name "folder" -ItemType "directory"
Invoke-WebRequest -Uri https://something.com\setup.exe -OutFile c:\folder\swibm#$CLID#101518#.exe
$installer = "swibm#$CLID#101518#.exe"
Start-Process -FilePath $installer -WorkingDirectory "C:\folder"
}
else
{
Write-Host "Client Already Installed"
}

如果我單獨運行$service.Status我會得到一個“OK”返回。 在這種情況下,我需要腳本停止並運行 else 部分。 如果$service.Status什么都不返回,我只希望這個腳本運行。 我在哪里錯了?

您可以嘗試將 $null 放在比較的左側。

If($null -eq $services.status)

是一篇很好的文章討論它

檢查服務是否存在的更簡單方法:

if( Get-WmiObject -Class Win32_Service -Filter "Name='servicename'" ) {
    # Service exists
}
else {
    # Service doesn't exist
}

...或使用Get-Service cmdlet:

if( Get-Service -ErrorAction SilentlyContinue -Name servicename ) {
    # Service exists
}
else {
    # Service doesn't exist
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM