Powershell:如何将ADUser转换为IdentityReference?

时间:2017-04-11 16:18:00

标签: powershell active-directory acl directory

我正在尝试在文件夹上设置所有者,但我一直遇到问题。这是我目前的脚本。我试图解析共享下的所有文件夹,并根据文件夹的名称将文件夹的所有者设置为相应的ADUser。文件夹名称为SAMAccountNames。

Import-Module ActiveDirectory

$path = Get-ChildItem F:\AppData\*\ | ?{ $_.PSIsContainer }
ForEach ($folder in $path) {
    $ACL = get-acl $folder
    $username = $folder.Name
    $userobject = Get-ADUser $username
    $ACL.SetOwner($userobject)
    Set-Acl $folder.FullName $ACL
    Write-Host $username
}

我得到的错误是:

  

无法将参数“Identity”与值(在此处插入专有名称)转换为“SetOwner”类型System.Security.Principal.IdentityReference

有什么更好的方法可以做到这一点?

2 个答案:

答案 0 :(得分:0)

假设这是一个域,您可以使用用户的samaccountname创建一个System.Security.Principal.NTAccount对象,该对象可以使用.SetOwner()方法。

$userobject = Get-ADUser $folder.Name
$ACL.SetOwner(New-Object System.Security.Principal.NTAccount("bagel", $userobject.samaccountname))

正如您所发现的那样,用户可能不存在,因此您需要对其进行说明以减少将来的错误。一种简单的方法是检查Get-Aduser

的结果
$userobject = Get-ADUser $folder.Name -ErrorAction SilentlyContinue
if($userobject){
    # Found it. Do stuff
} else {
    # Could not find it. Do different stuff
}

注意即可。如果让用户因任何原因而失败,则会触发其他操作。 DC不可用,找不到用户,权限错误等。

如果您想要更多控制权,那么您可以尝试try / catch寻找特定错误等。

try{
    Get-ADUser "cantpossiblyexist"
} catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]{
    "No. Mr. User not here"
}

答案 1 :(得分:0)

感谢Matt对他的一些帮助,但答案最终有所不同。这是最终的工作产品。

  

重要说明:脚本必须从另一台计算机运行,最好是Windows 2012或更高版本,否则您将收到错误消息"安全标识符不允许是此对象的所有者。&#34 ;

$path = Get-ChildItem \\COMPUTERNAME\SHARENAME\* | ?{ $_.PSIsContainer }
ForEach ($folder in $path) {
    $ACL = (get-item $folder.FullName).GetAccessControl('Owner')
    $username = $folder.Name
    $userobject = New-Object System.Security.Principal.NTAccount("NTDOMAIN", $username)
    $AccessRule1 = New-Object  system.security.accesscontrol.filesystemaccessrule("CREATOR OWNER","FullControl","ContainerInherit, ObjectInherit","InheritOnly","Allow")
    $AccessRule2 = New-Object  system.security.accesscontrol.filesystemaccessrule("Domain Admins","FullControl","ContainerInherit, ObjectInherit","InheritOnly","Allow")
    $AccessRule3 = New-Object  system.security.accesscontrol.filesystemaccessrule($userobject,"FullControl","ContainerInherit, ObjectInherit","InheritOnly","Allow")

    try {
        $ACL.SetOwner($userobject)
        $ACL.AddAccessRule($AccessRule1)
        $ACL.AddAccessRule($AccessRule2)
        $ACL.AddAccessRule($AccessRule3)
        Set-Acl $folder.FullName $ACL
        Write-Host $username
    }
    catch {
        #Delete folder if user is not found.
        Remove-Item $folder -recurse -force
        Write-Host $username "CANNOT BE FOUND"
    }
}