【问题标题】:PowerShell Change owner of files and foldersPowerShell 更改文件和文件夹的所有者
【发布时间】:2020-06-18 14:45:37
【问题描述】:

在网上搜索,我发现了 2 个能够更改文件和文件夹所有者的脚本。对此进行测试时,它在 PowerShell 1.0 中完美运行。现在我正在尝试将两者结合起来,以便它们递归地工作,因为我们的文件夹中有超过 500 个子目录和文件。这是一项艰巨的工作..

我们希望:

  • 在\\server\C$\Folder 上运行一个脚本(不使用外部工具)
  • 将所有文件和子文件夹的所有者更改为BUILTIN\Administrators

问题:

  • 每个脚本仅适用于 1 个文件或 1 个文件夹。如何将其组合在一个脚本中,以便将所有子文件夹和文件一起处理?可能将其放入 2 个不同的函数中并循环遍历它,或者..

Script1:将文件所有者更改为管理员

$File = "\\server\c$\Users\dir\Downloads\Target\TargetFile.txt"
$Account = New-Object System.Security.Principal.NTAccount("BUILTIN\Administrators")
$FileSecurity = new-object System.Security.AccessControl.FileSecurity
$FileSecurity.SetOwner($Account)
[System.IO.File]::SetAccessControl($File, $FileSecurity)

Script2:将文件夹所有者更改为管理员

$AdjustTokenPrivileges = @"
using System;
using System.Runtime.InteropServices;

 public class TokenManipulator
 {
  [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
  internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
  ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
  [DllImport("kernel32.dll", ExactSpelling = true)]
  internal static extern IntPtr GetCurrentProcess();
  [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
  internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr
  phtok);
  [DllImport("advapi32.dll", SetLastError = true)]
  internal static extern bool LookupPrivilegeValue(string host, string name,
  ref long pluid);
  [StructLayout(LayoutKind.Sequential, Pack = 1)]
  internal struct TokPriv1Luid
  {
   public int Count;
   public long Luid;
   public int Attr;
  }
  internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
  internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
  internal const int TOKEN_QUERY = 0x00000008;
  internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
  public static bool AddPrivilege(string privilege)
  {
   try
   {
    bool retVal;
    TokPriv1Luid tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_ENABLED;
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    return retVal;
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }
  public static bool RemovePrivilege(string privilege)
  {
   try
   {
    bool retVal;
    TokPriv1Luid tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_DISABLED;
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    return retVal;
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }
 }
"@
add-type $AdjustTokenPrivileges
$Folder = Get-Item "C:\Users\dir\Downloads\Target"
[void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") 
[void][TokenManipulator]::AddPrivilege("SeBackupPrivilege") 
[void][TokenManipulator]::AddPrivilege("SeTakeOwnershipPrivilege") 
$NewOwnerACL = New-Object System.Security.AccessControl.DirectorySecurity
$Admin = New-Object System.Security.Principal.NTAccount("BUILTIN\Administrators")
$NewOwnerACL.SetOwner($Admin)
$Folder.SetAccessControl($NewOwnerACL)

【问题讨论】:

  • 我建议手动执行此操作。在 Windows 8 中,您可以进入文件夹属性、安全选项卡、高级按钮、“更改”所有者链接,提供新所有者并点击确定,选中“替换子容器和对象的所有者”复选框,点击应用。这比尝试使用 PowerShell 更快、更安全。
  • 运行 cmd.exe 命令对我来说是一个更简单的解决方案。 takeown.exe /F $dest /R 将我的当前用户设置为所有文件和子目录的所有者,icacls $dest /t /grant "Everyone:(F)" 授予每个人的完全访问权限。 $dest 变量具有目标目录路径。 Powershell 以管理员身份运行。这适用于本地文件夹,例如:c:\myfolder,但我还没有测试它们的远程服务器路径\\server\C$\Folder

标签: powershell


【解决方案1】:

您可以对文件夹使用SetOwner() 方法,就像对文件一样。

# Define the owner account/group
$Account = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList 'BUILTIN\Administrators';

# Get a list of folders and files
$ItemList = Get-ChildItem -Path c:\test -Recurse;

# Iterate over files/folders
foreach ($Item in $ItemList) {
    $Acl = $null; # Reset the $Acl variable to $null
    $Acl = Get-Acl -Path $Item.FullName; # Get the ACL from the item
    $Acl.SetOwner($Account); # Update the in-memory ACL
    Set-Acl -Path $Item.FullName -AclObject $Acl;  # Set the updated ACL on the target item
}

【讨论】:

  • 这不起作用,因为 PowerShell 本身无法设置所有者,因为权限丢失。这就是为什么我需要使用上面找到的脚本。我尝试了您的建议,但出现错误:“Set-Acl:尝试执行未经授权的操作。在 .. Set-Acl
  • 这对我也不起作用 - Attempted to perform an unauthorized operation
  • 它确实有效,有些人访问被拒绝的原因是 PowerShell 命令没有以管理员身份运行,而是试图使用被 Windows UAC 阻止的“BUILTIN\Administrator”。用普通账户试一下,就可以了。
  • 非常适合我,谢谢! (Windows 10,提升的 Powershell 控制台)
  • 它确实在任何地方都可以在提升的提示下工作。确保使用Set-Acl 而不是(Get-Item $Path).SetAccessControl($Acl)
【解决方案2】:

在使用 PowerShell 一周后,我找到了自己问题的答案:

$Target = "\\domain.net\myFolder"
$TempFolder = 'C:\TempFolder'
$TempFile = 'C:\TempFile'

#region Load super powers
$AdjustTokenPrivileges = @"
using System;
using System.Runtime.InteropServices;

 public class TokenManipulator
 {
  [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
  internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
  ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
  [DllImport("kernel32.dll", ExactSpelling = true)]
  internal static extern IntPtr GetCurrentProcess();
  [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
  internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr
  phtok);
  [DllImport("advapi32.dll", SetLastError = true)]
  internal static extern bool LookupPrivilegeValue(string host, string name,
  ref long pluid);
  [StructLayout(LayoutKind.Sequential, Pack = 1)]
  internal struct TokPriv1Luid
  {
   public int Count;
   public long Luid;
   public int Attr;
  }
  internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
  internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
  internal const int TOKEN_QUERY = 0x00000008;
  internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
  public static bool AddPrivilege(string privilege)
  {
   try
   {
    bool retVal;
    TokPriv1Luid tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_ENABLED;
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    return retVal;
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }
  public static bool RemovePrivilege(string privilege)
  {
   try
   {
    bool retVal;
    TokPriv1Luid tp;
    IntPtr hproc = GetCurrentProcess();
    IntPtr htok = IntPtr.Zero;
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
    tp.Count = 1;
    tp.Luid = 0;
    tp.Attr = SE_PRIVILEGE_DISABLED;
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
    return retVal;
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }
 }
"@
Add-Type $AdjustTokenPrivileges
[void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") 
[void][TokenManipulator]::AddPrivilege("SeBackupPrivilege") 
[void][TokenManipulator]::AddPrivilege("SeTakeOwnershipPrivilege") 
#endregion

$BuiltinAdmin = New-Object System.Security.Principal.NTAccount("BUILTIN\Administrators")
$BuiltinAdminFullControlAcl = New-Object System.Security.AccessControl.FileSystemAccessRule($BuiltinAdmin,"FullControl","Allow")

#region Create temp folder with Admin owner and full control
$FolderBuiltinAdminOwnerAcl = New-Object System.Security.AccessControl.DirectorySecurity
$FolderBuiltinAdminOwnerAcl.SetOwner($BuiltinAdmin)

Remove-Item $TempFolder -EA Ignore
New-Item -Type Directory -Path $TempFolder

$TempFolderAcl = Get-Acl -Path $TempFolder
$TempFolderAcl.SetAccessRule($BuiltinAdminFullControlAcl)
#endregion

#region Change folder owners to Admin
$Folders = @(Get-ChildItem -Path $Target -Directory -Recurse)

foreach ($Folder in $Folders) {
    $Folder.SetAccessControl($FolderBuiltinAdminOwnerAcl)
    Set-Acl -Path $Folder -AclObject $TempFolderAcl
}
#endregion

#region Create temp file with Admin owner and full control
$FileBuiltinAdminOwnerAcl = New-Object System.Security.AccessControl.FileSecurity
$FileBuiltinAdminOwnerAcl.SetOwner($BuiltinAdmin)

Remove-Item $TempFile -EA Ignore
New-Item -Type File -Path $TempFile

$TempFileAcl = Get-Acl -Path $TempFile
$TempFileAcl.SetAccessRule($BuiltinAdminFullControlAcl)
#endregion

#region Change file owners to Admin
$Files = @(Get-ChildItem -Path $Target -File -Recurse)

foreach ($File in $Files) {
    $File.SetAccessControl($FileBuiltinAdminOwnerAcl)
    Set-Acl -Path $File -AclObject $TempFileAcl
}
#endregion

#region Clean-up
Remove-Item $TempFile, $TempFolder
#endregion

再次感谢大家的帮助。希望其他人可以从我的 PowerShell 研究中受益。剩下的唯一想法就是让它变得更冗长,但那是另一天的事了。它会做它需要做的事情,并且在权限确实混乱的最恶劣条件下。

【讨论】:

  • 谢谢!我在一个新驱动器上安装了 Windows,并获得了一些内置的 takeown 实用程序无法修复的权限。你太棒了!
  • 我正在使用这个解决方案,我发现[void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") 仅用于将所有者设置为不是您自己的人的附加信息。我能够完全避免使用[void][TokenManipulator]::AddPrivilege("SeBackupPrivilege")。很好的答案!
猜你喜欢
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 2015-03-25
  • 2018-07-28
  • 2013-11-13
相关资源
最近更新 更多