csv Powershell脚本改进以获取有关进程状态的信息

pdtvr36n  于 2022-12-15  发布在  Shell
关注(0)|答案(1)|浏览(147)

我使用简单的脚本如下,为了收集有关3进程在我的服务器上运行的信息。Whne进程没有运行,然后从脚本输出是0,当运行是1。我想改进我的脚本,并减少行数,因为每个进程我使用单独相同的代码,我知道这是可能的,在一个循环,但我不知道如何改进。

$file = "D:\GrafanaScripts\results.txt"

$ServiceName1 = "ETOS1"
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"  
$server= Hostname
$ServiceStatus = (Get-Service -Name $ServiceName1).status
if($ServiceStatus -eq "Running")
{
   # Write-Host "Running"
   echo "$time;$server;$ServiceName1;;;1"  >> $file
   }
else {
   #Write-Host "Stopped"
   echo "$time;$server;$ServiceName1;;;0"  >> $file
} 

$ServiceName2 = "ETOS1 Database"
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"  
$server= Hostname
$ServiceStatus = (Get-Service -Name $ServiceName2).status
if($ServiceStatus -eq "Running")
{
   # Write-Host "Running"
   echo "$time;$server;;$ServiceName2;;1"  >> $file
   }
else {
   #Write-Host "Stopped"
   echo "$time;$server;;$ServiceName2;;0"  >> $file
} 

$ServiceName3 = "ETOS1 Webserver"
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"  
$server= Hostname
$ServiceStatus = (Get-Service -Name $ServiceName3).status
if($ServiceStatus -eq "Running")
{
   #Write-Host "Running"
   echo "$time;$server;;;$ServiceName3;1"  >> $file
   }
else {
   #Write-Host "Stopped"
   echo "$time;$server;;;$ServiceName3;0"  >> $file
} 

Out-File "D:\GrafanaScripts\results.csv" -encoding utf8 
Add-Content "D:\GrafanaScripts\results.csv"  "Time;Hostname;ServiceName1;ServiceName2;ServiceName3;Status"
Add-Content "D:\GrafanaScripts\results.csv" -Value (Get-Content $file)

结果应导出到csv文件中,如下所示:

Time;Hostname;ServiceName1;ServiceName2;ServiceName3;Status
2022-12-09 09:20:43;sneoshh1122;ETOS1;;;1
2022-12-09 09:20:44;sneoshh1122;;ETOS1 Database;;1
2022-12-09 09:20:44;sneoshh1122;;;ETOS1 Webserver;1

谢谢你的支持

bvuwiixz

bvuwiixz1#

这样就可以了,现在你有了一个遍历列表ServiceNames中每个ServiceName的循环。

$file = "D:\GrafanaScripts\results.txt"
$ServiceNames = "ETOS1",”ETOS1 Database“,"ETOS1 Webserver"
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"  
$server= Hostname
Foreach($ServiceName in $ServiceNames){
   $ServiceStatus = (Get-Service -Name $ServiceName).status
   if($ServiceStatus -eq "Running")
{
   # Write-Host "Running"
  echo"$time;$server;$ServiceName1;;;1"  >> $file
   }
   else {
   #Write-Host "Stopped"
   echo "$time;$server;$ServiceName1;;;0"  >> $file
} 
}

你是复制脚本到服务器并在本地运行它吗?因为如果需要,这也可以在多个服务器上并行远程完成。

相关问题