我正在尝试修改 powershell 脚本以在执行结束时修剪其日志文件。
这个有效
$prunedContent = Get-Content -Path $logfile | Where{[DateTime]($_.Substring(0, $_.IndexOf(' '))) -GE $pruneDate}
这会引发空对象异常
$prunedContent = Get-Content -Path $logfile | Where-Object -InputObject [DateTime]($_.Substring(0, $_.IndexOf(' '))) -GE $pruneDate
vs code 给了我一个警告
“Where”是“Where-Object”的别名。别名可能会带来问题并使脚本难以维护。请考虑将别名更改为其完整内容。
我怎样才能使Where-Object工作?
我已在调试器中验证 Get-Content 正在返回日志文件的全部内容。 日志文件的每一行均以格式化日期/时间开头,格式为 YYYY-MM-DD HH:MM:SS
AvoidUsingCmdletAliases
,只是一个PSScriptAnalyzer规则,建议不要在脚本中使用别名。它只是告诉你:
$prunedContent = Get-Content -Path $logfile | Where { [DateTime]($_.Substring(0, $_.IndexOf(' '))) -GE $pruneDate }
应该是:
$prunedContent = Get-Content -Path $logfile | Where-Object { [DateTime]($_.Substring(0, $_.IndexOf(' '))) -GE $pruneDate }