Powershell:在删除之前抓取目录的名称

时间:2014-09-17 19:27:07

标签: powershell

我想获取目录的名称并在删除之前将其写入日志文件。这是我到目前为止所拥有的,

$limit = (Get-Date).AddDays(0)
$path = "C:\STest\Videos\"
$logFile = "C:\STest\Log\log.txt"

# Delete folders older than the $limit.
$file = Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and       $_.CreationTime -lt $limit } | Remove-Item -Recurse -Force
Write-Host $file

#Log what we've done
#Add-Content -Path $strLogFile -Value "$(Get-Date) deleted $file"

我尝试过像这样添加-Name:

$file = Get-ChildItem -Path $path -Recurse -Force -name | Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Recurse -Force

脚本运行但$ file不保存任何信息。我认为-Name就是我想要的,我只是在错误的地方使用它。

2 个答案:

答案 0 :(得分:2)

另一种方法是使用Tee-Object例如:

Get-ChildItem -Path $path -Recurse -Force | 
     Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit } |
     Foreach {$_.FullName} | Tee-Object -FilePath $LogFile | Remove-Item -Recurse -Force

此外,如果您使用的是V3或更高版本,则可以简化为:

Get-ChildItem -Path $path -Recurse -Force -Directory | 
     Where CreationTime -lt $limit |
     Foreach FullName | Tee-Object -FilePath $LogFile | Remove-Item -Recurse -Force

此外,根据您希望文件在日志中的显示方式,您可以进一步简化:

Get-ChildItem -Path $path -Recurse -Force -Directory | 
     Where CreationTime -lt $limit |
     Tee-Object -FilePath $LogFile | Remove-Item -Recurse -Force

答案 1 :(得分:1)

问题是你正在使用没有输出的Remove-Item。把它分开:

$limit = (Get-Date).AddDays(0)
$path = "C:\STest\Videos\"
$logFile = "C:\STest\Log\log.txt"

# Delete folders older than the $limit.
$file = Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and       $_.CreationTime -lt $limit }
$file | Remove-Item -Recurse -Force
$file | Select -Expand FullName | Out-File $LogFile -append