我正在编写一个脚本,通过PowerShell自动创建用户帐户。其中一部分是为新用户建立电子邮件地址。我们将邮箱(或多或少)均匀地分布在3个数据库上:Default01,Default02和Default03。
要确定帐户数量最少的数据库,我会计算当前的统计数据。
function Get-MDBMailboxCount ([string]$DN) {
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://$(([system.directoryservices.activedirectory.domain]::GetCurrentDomain()).Name)")
$Searcher.Filter = "(&(objectClass=user)(homeMDB=$DN))"
$Searcher.PageSize = 10000
$Searcher.SearchScope = "Subtree"
$results = $Searcher.FindAll()
$returnValue = $results.Count
#dispose of the search and results properly to avoid a memory leak
$Searcher.Dispose()
$results.Dispose()
return $returnValue
}
$Databases = (Get-MailboxDatabase) Where {$_.Name -like 'Default*'} | Select-Object Name, @{Name="Count";Expression={Get-MDBMailboxCount -DN $_.DistinguishedName}} | Sort-Object count
}
这将返回一个对象$ databases,其列为名称和计数。然后我提取具有最低计数的DB。
$DB = $Databases |Sort-Object Count |Select-Object -First 1
到目前为止一切都很好:)但由于我的脚本可以一次创建多个帐户,所以每次在$ databases对象中创建用户时都要更新计数器。 (我不想再次运行该功能,因为它可能需要几秒钟才能处理)。我可以像这样更新对象:
($databases | Where {$_.Name -eq $($DB.Name)}).Count = $NewCount
但我想知道是否有更简单的方法来更新Powershell对象中的元素。像
这样的东西$Databases["Default01"].Count = $NewCount
这样的事情可能吗?或者没有其他/更好的方法来更新对象中的元素吗?
获取Get-MDBMailboxCount函数的信用 link
答案 0 :(得分:0)
如果您已经有对当前数据库对象的引用,那么只需直接更新其Count
属性即可。语法为$DB.Count = <new value>
或$DB.Count += <amount to add>
$databases = <do expensive get operation, get initial counts>
foreach($newUser in $userList)
{
$DB = $databases | Sort-Object Count | Select-Object -First 1
< go add users to the particular $DB, keep track of how many new users >
$DB.Count += $numNewUsers # or $DB.Count = $totalUserCount, whatever you like
}
$DB
是指向$databases
数组中相同底层对象的引用。因此,当您设置$DB.Count
时,它也会更新$databases
中的正确元素,并且下次对数组进行排序时,它将使用新计数。