gpt4 book ai didi

powershell - PowerShell删除更快

转载 作者:行者123 更新时间:2023-12-03 00:08:35 25 4
gpt4 key购买 nike

我有一个PowerShell脚本,该脚本以递归方式删除所有文件和文件夹,但排除了某些文件夹,因为它们不应被删除。
它可以100%工作,但是我的问题是性能。我需要它来加快运行速度。

关于如何使其更快的任何想法?

Write-Host "Purging $InstallationDirectorySite - Deleting files..."

$FolderExlusions = (
"App_Data",
"Logs",
"TEMP",
"ExamineIndexes",
"DistCache",
"GitPathProviderRepository"
)

[regex] $files_regex = "Logs|ExamineIndexes|DistCache*|GitPathProviderRepository*"

if(Test-Path $InstallationDirectorySite) {
Get-ChildItem -Path $InstallationDirectorySite -Recurse -Exclude $FolderExlusions |
Where-Object {$_.FullName -notmatch $files_regex} |
Remove-Item -Recurse
}
else {
Write-Output "$InstallationDirectorySite doesn't exist"
}

最佳答案

实际上,您两次过滤了排除的文件夹。
第一次使用-Exclude参数,第二次使用Regex -match
但是,Exclude参数采用字符串数组,而不是使用从“here-string”中获得的带有逗号和换行符分隔的关键字的单个字符串。
参见Get-ChildItem

另外,您使用的正则表达式是错误的,因为正则表达式中的星号*是一个量词,而不是通配符。

我建议您使用这样的-Exclude参数过滤一次(此处的星号是通配符):

$FolderExlusions = "App_Data","Logs","TEMP","ExamineIndexes","DistCache*","GitPathProviderRepository*"
Get-ChildItem -Path $InstallationDirectorySite -Recurse -Exclude $FolderExlusions | Remove-Item -Recurse -WhatIf

或者像这样在 Where-Object子句中仅使用regex方法:
$FolderExlusions = "^(App_Data|Logs|TEMP|ExamineIndexes|DistCache.*|GitPathProviderRepository.*)"
Get-ChildItem -Path $InstallationDirectorySite -Recurse | Where-Object { $_.Name -notmatch $FolderExlusions } | Remove-Item -Recurse -WhatIf

如果您对结果满意,请删除 -WhatIf

希望能有所帮助

关于powershell - PowerShell删除更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55098136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com