如何使用WMI更改文件权限?

我想要做的是相当于这里描述的脚本。 基本上,我想取得文件的所有权,并将权限设置为OWNER /完全控制。

在我看来,从VBS脚本使用WMI是最便携的方式。 也就是说,我想避免xcacls,icacls和其他工具,要么下载,要么只支持某些版本的Windows

search后,我发现这个代码取得所有权:

'connect to WMI namespace on local machine Set objServices = GetObject("winmgmts:{impersonationLevel=impersonate}") 'get a reference to data file strFile = Wscript.Arguments(0) Set objFile = objServices.Get("CIM_DataFile.Name='" & strFile & "'") If objFile.TakeOwnership = 0 Then Wscript.Echo "File ownership successfully changed" Else Wscript.Echo "File ownership transfer operation" End If 

我仍然缺less的部分是设置权限,并使其工作在相对path。

Solutions Collecting From Web of "如何使用WMI更改文件权限?"

由于您已经在CIM_DataFile类中使用了CIM_DataFile ,我假设您可以使用ChangeSecurityPermissions来更改权限,这是在同一个类中。

在使用它们之前,您可以使用GetAbsolutePathName将相对路径转换为绝对路径。

从ho1的回答中得知,我搜索了一些,最终得出这个结论:

此脚本查找当前用户的SID,然后获取所有权并将argv [0]中给出的文件的权限仅更改为当前用户的完全控制。

 Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}") Function GetCurrentUserSID ' Get user name ' Set colComputer = objWMI.ExecQuery("Select * from Win32_ComputerSystem") ' Looping over one item ' For Each objComputer in colComputer currentUserName = objComputer.UserName Next Set AccountSIDs = GetObject("Winmgmts:").InstancesOf("Win32_AccountSID") For Each AccountSID In AccountSIDs AccountKey = AccountSID.Element Set objAccount = GetObject("Winmgmts:"+AccountKey) strName = objAccount.Domain & "\" & objAccount.Name If strName = currentUserName Then ' that's it SIDKey = AccountSID.Setting Set SID = GetObject("Winmgmts:" + SIDKey) GetCurrentUserSID = SID.BinaryRepresentation Exit For End If Next End Function Function LimitPermissions(path, SID) Set objFile = objWMI.Get("CIM_DataFile.Name='" & path & "'") Set Trustee = GetObject("Winmgmts:Win32_Trustee").SpawnInstance_ Trustee.SID = SID Set ACE = getObject("Winmgmts:Win32_Ace").Spawninstance_ ACE.AccessMask = 2032127 ' Full Control ACE.AceFlags = 3 ACE.AceType = 0 ACE.Trustee = Trustee Set objSecDescriptor = GetObject("Winmgmts:Win32_SecurityDescriptor").SpawnInstance_ objSecDescriptor.DACL = Array(ACE) objFile.ChangeSecurityPermissions objSecDescriptor, 4 End Function Function TakeOwnership(path) Set objFile = objWMI.Get("CIM_DataFile.Name='" & path & "'") TakeOwnership = objFile.TakeOwnership End Function ' Main ' strFilename = Wscript.Arguments(0) Set fso = CreateObject("Scripting.FileSystemObject") path = fso.GetAbsolutePathName(strFilename) SID = GetCurrentUserSID TakeOwnership path LimitPermissions path, SID