一、文件夹遍历相关操作
清理某个目录下的子文件夹下的*.Log 文件
Get-ChildItem C:\inetpub\logs\LogFiles\ -recurse *.log |Remove-Item -Force
PowerShell遍历文件夹下的子文件夹和文件是一件很容易的事儿。Get-ChildItem这个cmdlet就有一个recurse参数是用于遍历文件夹的。
PowerShell中,使用Get-ChildItem来获取文件夹下面的子文件夹和文件(当然,它的功能不仅于此)。然后我们可以使用ForEach-Object的cmdlet来循环遍历下面的子对象。然后通过psiscontainer 属性来判断是文件夹还是文件。
Get-ChildItem,获取指定对象的所有子对象集合。
举例:
#获取D:\对象,返回值类型为System.IO.DirectoryInfo
Get-ChildItem D:\
#输出D:\下所有文件的文件名
Get-ChildItem D:\ | ForEach-Object -Process{
if($_ -is [System.IO.FileInfo])
{
Write-Host($_.name);
}
}
#列出今天创建的文件
Get-ChildItem D:\ | ForEach-Object -Process{
if($_ -is [System.IO.FileInfo] -and ($_.CreationTime -ge [System.DateTime]::Today))
{
Write-Host($_.name,$_.CreationTime);
}
}
#找出D盘根目录下的所有文件
Get-ChildItem d:\ | ?{$_.psiscontainer -eq $false}
如果要找文件夹,则把$false换成$true
二、删除目录内多余文件,目录文件个数大于$count后,按最后修改时间倒序排列,删除最旧的文件。
Sort-Object -Property LastWriteTime -Descending 按照文件的最后修改时间倒序排列
Select-Object -Skip $count 跳过开头的$count条数据,取剩余的数据
$count = 3 $filePathList = "E:\MySql\1", "E:\MySql\2", "E:\MySql\3" foreach($filePath in $filePathList) { $files = Get-ChildItem -Path $filePath | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip $count if ($files.count -gt 0) { foreach($file in $files) { Remove-Item $file.FullName -Recurse -Force } } }
三、删除目录内所有文件修改时间超过timeOutDay的文件。
$timeOutDay = 30 $filePath = "H:\DataBackup\File\1", "H:\DataBackup\Database\2" $allFile = Get-ChildItem -Path $filePath foreach($file in $allFile) { $daySpan = ((Get-Date) - $file.LastWriteTime).Days if ($daySpan -gt $timeOutDay) { Remove-Item $file.FullName -Recurse -Force } }