Powershell脚本删除专门命名的文件

时间:2013-10-17 20:50:00

标签: powershell

我有一个Powershell脚本,每晚都作为计划任务运行。它很棒。 我现在要做的是在另一台机器上使用相同的脚本来删除超过x天的特定日志文件。 日志文件的路径:C:\ Company \ Logs 这里有4个不同的日志文件。我需要能够独立删除每种类型,并发送脚本中已有的相同类型的报告。

main.log.date.txtlog

companyname.date.txtlog

dupdump.txt

sfsync.date.txt

这是我目前正在使用的脚本。

dir C:\inetpub\logs\LogFiles\W3SVC1 -recurse | where {!$_.PsIsContainer -AND $_.lastWriteTime -lt (Get-Date).AddDays(-10) } | select LastWriteTime,@{n="Path";e={convert-path $_.PSPath}} | tee C:\LogCleanup\deleted.txt | Remove-Item -force

$filename = "C:\LogCleanup\deleted.txt"
$smtpserver = “smtp.company.net”
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($filename)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.EnableSsl = $True
$smtp.Credentials = New-Object System.Net.NetworkCredential(“monitor@company.net”, “password”);  # Put username without the @GMAIL.com or – @gmail.com
$msg.From = “DeletedFilesLog@company.net”
$msg.To.Add(”is@company.net")
$msg.Subject = “The IIS log files in the attached file have been deleted.”
$msg.Body = “The IIS log files on MACHINE NAME have been deleted. See the attached file to view     the log files that were deleted today”
$msg.Attachments.Add($att)
$smtp.Send($msg)

1 个答案:

答案 0 :(得分:0)

这应该有效:

$time = "-7"    
$filename = main.log.date.txtlog
Get-ChildItem "\\$PATH" -Recurse | Where {$_.creationtime -lt (Get-Date).AddDays($time)} | Remove-Item -Include $filename -Force 

$ Time确定文件删除前的年龄。 $ filename是确切的文件名,无论它叫什么。