2017-04-19 69 views
0
$Service = Get-Service -ComputerName SYNESIGNSVR -Name SynAutoImportService 
$ServiceDName = $Service.DisplayName 
$ServiceStat = $Service.Status 

Add-Content "c:\temp\logtemp - Services Status.log" "$(Get-Date -Format 
"yyyy-MM-dd HH:mm:ss") - $ServiceDName service on server SYNESIGNSVR current 
status: $ServiceStat" 

我正在写一个PS脚本,将创建一个日志文件与几个不同的服务和他们的几个不同的Windows服务器的当前状态。上面的代码工作和回报:PowerShell添加内容与获取服务

2017年4月19日12时01分17秒 - 在服务器上SYNESIGNSVR当前状态协同文档AUTOIMPORT服务:运行

这似乎是草率的代码,我的方式已经拉取得服务,并使状态和显示名称拉入。

我正在寻找方法,我可以使此代码更清洁,或更有效。

+0

没有什么错与您的代码。 –

+0

同意,Ansgar。我在PowerShell方面有点新,并且正在寻找优化/编写干净代码的方法。此代码确实会返回我想要和需要的内容。 –

+0

我的意思是说你的代码很好。你可以用不同的方式得到相同的结果(例如参见TessellatingHeckler的答案),但我不会认为比其他方法更“清洁”或“更高效”,至少在你的问题的背景下。 –

回答

3

什么:

$Computer = 'SYNESIGNSVR' 
$Service = Get-Service -ComputerName $Computer -Name SynAutoImportService 

$LogLine = "{0} - {1} service on server {2} current status: {3}" -f [DateTime]::Now, 
                    $Service.DisplayName, 
                    $Computer, 
                    $Service.Status 

Add-Content -Path "C:\temp\logtemp - Services Status.log" -Value $LogLine 
+0

如果经常使用它,我会认为将它们包装到一个函数中,并将'Computer''ServiceName''logFile'作为参数,保持不变。 –

+0

在变量例如脚本的顶部,'Path'参数的值也会更好。 $ outputPath – pandemic

+0

与logline模板相同。 –