powershell - Power Shell 获取服务问题
问题描述
嗨,我需要一个脚本来执行以下操作:
- 检查服务是否存在
- 如果服务不存在运行我的脚本
- 如果服务存在,什么也不做
这是我所拥有的,但它对我不起作用:
$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
什么都不返回的情况下运行。我在哪里错了?
解决方案
检查服务是否存在的更简单方法:
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
}
推荐阅读
- node.js - 在 Alexa Intent 处理程序中进行 API 调用
- sql-server - SQL Server:从一列创建两列
- php - 重复代码,生成函数,但保持变量全局?
- php - 使用数组按票数排序后未显示新的自定义帖子
- mysql - 基于两个列 id 的 mySQL 透视/合并/移动行到列中
- r - 计算具有相似键的过去条目
- r - ggplot2中的颜色和填充参数有什么区别?
- sql - 将 spark 数据帧聚合转换为 SQL 查询;window、groupby 的问题,以及如何聚合?
- vhdl - 在第一个时钟脉冲中读取 ROM 时出现意外值
- java - java - 如何通过java j2ee中的控制器设置外键?