我正在尝试清除DFS共享上的一些孤立用户共享。我想使用HomeDirectory
将文件夹的全名与指定对象的Get-ADUser -Filter
属性进行比较。
如果我使用例如(Get-ADUser $varibale -Properties * | Select Homedirectory)
,则在找不到帐户时会显示错误。因此,如果找不到帐户,我会使用-Filter
来隐藏错误。但是,这比-Properties * | Select
方法慢得多。
脚本:
$path = Read-Host -Prompt "Share path...."
$Dirs = Get-ChildItem $Path
foreach ($D in $Dirs) {
$Login = Get-ADUser -Filter {HomeDirectory -eq $d.FullName}
if ($d.FullName -ne $Login."HomeDirectory") {
$host.UI.RawUI.WindowTitle = "Checking $d..."
$choice = ""
Write-Host "Comparing $($d.FullName)......." -ForegroundColor Yellow
$prompt = Write-Host "An account with matching Home Directory to $($d.FullName) could not be found. Purge $($d.fullname)?" -ForegroundColor Red
$choice = Read-Host -Prompt $prompt
if ($choice -eq "y") {
function Remove-PathToLongDirectory {
Param([string]$directory)
# create a temporary (empty) directory
$parent = [System.IO.Path]::GetTempPath()
[string] $name = [System.Guid]::NewGuid()
$tempDirectory = New-Item -ItemType Directory -Path (Join-Path $parent $name)
robocopy /MIR $tempDirectory.FullName $directory
Remove-Item $directory -Force
Remove-Item $tempDirectory -Force
}
# Start of Script to delete folders from User Input and Confirms
# the specified folder deletion
Remove-PathToLongDirectory $d.FullName
}
} else {
Write-Host "Done!" -ForegroundColor Cyan
}
Write-Host "Done!" -ForegroundColor Cyan
}
答案 0 :(得分:0)
你的代码中有一些次优的东西(比如(重新)在循环中定义一个函数,或者一遍又一遍地创建和删除一个空目录),但你最大的瓶颈可能是你做了一个AD查询对于每个目录。通过制作单个AD查询并将其结果存储在数组中,您应该能够大大加快代码的速度:
$qry = '(&(objectclass=user)(objectcategory=user)(homeDirectory=*)'
$homes = Get-ADUser -LDAPFilter $qry -Properties HomeDirectory |
Select-Object -Expand HomeDirectory
以便您可以检查是否存在具有给定主目录的帐户,如下所示:
foreach ($d in $dirs) {
if ($homes -notcontains $d.FullName) {
# ... prompt for deletion ...
} else {
# ...
}
}
性能方面在使用每个命令删除2 GB测试文件夹时,我没有注意到robocopy /mir
方法与Remove-Item
之间的区别。但是,如果您的length exceeds 260 characters路径robocopy
可能与Remove-Item
相关,那么$empty = Join-Path ([IO.Path]::GetTempPath()) ([Guid]::NewGuid())
New-Item -Type Directory -Path $empty | Out-Null
foreach ($d in $dirs) {
if ($homes -notcontains $d.FullName) {
# ... prompt for confirmation ...
if ($choice -eq 'y') {
# "mirror" an empty directory into the orphaned home directory to
# delete its content. This is used b/c regular PowerShell cmdlets
# can't handle paths longer than 260 characters.
robocopy $empty $d.FullName /mir
Remove-Item $d -Recurse -Force
}
} else {
# ...
}
}
Remove-Item $empty -Force
can't handle those。我建议添加一条注释来解释你使用该命令的内容,因为下一个阅读你脚本的人可能和我一样感到困惑。
cards = board.get_cards()
self.assertIn(Card(name="item6"), cards)
还有一个PowerShell module构建在AlphaFS库之上,据说可以处理长路径。我自己还没有使用它,但它可能值得一试。