powershell 获取日志文件的日期

问题描述 投票:0回答:1

我正在尝试获取一个脚本来测试 IP 地址列表的连接并将输出记录到文件中。当我没有得到回应时,我希望它在日志中添加时间/日期戳。我想在 2-3 天的时间内执行该脚本。我已经将时间/日期标记放在控制台的输出上,但不在输出文件中。这是脚本。

$names=Get-Content "C:\script\hname.txt"
foreach($name in $names){
    if(Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
        Write-Host "$name is up" -ForegroundColor Green
        $output+="$name is up,"
    }
    else{
        Write-Host "$name is down" -ForegroundColor Red
        Get-Date 
        $output+="$name is down,"
        " "
    }
}
$output | Out-File -FilePath "C:\script\results.txt"
Start-Sleep -s 3

这是ps控制台上的结果

PS C:\Windows\system32> C:\Users dmin\Documents\Test Connection-3sec.ps1
192.168.1.254 已上线
192.168.1.74 已关闭

2023 年 10 月 10 日星期二 12:06:05 下午
 
192.168.1.239 已上线
192.168.1.23 已关闭
2023 年 10 月 10 日星期二 12:06:07 下午
 
192.168.1.189 已上线
192.168.1.78 已上线
192.168.1.79 已上线
192.168.1.81 已上线
192.168.1.89 已关闭
2023 年 10 月 10 日星期二 12:06:08 下午
 
192.168.1.82 已上线
192.168.1.85 已上线
192.168.1.45 已关闭
2023 年 10 月 10 日星期二下午 12:06:10

PS C:\Windows\system32>

但这就是我在 results.txt 文件中得到的。

192.168.1.254 已上线,
192.168.1.74 已关闭,
192.168.1.239 已上线,
192.168.1.23 已关闭,
192.168.1.189 已上线,
192.168.1.78 已上线,
192.168.1.79 已上线,
192.168.1.81 已上线,
192.168.1.89 已关闭,
192.168.1.82 已上线,
192.168.1.85 已上线,
192.168.1.45 已关闭,

作为旁注,该格式没有新的换行符,据我所知,如果我添加`$output+="$name is up," +"

n
r"

,我应该能够得到新的换行符

我尝试将 get-date 放在 $output 行的末尾,但没有成功。

$output+="$name is down," Get-Date`your text`

我该怎么做?

powershell output logfile getdate
1个回答
0
投票
$output+="$name is down,$(Get-date)"
© www.soinside.com 2019 - 2024. All rights reserved.