我正在尝试编写一个搜索的脚本:
执行搜索后,我希望删除所有1和2以及父文件夹(如果它们不匹配)。这是我到目前为止所拥有的:
#Define list of computers to search for the files and folders in question
$ComputerList = Get-Content -Path "C:\computers.txt"
#Define a function for searching files and folders based on criteria:
function search {
PROCESS {
$srcFolder ="C:\test"
Get-ChildItem $srcFolder -ErrorAction SilentlyContinue -recurse -Force | Where-Object {`
$_.Name -eq “keyword1” -or`
$_.Name -eq “keyword2” -or`
-and $_.fullname -notmatch 'C:\\Windows'`
-and $_.fullname -notmatch 'C:\\Program Files'
} | foreach-object -process { _.FullName }
}
}
foreach ($strComputer in $ComputerList)
{
#Perform the search function on all the computers listed
foreach ($objItem in $colItems)
{
write-host "-------------------------$strComputer ----------------" -foregroundcolor "red"
write-host " Files Found " -foregroundcolor "yellow" -backgroundcolor "black"
$ComputerList | search
"Number of files and folders found: " +($ComputerList | search | Measure-Object | Select-Object -ExpandProperty Count)
write-host "------------------------------------------------------------------" -foregroundcolor "red"
}
if (($ComputerList | search).count -lt 1) {
write-host "No files found to delete"
}
else {
#Prompt if you want to delete the files
write-host "Do you want to delete these files?" -foregroundcolor "yellow" -backgroundcolor "black"
$ComputerList | search | Remove-Item -Force -confirm
}
}
Out-File -FilePath C:\results.txt
以下是我遇到的问题:
我可以让脚本工作。但是,我不确定如何在保护被排除的文件夹的同时删除父文件夹。
文件的输出无效。文件被创建,但它是空白的。为什么呢?
在查看Get-ChildItem | Get-Member
之后,我意识到Parent属性是由System.IO.DirectoryInfo Parent指定的,所以如果我可以将它添加到要删除的项列表中,那么它应该可以工作。
文件夹结构如下。为了以更清晰的方式重申,我想删除一个文件夹:
以下是普通网址:
oi42.tinypic.com/2nulmz4.jpg
oi43.tinypic.com/fwlxd0.jpg
oi42.tinypic.com/315hdw9.jpg
答案 0 :(得分:1)
你可以保持简单:
$folder = "C:\pst"
$excludedFolders = "c:\Windows", "c:\PST\new"
$itemsFromFolder = get-childitem $folder -recurse
$itemsToDelete = New-Object System.Collections.Generic.List[string]
foreach ($item in $itemsFromFolder)
{
$exclude = $false
foreach ($exclusion in $excludedFolders)
{
if ($item.FullName.ToLower().StartsWith($exclusion.ToLower()))
{
$exclude = $true
}
}
if (!$exclude)
{
$itemsToDelete.Add($item.FullName)
}
}
如您所见,您可以定义需要预先排除的文件夹,然后对所有项目进行排序,过滤掉应保留的目录。然后,您还可以使用Remove-Item:
排除某些路径或扩展名Remove-Item c:\scripts\* -include *.txt -exclude *test*