我对Powershell来说相当新,但到目前为止,我们已经将一个删除早于定义的创建日期的文件并排除某些文件类型的脚本组合在一起。但是,我很难将verbose和文件记录输出结合起来。我尝试过各种在网上找到的方法,我认为Out-File是最合适的,但我根本无法使其正常工作。希望有人可以提供帮助!
Set-StrictMode -Version Latest
# $Logfile = "C:\Temp\Log.log"
function Remove-Files([parameter(Mandatory=$true)][ValidateScript({Test-Path $_})][string] $Path, [parameter(Mandatory=$true)][DateTime] $DateTime, [switch] $WhatIf)
{
Get-ChildItem -Path $Path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $DateTime -and ($_.Name -notlike "*.txt"-and $_.Name -notlike "*.log")} |
# Out-File -filepath $logfile -append
ForEach-Object { Remove-Item -Path $_.FullName -Force -WhatIf:$WhatIf}
}
Remove-Files -Path "C:\Temp" -DateTime ((Get-Date).AddDays(-10)) # -whatif
答案 0 :(得分:4)
您没有向日志文件发送任何内容。
取消注释$logfile
声明,并将其用作例如:
ForEach-Object {
Remove-Item -Path $_.FullName -Force -WhatIf:$WhatIf
"Removed $($_.FullName)" | Out-File -FilePath $logfile -Append
}
答案 1 :(得分:4)
在删除文件之前,您只需要Tee-Object
这些文件。比如,只是用Out-File
替换你的Tee-Object
:
function Remove-Files {
[CmdletBinding()]
param(
[parameter(Mandatory=$true)]
[ValidateScript({Test-Path $_})]
[string]$Path,
[parameter(Mandatory=$true)]
[DateTime]$DateTime,
# Personally, I would pass the log file as a parameter
# [string]$LogFile,
[switch]$WhatIf
)
Get-ChildItem -Path $Path -Recurse -Force |
Where-Object {
!$_.PSIsContainer -and
$_.CreationTime -lt $DateTime -and
($_.lName -notlike "*.txt" -and $_.Name -notlike "*.log")
} |
Tee-Object -Filepath $LogFile -Append |
Remove-Item -Force -WhatIf:$WhatIf
}
Remove-Files -Path "C:\Temp" -Log "C:\Temp\Rm.log" -DateTime ((Get-Date).AddDays(-10))
唯一的问题是:
-Whatif
使其不删除,但不会停止日志)答案 2 :(得分:1)
这是我更新的代码,可以让日志记录正常运行..
function Remove-FilesCreatedBeforeDate([parameter(Mandatory=$true)][ValidateScript({Test-Path $_})][string] $Path, [parameter(Mandatory=$true)][DateTime] $DateTime, [string]$LogFile = "C:\Temp\Log.log", [switch] $WhatIf)
{
"LOG START $(Get-Date –f "yyyy-MM-dd HH:mm:ss")" | Out-File -FilePath $logfile -Append
Get-ChildItem -Path $Path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $DateTime -and ($_.Name -notlike "*.txt"-and $_.Name -notlike "*.log")} |
ForEach-Object { Remove-Item -Path $_.FullName -Force -WhatIf:$WhatIf
"$(Get-Date –f o) Removed $($_.FullName)" | Out-File -FilePath $logfile -Append | Write-host "Removed $($_.FullName)"}
"LOG END $(Get-Date –f "yyyy-MM-dd HH:mm:ss")" | Out-File -FilePath $logfile -Append
}
Remove-FilesCreatedBeforeDate -Path "C:\Temp" -DateTime ((Get-Date).AddDays(-0))
答案 3 :(得分:0)
前段时间我创建了一个Log-Entry
framework,您可以在其中执行内联日志记录,如:
Remove-Item -Path (Log "Removing:" $_.FullName ?) -Force -WhatIf:$WhatIf