使用 Powershell 批量更改 AD 对象的主文件夹路径 - %username”?

使用 Powershell 批量更改 AD 对象的主文件夹路径 - %username”?

我对此进行了大量搜索,但仍然找不到答案。

我创建了一个脚本,它将一个 OU 中的所有用户对象批量移动到另一个 OU。这很好用。现在我试图批量更改这些用户的 Home Folder 路径(和驱动器号)。到目前为止,我可以让脚本正确地更改路径/驱动器号,但我无法让它将用户的登录名添加到路径末尾(\server\share\username)。用户的 Home Folder 以他们的登录名命名。通常,我们会单独执行此操作,只需将 \server\share\%username% 放在 AD 中的 Home Folder 路径中,但 %username% 似乎不是 Powershell 的选项。如果我将“%username%”添加到路径末尾,AD 路径将如下所示 - \server\share\%username%(用户的名称显示为“%username%”,而不是他们的实际登录名)。我尝试了多种方法来实现这一点(变量、$_.SamAccountName 等),但到目前为止,都没有成功。

到目前为止,这是我的脚本……

#This script will move objects from one OU to another and set AD Home folder path.

Clear-Host
write-host "This script will move objects from one OU to another and set AD Home folder path." -ForegroundColor Magenta

start-sleep -s 2
#Global Variables
$global:path = "OU=users,OU=IT,"dc=contoso,dc=com"
$domain = "dc=contoso,dc=com"

do
{

# Operator Variables.
$rootOUsource  = read-host "What is the SOURCE root OU name?"
$deptnamesource = read-host "What is the SOURCE department name?"

write-host "Retrieving user objects...." -ForegroundColor Magenta
start-sleep -s 1

#Retrieve object info.
Get-ADUser -Filter * -SearchBase "OU=$deptnamesource,OU=users,OU=$rootOUsource,$domain"
# Operator Variables.
$divnametarget = read-host "What is the TARGET division name?"
$deptnametarget = read-host "What is the TARGET department name?"

#Object/target variables
$users = Get-ADUser -Filter * -SearchBase "OU=$deptnamesource,OU=users,OU=$rootOUsource,$domain"
$targetOU = "OU=$deptnametarget,OU=$divnametarget,$path"
#Move object/s.
foreach ($user in $users) {
    Move-ADObject $user -TargetPath $targetOU

}
#THIS PART DOES NOT WORK CORRECTLY...
#Set AD Home Folder path and create/permission folder.
$newusers = Get-ADUser -Filter * -SearchBase $targetou
foreach ($newuser in $newusers) {
    set-aduser $newuser -homedirectory "\\server\share\users\%username%" -homedrive H:

}

#Repeat process option.
write-host "All objects have been moved." -ForegroundColor Magenta
$choice = read-host "Do you want to move more objects?"
$choice = $choice.toupper()


}
while ($choice -eq "Y")

是否有 %username% 的“替代品”可以同时供一群用户使用?

答案1

我周一就做了这件事。下面是我使用的脚本,显然是为了在这里发布而修改的。你要找的%username%$_.SamAccountName

Get-ADUser -SearchBase "OU=Users,OU=[site],DC=[company],DC=[tld]" | % { Set-ADUser $_ -HomeDrive "H:" -HomeDirectory ('\\[dfs root]\[remote site name]\Users\' + $_.SamAccountName) }

(是的,这确实会提示输入过滤值,因为我们的用户 OU 中不仅仅有用户。 如果你想消除它,你可以将其添加-Filter *到那里。)

答案2

你是对的!$_.SamAccountName才是应该走的路。

仅供参考。我在下面找到了这个,它对我有用。它看起来和你的例子很相似。谢谢!


#Set AD Home Folder path.
Get-ADUser -Filter * -SearchBase $targetou | Foreach-Object {
    $sam = $_.SamAccountName
    Set-ADuser -Identity $_ -HomeDrive "H:" -HomeDirectory "\\server\share\$sam"
}

相关内容