我在下面有一个powershell脚本,它接受一个配置文件并删除与正则表达式匹配的x天以前的文件。
配置文件:
path,pattern,days,testrun
C:\logs\,^data_access_listener.log,7,false
然而,这是输出:
Would have deleted 000a19f6-a982-4f77-88be-ca9cc51a2bcbuu_data_access_listener.log
Would have deleted 00189746-2d46-4cdd-a5bb-6fed4bee25a7uu_data_access_listener.log
我期望输出包含完整的文件路径,因为我正在使用.FullName属性,所以我希望输出如下:
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
如果我使用$ x.FullName,为什么我没有获得路径的全名(C:\ logs)?
由于 布拉德
$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
}
答案 0 :(得分:8)
看起来像一个错字。您没有在导致“将被删除”的条件下使用FullName。变化:
write-output “Would have deleted $x” >>$LogFile
为:
write-output “Would have deleted " $x.FullName >>$LogFile
要回答您的评论,如果要在字符串中展开的变量上调用属性,则必须将其包围在$()
中,以便解析器知道调用整个表达式。像这样:
write-output “Would have deleted $($x.FullName)" >>$LogFile