I'm trying to modify a powershell script to prune its log file at then end of its execution.
this works
$prunedContent = Get-Content -Path $logfile | Where{[DateTime]($_.Substring(0, $_.IndexOf(' '))) -GE $pruneDate}
this throws a null object exception
$prunedContent = Get-Content -Path $logfile | Where-Object -InputObject [DateTime]($_.Substring(0, $_.IndexOf(' '))) -GE $pruneDate
vs code gives me a warning
'Where' is an alias of 'Where-Object'. Alias can introduce possible problems and make scripts hard to maintain. Please consider changing alias to its full content.
how can I make the Where-Object work?
I've verified in the debugger that Get-Content is returning the entire contents of the log file. Each line of the log file is known to start with the formatted date/time as YYYY-MM-DD HH:MM:SS
The warning you see, AvoidUsingCmdletAliases
, is just a PSScriptAnalyzer rule that recommends not using aliases in your scripts. It's simply telling you that:
$prunedContent = Get-Content -Path $logfile | Where { [DateTime]($_.Substring(0, $_.IndexOf(' '))) -GE $pruneDate }
Should be:
$prunedContent = Get-Content -Path $logfile | Where-Object { [DateTime]($_.Substring(0, $_.IndexOf(' '))) -GE $pruneDate }