I have a powershell script below which takes a config file and deletes files older than x days matching a regular expression.
Config File:
path,pattern,days,testrun
C:\logs\,^data_access_listener.log,7,false
However here is what is output:
Would have deleted 000a19f6-a982-4f77-88be-ca9cc51a2bcbuu_data_access_listener.log
Would have deleted 00189746-2d46-4cdd-a5bb-6fed4bee25a7uu_data_access_listener.log
I'm expecting the output to include the full fi开发者_如何学Cle path since I'm using the .FullName attribute so I'd expect output as such:
Would have deleted C:\logs\000a19f6-a982-4f77-88be-ca9cc51a2bcbuu_data_access_listener.log
Would have deleted C:\logs\00189746-2d46-4cdd-a5bb-6fed4bee25a7uu_data_access_listener.log
If I am using $x.FullName why am I not getting the full name with path (C:\logs)?
Thanks Brad
$LogFile = "C:\deletefiles.log"
$Config = import-csv -path C:\config.txt
function DeleteFiles ([string]$path, [string]$pattern, [int]$days, [string]$testrun){
$a = Get-ChildItem $path -recurse | where-object {$_.Name -notmatch $pattern}
foreach($x in $a) {
$y = ((Get-Date) - $x.LastWriteTime).Days
if ($y -gt $days -and $x.PsISContainer -ne $True) {
if ($testrun -eq "false") {
write-output “Deleted" $x.FullName >>$LogFile
} else {
write-output “Would have deleted $x” >>$LogFile
}
}
}
}
foreach ($line in $Config) {
$path = $line.path
$pattern = $line.pattern
$days = $line.days
$testrun = $line.testrun
DeleteFiles $path $pattern $days
}
Looks like a typo. You are not using FullName in the condition that leads to "Would have Deleted". Change:
write-output “Would have deleted $x” >>$LogFile
to:
write-output “Would have deleted " $x.FullName >>$LogFile
To answer your comment, if you want to call a property on a variable that is expanded in the string, you have to surround it in $()
, so that the parser knows to invoke the whole expression. Like this:
write-output “Would have deleted $($x.FullName)" >>$LogFile
精彩评论