在权限组中添加用户的PowerShell有时无法正常工作. [英] PowerShell to add user in permission group does not work always.

查看:125
本文介绍了在权限组中添加用户的PowerShell有时无法正常工作.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的将用户添加到权限组的代码.

Below is my code to add the user to the permission group.

function SetUserIntoGroup{
	param([string]$WebUrl)
	$WebUrl
	$ADGroupName = "AD Group Name"
	$SPGroupName = "Project Owners"
	echo "Function Called"
	$site = Get-SPSite $WebUrl
	$web = $site.OpenWeb()
	$web.AllowUnsafeUpdates = $true

	try{

		$user = $web.EnsureUser($ADGroupName)
		$user.Name
		$user.LoginName
		if(@($web.SiteGroups.GetCollection(@($SPGroupName))).Count -eq 1){
			echo "Group Found"
			$SPGroup1 = $web.SiteGroups[$SPGroupName]
			$SPGroup1.Name
			# Check if user does not exist in group then only add to the group.
			$SPGroup1.AddUser($user)
			Write-Output "$user added to $SPGroup"
		}
	}
	catch [Exception]{
	  Write-Host $_.Exception.GetType().FullName, $_.Exception.Message -foregroundcolor "magenta"
	}
	finally{
		$web.AllowUnsafeUpdates = $false

		if($web){
		echo "Disposing web"
		$web.Dispose();
		}
		if($site){
		echo "Disposing site"
		$site.Dispose();
		}
	}
}




但是,当我运行代码时,它不会给我错误.有时将用户添加到权限组,有时不添加.当它不起作用时,我不知道确切的情况是什么.如果我多次运行,那么我会添加用户 到小组.

However, it does not give me the error when I run the code. It sometimes adds the user to the permission group and sometimes does not add. I can't figure out what is the exact scenario when it does not work. If I run multiple times then I get the user added to the group.

请帮助我解决问题.还有一件事,是代码编写得很好还是需要修改?

Please help me to solve the issue. One more thing, is the code written in good approach or needs to be modified?

TIA.





推荐答案

我们可以使用PowerShell的客户端对象模型来实现它.我已经测试过并且有效.

We can use client object model of PowerShell to achieve it. I have tested and it worked.

以下是一个简单的演示供您参考:

Here is a simple demo for your reference:

Import-Module 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.dll'


siteUrl ="http://sp/sites/DevSite"
siteUrl="http://sp/sites/DevSite"


groupName ="MyGroup2"
groupName="MyGroup2"


这篇关于在权限组中添加用户的PowerShell有时无法正常工作.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆