我试图创建一个PowerShell脚本,它将列出包含文件和子目录的所有目录,这些脚本在90天内未被修改。我不是一个经验丰富的脚本编写者,所以我四处搜索并找到了下面的脚本。
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objStartFolder = objFSO.GetFolder("C:\Scripts")
Set colFiles = objStartFolder.Files
i = 0
For Each objFile in colFiles
dtmDate = objFile.DateLastModified
intAge = DateDiff("d", dtmDate, Date)
If intAge < 90 Then
i = 1
Exit For
End If
Next
If i = 0 Then
Wscript.Echo objStartFolder.Path
End If
ShowSubfolders(objStartFolder)
Sub ShowSubFolders(Folder)
For Each objSubfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(objSubFolder.Path)
Set colFiles = objFolder.Files
i = 0
For Each objFile in colFiles
dtmDate = objFile.DateLastModified
intAge = DateDiff("d", dtmDate, Date)
If intAge < 90 Then
i = 1
Exit For
End If
Next
If i = 0 Then
Wscript.Echo objSubfolder.Path
End If
ShowSubFolders objSubfolder
Next
End Sub
太棒了,所以我在我的Windows系统上运行它,但它返回以下错误:
Missing opening '(' after keyword 'for'.
At F:\find.ps1:8 char:5
+ For <<<< Each objFile in colFiles
+ CategoryInfo : ParserError: (OpenParenToken:Token
+ FullyQualifiedErrorId : MissingOpenParenthesisAfterKeyword
我玩过它,猜测如何/在哪里添加&#34;(&#34;但我真的无法到达任何地方。
答案 0 :(得分:2)
使用Get-ChildItem
cmdlet在PowerShell中可以更加简洁:
递归:
$Filter = {$_.LastWriteTime -lt (Get-Date).AddDays(-90)}
$OldStuff = Get-ChildItem "C:\your\base\dir" -File -Recurse | Where-Object $Filter
或者只是文件夹及其直接子文件夹(如示例所示):
$Filter = {$_.LastWriteTime -lt (Get-Date).AddDays(-90)}
$OldStuff = Get-ChildItem "C:\your\base\dir" -File | Where-Object $Filter
$OldStuff += Get-ChildItem "C:\your\base\dir" -Directory | ForEach-Object {
Get-ChildItem "C:\your\base\dir" -File | Where-Object $Filter
}
在2.0版中,Get-ChildItem
cmdlet没有-File
参数。您可以使用Where-Object
来测试该项目是否为文件夹(使用PsIsContainer
属性):
递归:
$Filter = {-not($_.PsIsContainer) -and ($_.LastWriteTime -lt (Get-Date).AddDays(-90))}
$OldStuff = Get-ChildItem "C:\your\base\dir" -Recurse | Where-Object $Filter
文件夹及其直接子文件夹:
$Filter = {-not($_.PsIsContainer) -and ($_.LastWriteTime -lt (Get-Date).AddDays(-90))}
$OldStuff = Get-ChildItem "C:\your\base\dir" | Where-Object $Filter
$OldStuff += Get-ChildItem "C:\your\base\dir" |Where-Object {$_.PsIsContainer}| ForEach-Object {
Get-ChildItem "C:\your\base\dir" | Where-Object $Filter
}