我在服务器上的某个位置有一个文本文件。该文件包含一个字符串值和一个时间戳。 我想用PowerShell替换这个特定的行和最新的时间戳。使用PowerShell替换文本文件中的字符串
下面是记事本文件中的数据:
Test Service|05-09-2017 01-09-41
这里2017年5月9日41年1月9日是MM-DD-YYYY HH-MM-SS,我想与最新的替换此行时间戳。
所以,如果两分钟后它应该是
Test Service|05-09-2017 01-11-41
下面是我在做什么:
$ReplaceString = "$ServiceName + "|" + (Get-Date).ToString('MM-dd-yyyy HH-mm-ss')"
Get-Content Path -Replace($ServiceName + "|" + $StringLastRunTime,$ReplaceString) | Set-Content Path
但它不会产生预期的输出。
UPDATE
对不起,我不是符合要求
我想监控安装使用PowerShell脚本在服务器上的关键服务,以便清楚。我在一个文本文件中列出了要监视的所有服务,并且该脚本中提到了该路径。该脚本每5分钟执行一次,如果未安装服务或停止服务,则会生成电子邮件通知。为了防止电子邮件泛滥,我正考虑使用文本文件中的服务名称来更新时间戳。 因此,如果我发现一个服务处于停止模式或未安装,我将发送通知并更新最后发送时间的时间戳。我有一个重发间隔,每隔五分钟检查一次,如果间隔时间已过,我必须再次发送通知,我想更新时间戳。
代码(我已删除的电子邮件发送部分,使其不太复杂):
$ServicesList = Get-Content E:\ServiceReports\Services.txt
$ResendEmailInterval = 10 #In Minutes
foreach ($Service in $ServicesList) {
$ServiceName = $Service
$Service = Get-Service -Display $Service -ErrorAction SilentlyContinue
$serviceDisplayName = $Service.displayname
if (-Not $Service) {
#Service is not installed. So need to send an email alert and update the timestamp.
Write-Host $ServiceName.IndexOf("|")
if ($ServiceName.IndexOf("|") -gt 0) {
$ServiceName,$StringLastRunTime = $ServiceName.Split('|')
$LastRunTime = [datetime]::ParseExact($StringLastRunTime, "MM-dd-yyyy HH-mm-ss", $null)
Write-Host $ServiceName
Write-Host $LastRunTime
Write-Host (Get-Date).AddMinutes($ResendEmailInterval)
if ($LastRunTime -lt (Get-Date).AddMinutes($ResendEmailInterval)) {
Write-Host "time to run"
$ReplaceString = $ServiceName + "|" + (Get-Date).ToString('MM-dd-yyyy HH-mm-ss')
Write-Host $ServiceName"|"$StringLastRunTime
Write-Host $ReplaceString
#$ServiceName = "Test Service";
$ReplaceString = "{0}|{1}" -f $ServiceName, (Get-Date).ToString('MM-dd-yyyy HH-mm-ss');
(Get-Content -Path $ServicesListPath) -replace ('([^|]+).*', $ReplaceString) | Set-Content $ServicesListPath;
$ServicesList -replace ($ServiceName + "|" + $StringLastRunTime, $ReplaceString) | Set-Content $ServicesListPath
}
} else {
$ReplaceString = $ServiceName + "|" + (Get-Date).ToString('MM-dd-yyyy HH-mm-ss')
$ServicesList -replace ($ServiceName, $ReplaceString) | Set-Content $ServicesListPath
$i = $i+1;
}
} else {
if ($Service.Status -eq "Stopped") {
Write-Host "Service is stopped"
#Time to send email and update the time stamp
$i = $i+1;
} else {
#Write-Host "Service is running. Nothing to do."
}
}
}
这是由什么产生的实际输出? – Seth
你可以粘贴整个脚本吗? – 30000MONKEYS
@ 30000MONKEYS更新 –