[方法] ユーザーとグループを操作する

最終更新日: 2011年4月29日

適用対象: SharePoint Foundation 2010

この記事の内容
SharePoint グループからすべてのユーザーを取得する
ユーザーの特定のプロパティを取得する
サイト コレクションのすべてのグループのすべてのユーザーを取得する
SharePoint グループにユーザーを追加する

SharePoint Online で使用可能

Microsoft.SharePoint.Client 名前空間 (JavaScript: SP) の Web サイト、リスト、およびリスト アイテムに適用されるデータ取得ロジックと同じものがユーザーおよびグループに適用されます。この名前空間の他のオブジェクトと同様に、CreationInformation オブジェクトを使用して、ユーザー オブジェクトまたはグループ オブジェクトを作成できます。

SharePoint グループからすべてのユーザーを取得する

Web クラス (JavaScript: Web) の SiteGroups プロパティ (JavaScript: siteGroups) は、サイト コレクション内のすべての Web サイトのすべてのグループを取得します。次の例で示すように、GetById(Int32) メソッド (JavaScript: getById(id)) を使用して、グループのコレクションから特定のグループを返すことができます。Group クラス (JavaScript: Group) の Users プロパティ (JavaScript: users) はグループ内のすべてのユーザーを取得します。次の例では、特定のグループのユーザーを読み込むため、各ユーザー オブジェクトのすべてのプロパティを使用できます。

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveAllUsersInGroup
    {
        static void Main()
        {
            ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            GroupCollection collGroup = clientContext.Web.SiteGroups;
            Group oGroup = collGroup.GetById(7);
            UserCollection collUser = oGroup.Users;

            clientContext.Load(collUser);

            clientContext.ExecuteQuery();

            foreach (User oUser in collUser)
            {
                Console.WriteLine("User: {0}  ID: {1} Email: {2} Login Name: {3}", 
                    oUser.Title, oUser.Id, oUser.Email, oUser.LoginName);
            }
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveAllUsersInGroup

        Shared Sub Main()
            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim collGroup As GroupCollection = clientContext.Web.SiteGroups
            Dim oGroup As Group = collGroup.GetById(7)
            Dim collUser As UserCollection = oGroup.Users

            clientContext.Load(collUser)

            clientContext.ExecuteQuery()

            Dim oUser As User
            For Each oUser In collUser
                Console.WriteLine("User: {0}  ID: {1} Email: {2} Login Name: {3}", _
                                  oUser.Title, oUser.Id, oUser.Email, oUser.LoginName)
            Next oUser

        End Sub        
    End Class
End Namespace
var siteUrl = '/sites/MySiteCollection ';

function retrieveAllUsersInGroup() {

    var clientContext = new SP.ClientContext(siteUrl);
    var collGroup = clientContext.get_web().get_siteGroups();
    var oGroup = collGroup.getById(7);
    this.collUser = oGroup.get_users();
    clientContext.load(collUser);


    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    var userInfo = '';

    var userEnumerator = collUser.getEnumerator();
    while (userEnumerator.moveNext()) {
        var oUser = userEnumerator.get_current();
        this.userInfo += '\nUser: ' + oUser.get_title() + 
            '\nID: ' + oUser.get_id() + 
            '\nEmail: ' + oUser.get_email() + 
            '\nLogin Name: ' + oUser.get_loginName();
    }
      
    alert(userInfo);
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

ユーザーの特定のプロパティを取得する

次の例は、前の例を変更して、特定のグループの各ユーザーのタイトルと電子メール アドレスのみを返します。この例では、Include<TSource>(IQueryable<TSource>, []) メソッド (JavaScript: Include ステートメント) を使用して、各ユーザー オブジェクトで Title (JavaScript: title) プロパティおよび Email (JavaScript: email) プロパティのみを使用できるように指定します。他のプロパティを呼び出すと、PropertyOrFieldNotInitializedException が返されます。

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveSpecificUserProperties
    {
        static void Main()
        {
            ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            GroupCollection collGroup = clientContext.Web.SiteGroups;
            Group oGroup = collGroup.GetById(7);
            UserCollection collUser = oGroup.Users;

            clientContext.Load(collUser,
                users => users.Include(
                    user => user.Title,
                    user => user.LoginName,
                    user => user.Email));

            clientContext.ExecuteQuery();

            foreach (User oUser in collUser)
            {
                Console.WriteLine("User: {0} Login name: {1} Email: {2}", 
                    oUser.Title, oUser.LoginName, oUser.Email);
            }
        }
}
Imports System
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveSpecificUserProperties

        Shared Sub Main()
            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim collGroup As GroupCollection = clientContext.Web.SiteGroups
            Dim oGroup As Group = collGroup.GetById(7)
            Dim collUser As UserCollection = oGroup.Users

            clientContext.Load(collUser, Function(users) users.Include( _
                                             Function(user) user.Title, _
                                             Function(user) user.LoginName, _
                                             Function(user) user.Email))

            clientContext.ExecuteQuery()

            Dim oUser As User
            For Each oUser In collUser
                Console.WriteLine("User: {0} Login name: {1} Email: {2}", _
                                  oUser.Title, oUser.LoginName, oUser.Email)
            Next oUser

        End Sub        
    End Class
End Namespace
var siteUrl = '/sites/MySiteCollection ';

function retrieveSpecificUserProperties() {

    var clientContext = new SP.ClientContext(siteUrl);
    var collGroup = clientContext.get_web().get_siteGroups();
    var oGroup = collGroup.getById(7);
    this.collUser = oGroup.get_users();
    clientContext.load(collUser, 'Include(Title, LoginName, Email)');


    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    var userInfo = '';

    var userEnumerator = collUser.getEnumerator();
    while (userEnumerator.moveNext()) {
        var oUser = userEnumerator.get_current();
        this.userInfo += '\nUser: ' + oUser.get_title() + 
            '\nEmail: ' + oUser.get_email() + 
            '\vLogin Name: ' + oUser.get_loginName();
    }
        
    alert(userInfo);
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

サイト コレクションのすべてのグループのすべてのユーザーを取得する

前の例は、特定のグループからすべてのユーザーを返す方法を示しています。サイト コレクション内のすべてのグループからすべてのユーザーを返すには、Load<T>(T, []) メソッド (JavaScript: load(clientObject)) を 2 回使用して、各グループのグループ コレクションとユーザー コレクションの両方を読み込みます。これにより、各ユーザーおよびグループのすべてのプロパティが使用できるようになります。次の例で示すように、LINQ query メソッドの構文を使用して、各グループの各ユーザー コレクションを含めます。

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveAllUsersAllGroups
    {
        static void Main()
        {
            ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            GroupCollection collGroup = clientContext.Web.SiteGroups;

            clientContext.Load(collGroup);

            clientContext.Load(collGroup,
                groups => groups.Include(
                    group => group.Users));

            clientContext.ExecuteQuery();

            foreach (Group oGroup in collGroup)
            {
                UserCollection collUser = oGroup.Users;

                foreach (User oUser in collUser)
                {
                    Console.WriteLine("Group ID: {0} Group Title: {1} User: {2} Login Name: {3}", 
                        oGroup.Id, oGroup.Title, oUser.Title, oUser.LoginName);
                }
            }  
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveAllUsersAllGroups

        Shared Sub Main()
            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim collGroup As GroupCollection = clientContext.Web.SiteGroups

            clientContext.Load(collGroup)

            clientContext.Load(collGroup, Function(groups) groups.Include( _
                                              Function(group) group.Users))

            clientContext.ExecuteQuery()

            Dim oGroup As Group
            For Each oGroup In collGroup
                Dim collUser As UserCollection = oGroup.Users

                Dim oUser As User
                For Each oUser In collUser
                    Console.WriteLine("Group ID: {0} Group Title: {1} User: {2} Login Name: {3}", _
                                      oGroup.Id, oGroup.Title, oUser.Title, oUser.LoginName)
                Next oUser
            Next oGroup

        End Sub        
    End Class
End Namespace
var siteUrl = '/sites/MySiteCollection ';

function retrieveAllUsersAllGroups() {

    var clientContext = new SP.ClientContext(siteUrl);
    this.collGroup = clientContext.get_web().get_siteGroups();
    clientContext.load(collGroup);
    clientContext.load(collGroup, 'Include(Users)');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    var userInfo = '';

    var groupEnumerator = collGroup.getEnumerator();
    while (groupEnumerator.moveNext()) {
        var oGroup = groupEnumerator.get_current();
        var collUser = oGroup.get_users();
        var userEnumerator = collUser.getEnumerator();
        while (userEnumerator.moveNext()) {
            var oUser = userEnumerator.get_current();
            this.userInfo += '\nGroup ID: ' + oGroup.get_id() + 
                '\nGroup Title: ' + oGroup.get_title() + 
                '\nUser: ' + oUser.get_title() + 
                '\nLogin Name: ' + oUser.get_loginName();
        }
    }
        
    alert(userInfo);
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

効率性を高めるには、次の例で示すように、Load<T>(T, []) メソッド (JavaScript: load(clientObject)) を 1 回呼び出して、特定のプロパティのみが含められるようにクエリ式を変更します。

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveAllUsersAllGroupsSpecificProperties
    {
        static void Main()
        {
            ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            GroupCollection collGroup = clientContext.Web.SiteGroups;

            clientContext.Load(collGroup,
                groups => groups.Include(
                    group => group.Title,
                    group => group.Id,
                    group => group.Users.Include(
                        user => user.Title,
                        user => user.LoginName)));

            clientContext.ExecuteQuery();

            foreach (Group oGroup in collGroup)
            {
                UserCollection collUser = oGroup.Users;

                foreach (User oUser in oGroup.Users)
                {
                    Console.WriteLine("Group: {0} Group ID: {1} User: {2} Login Name: {3}", 
                        oGroup.Title, oGroup.Id, oUser.Title, oUser.LoginName);
                }
            }
         }
    }
}
Imports System
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveAllUsersAllGroupsSpecificProperties

        Shared Sub Main()
            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim collGroup As GroupCollection = clientContext.Web.SiteGroups

            clientContext.Load(collGroup, Function(groups) groups.Include( _
                                         Function(group) group.Title, _
                                         Function(group) group.Id, _
                                         Function(group) group.Users.Include( _
                                             Function(user) user.Title, _
                                             Function(user) user.LoginName)))

            clientContext.ExecuteQuery()

            Dim oGroup As Group
            For Each oGroup In collGroup
                Dim collUser As UserCollection = oGroup.Users

                Dim oUser As User
                For Each oUser In oGroup.Users
                    Console.WriteLine("Group: {0} Group ID: {1} User: {2} Login Name: {3}", _
                                      oGroup.Title, oGroup.Id, oUser.Title, oUser.LoginName)
                Next oUser
            Next oGroup

        End Sub        
    End Class
End Namespace
var siteUrl = '/sites/MySiteCollection ';

function retrieveAllUsersAllGroupsSpecificProperties() {

    var clientContext = new SP.ClientContext(siteUrl);
    this.collGroup = clientContext.get_web().get_siteGroups();
    clientContext.load(collGroup, 'Include(Title,Id,Users.Include(Title,LoginName))');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    var userInfo = '';

    var groupEnumerator = collGroup.getEnumerator();
    while (groupEnumerator.moveNext()) {
        var oGroup = groupEnumerator.get_current();
        var collUser = oGroup.get_users();
        var userEnumerator = collUser.getEnumerator();
        while (userEnumerator.moveNext()) {
            var oUser = userEnumerator.get_current();
            this.userInfo += '\nGroup ID: ' + oGroup.get_id() + 
                '\nGroup Title: ' + oGroup.get_title() + 
                '\nUser: ' + oUser.get_title() + 
                '\nLogin Name: ' + oUser.get_loginName();
        }
    }
        
    alert(userInfo);
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

SharePoint グループにユーザーを追加する

グループに追加するユーザー オブジェクトが既にサイト コレクション内に存在する場合は、AddUser(User) メソッド (JavaScript: addUser(user)) を使用して、グループのユーザー コレクションにユーザーを追加できます。ただし、ユーザーが存在しない場合は、次のコード例で示すように、UserCreationInformation クラス (JavaScript: UserCreationInformation) を使用して新しいユーザーを定義してから、Add(UserCreationInformation) メソッド (JavaScript: add(parameters)) を使用してグループのユーザー コレクションに、その新しいユーザーを追加します。この例では、GetById(Int32) メソッド (JavaScript: getById(id)) を使用してサイト コレクション内のグループ コレクションから特定のグループを返し、新しいユーザー オブジェクトを定義して、それをグループのユーザー コレクションに追加しています。

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class AddUserToSharePointGroup
    {
        static void Main()
        {   
            ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection ");
            GroupCollection collGroup = clientContext.Web.SiteGroups;
            Group oGroup = collGroup.GetById(6);

            UserCreationInformation userCreationInfo = new UserCreationInformation();
            userCreationInfo.Email = "alias@somewhere.com";
            userCreationInfo.LoginName = @"DOMAIN\alias";
            userCreationInfo.Title = "John";

            User oUser = oGroup.Users.Add(userCreationInfo);

            clientContext.ExecuteQuery(); 
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class AddUserToSharePointGroup

        Shared Sub Main()
            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim collGroup As GroupCollection = clientContext.Web.SiteGroups
            Dim oGroup As Group = collGroup.GetById(7)

            Dim userCreationInfo As New UserCreationInformation()
            userCreationInfo.Email = "alias@somewhere.com"
            userCreationInfo.LoginName = "DOMAIN\alias"
            userCreationInfo.Title = "John"
            Dim oUser As User = oGroup.Users.Add(userCreationInfo)

            clientContext.ExecuteQuery()

        End Sub        
    End Class
End Namespace
var siteUrl = '/sites/MySiteCollection ';

function addUserToSharePointGroup() {

    var clientContext = new SP.ClientContext(siteUrl);
    var collGroup = clientContext.get_web().get_siteGroups();
    var oGroup = collGroup.getById(7);
    var userCreationInfo = new SP.UserCreationInformation();
    userCreationInfo.set_email('alias@somewhere.com');
    userCreationInfo.set_loginName('DOMAIN\alias');
    userCreationInfo.set_title('John');
    this.oUser = oGroup.get_users().add(userCreationInfo);
    
    clientContext.load(oUser);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}

function onQuerySucceeded() {
        
    alert(this.oUser.get_title() + " added.");
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Microsoft SharePoint Foundation 2010 Silverlight オブジェクト モデルのコンテキスト内でのクライアント オブジェクトの使用に関する情報および使用例については、「Silverlight オブジェクト モデルを使用する」を参照してください。

関連項目

概念

[方法] ロールを処理する

[方法] ロール割り当ての継承を解除する

承認、ユーザー、およびグループ

データ取得の概要

クライアント オブジェクトの作成

クライアント オブジェクト モデルのガイドライン

一般的なプログラミング作業

その他の技術情報

クライアント クラス ライブラリ

ECMAScript クラス ライブラリ