powershell - 已完成 Powershell 任务的时间戳
问题描述
我有一个基本脚本,它将关闭 Windows 服务并生成有关其关闭过程的报告。我还想在我的输出变量$table
(我不知道如何在我的报告中实现这一点。
$processlist = @('SQLTELEMETRY$TESTDB', 'MSSQL$TESTDB', 'SQLWRITER')
$get = ''
$table = @{ }
$failed = 0
foreach ($proc in $processlist) {
stop-service -name $proc -force
}
#start-sleep -s 120
foreach ($proc in $processlist) {
$get = get-service $proc -Erroraction ignore
if ($get.Status -eq 'Running') {
$table += @{$proc = 'Running' }
}
else {
$table += @{$proc = 'Stopped' }
}
}
foreach ($value in $table.GetEnumerator()) {
if ($value.Value -eq 'Running') {
$failed += 1
}
}
if ($failed -gt 0) {
$err = 'FAILED'
}
else {
$err = 'SUCCESS'
}
$table.GetEnumerator() | Select-Object -Property Name, Value | export-csv appreport.csv -delimiter ";" -force -notypeinformation
(HTML part here...)
解决方案
与其将东西添加到哈希表中,我认为构建对象数组并将其写入 CSV 文件会容易得多。
像这样的东西:
$serviceList = 'SQLTELEMETRY$TESTDB', 'MSSQL$TESTDB', 'SQLWRITER'
$maxAttempts = 10
# $result will become an array of PsCustomObjects you can easily pipe to Export-Csv
$result = foreach ($service in $serviceList) {
$shutStart = Get-Date
$svc = Get-Service -Name $service -ErrorAction SilentlyContinue
if ($svc) {
for ($attempt = 0; $attempt -lt $maxAttempts; $attempt++) {
$shutResult = 'Failed'
Start-Sleep -Milliseconds 100
$svc | Stop-Service -Force -ErrorAction SilentlyContinue
# test if the service has stopped. If so exit the loop
if (($svc | Get-Service).Status -eq 'Stopped') {
$shutResult = 'Success'
break
}
}
[PsCustomObject]@{
'ServiceName' = $svc.Name
'ServiceDisplayName' = $svc.DisplayName
'ShutDownStart' = $shutStart
'ShutDownEnd' = Get-Date
'Result' = $shutResult
}
}
else {
[PsCustomObject]@{
'ServiceName' = $service
'ServiceDisplayName' = ''
'ShutDownStart' = $shutStart
'ShutDownEnd' = Get-Date
'Result' = "Failed: Service '$service' could not be found."
}
}
}
# output on screen
$result
# output to CSV
$result | Export-Csv 'D:\appreport.csv' -Delimiter ";" -Force -NoTypeInformation
屏幕上的输出将如下所示:
ServiceName : SQLTELEMETRY$TESTDB ServiceDisplayName : ShutDownStart : 22-8-2019 16:47:40 ShutDownEnd : 22-8-2019 16:47:40 Result : Failed: Service 'SQLTELEMETRY$TESTDB' could not be found. ServiceName : MSSQL$TESTDB ServiceDisplayName : ShutDownStart : 22-8-2019 16:47:40 ShutDownEnd : 22-8-2019 16:47:40 Result : Failed: Service 'MSSQL$TESTDB' could not be found. ServiceName : SQLWRITER ServiceDisplayName : SQL Server VSS Writer ShutDownStart : 22-8-2019 16:47:38 ShutDownEnd : 22-8-2019 16:47:39 Result : Success
希望有帮助
推荐阅读
- mysql - 将spring boot应用程序连接到My SQL数据库时如何避免异常?
- python - 将低特征图像拼接在一起
- javascript - 单击时如何使我的内部 div 中的元素覆盖整个外部 div?
- javascript - 使用 axios 返回保存在 URL 中的数组
- python - 如何从带有不同标题的 xls 文件中导入数据
- c# - 测试派生类时如何模拟我的基本方法
- docker - openshift 集群中 Kaniko 作业的权限被拒绝
- python - Jupyter 中的 Tkinter PhotoImage
- apache - Apache 上的 Symfony 将 /login 路径重写为 /web/login
- macos - 使用可能的密码列表从终端安装加密的 .dmg?