Adding Sharepoint user remotely PowerShell script - sharepoint

Running EnsureUser on an existing domain account give an error that the user could not be found. Same command(s) works fine in PowerShell on SharePoint server locally. I am able to create a SharePoint group remotely, just can't add a user to that group.
$site = new-object Microsoft.SharePoint.SPSite("http://sharepoint.company.com/dev")
$web = $site.OpenWeb()
function GrantUserpermission($userName)
{
$folder.BreakRoleInheritance("true")
$web.SiteGroups.Add("test_group", $web.Site.Owner, $web.Site.Owner, "Desc")
$ownerGroup = $web.SiteGroups["test_group"]
$ownerGroup.AllowMembersEditMembership = $true
$ownerGroup.Update()
$sitename = Get-SPWeb http://sharepoint.company.com/dev
$EnsuredUser = $sitename.EnsureUser("domain\user")
Set-SPUser -Identity $EnsuredUser -web $sitename -group "test_group"
$AddGroup = $web.SiteGroups["test_group"]
$roleAssignment = new-object Microsoft.sharepoint.SPRoleAssignment($AddGroup)
$roleDefinition = $web.RoleDefinitions["Contribute"]
$roleAssignment.RoleDefinitionBindings.add($roleDefinition)
$folder.RoleAssignments.Add($roleAssignment)
$folder.SystemUpdate()

Check if the domain user exists before use the EnsureUser method.
If you want to add SharePoint user to group in remote server, we can use CSOM with PowerShell to achieve it.
$url="http://sharepoint.company.com/dev"
$userName="administrator"
$password="**"
$domain="test"
$sGroup="test_group"
$sUserToAdd="domain\user"
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-Object System.Net.NetworkCredential($userName,$password,$domain)
$ctx.Credentials = $credentials
$groups=$ctx.Web.SiteGroups
$ctx.Load($groups)
#Getting the specific SharePoint Group where we want to add the user
$group=$groups.GetByName($sGroup)
$ctx.Load($group)
#Ensuring the user we want to add exists
$user = $ctx.Web.EnsureUser($sUserToAdd)
$ctx.Load($user)
$userToAdd=$group.Users.AddUser($user)
$ctx.Load($userToAdd)
$ctx.ExecuteQuery()

Related

Create more than one delegated permission in Azure application with PowerShell?

I am creating a script to create a new app registration within Azure.
So far, all is working well, I can create the app, create the service principal, set a secret and add a redirect uri.
The issue I face is that I can create a delegation permission for the application using the below function:
$graph = "00000003-0000-0000-c000-000000000000"
$sharePoint = "00000003-0000-0ff1-ce00-000000000000"
$userRead = "e1fe6dd8-ba31-4d61-89e7-88639da4683d"
$myFilesWrite = "2cfdc887-d7b4-4798-9b33-3d98d6b95dd2"
$allSitesWrite = "640ddd16-e5b7-4d71-9690-3f4022699ee7"
Function SetPermissions($resourceId, $argument)
{
$rra = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess"
$rra.ResourceAppId = $resourceId
$rra.ResourceAccess = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList $argument ,"Scope"
Set-AzureADApplication -ObjectId $myApp.ObjectId -RequiredResourceAccess $rra
}
SetPermissions $graph $userRead
but I will need three permissions for my app - when I call the function a second time it just overwrites the existing permission rather than adding a new one.
Any advice on how I can create multiple app permissions?
I tried to reproduce the same in my environment and got below results.
When I ran the same code as you, User.Read permission is added to the application like below:
Now I changed the arguments and ran the code again as below:
$myApp = Get-AzureADApplication -SearchString MyApp
$graph = "00000003-0000-0000-c000-000000000000"
$sharePoint = "00000003-0000-0ff1-ce00-000000000000"
$userRead = "e1fe6dd8-ba31-4d61-89e7-88639da4683d"
$myFilesWrite = "2cfdc887-d7b4-4798-9b33-3d98d6b95dd2"
$allSitesWrite = "640ddd16-e5b7-4d71-9690-3f4022699ee7"
Function SetPermissions($resourceId, $argument)
{
$rra = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess"
$rra.ResourceAppId = $resourceId
$rra.ResourceAccess = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList $argument ,"Scope"
Set-AzureADApplication -ObjectId $myApp.ObjectId -RequiredResourceAccess $rra
}
SetPermissions $sharePoint $allSitesWrite //Changed this
Response:
When I checked the same in Portal, existing permission removed, and new permission added like below:
To add multiple delegated permissions to Azure AD application from PowerShell, you can make use of below script:
$Graph = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess"
$Graph.ResourceAppId = "00000003-0000-0000-c000-000000000000"
$SharePoint = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess"
$SharePoint.ResourceAppId = "00000003-0000-0ff1-ce00-000000000000"
$userRead = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "e1fe6dd8-ba31-4d61-89e7-88639da4683d","Scope"
$myFilesWrite = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "2cfdc887-d7b4-4798-9b33-3d98d6b95dd2","Scope"
$allSitesWrite = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "640ddd16-e5b7-4d71-9690-3f4022699ee7","Scope"
$Graph.ResourceAccess = $userRead
$SharePoint.ResourceAccess = $myFilesWrite, $allSitesWrite
$myApp = Get-AzureADApplication -SearchString MyApp
Set-AzureADApplication -ObjectId $myApp.ObjectId -RequiredResourceAccess $Graph, $SharePoint
Response:
When I checked the same in Portal, multiple delegated permissions added to the application successfully like below:
Reference:
How to assign Permissions to Azure AD App by using PowerShell by rajaniesh

AzureAD - ConditionalAccessPolicy PersistentBrowser error

I have the following script to create a Conditional Access policy but i get below error.
And i dont understand what is wrong
$conditions = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessConditionSet
$conditions.Applications = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessApplicationCondition
$conditions.Applications.IncludeApplications = "Office365"
$conditions.Users = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessUserCondition
$conditions.Users.IncludeRoles = #('62e90394-69f5-4237-9190-012177145e10', 'f28a1f50-f6e7-4571-818b-6a12f2af6b6c', '29232cdf-9323-42fd-ade2-1d097af3e4de', 'b1be1c3e-b65d-4f19-8427-f6fa0d97feb9', '194ae4cb-b126-40b2-bd5b-6091b380977d', '729827e3-9c14-49f7-bb1b-9608f156bbb8', '966707d0-3269-4727-9be2-8c3a10f19b9d', 'b0f54661-2d74-4c50-afa3-1ec803f12efe', 'fe930be7-5e62-47db-91af-98c3a49a38b1')
$conditions.Users.ExcludeGroups = $ExcludeCAGroup.ObjectId
$conditions.ClientAppTypes = #('Browser', 'MobileAppsAndDesktopClients')
$controls = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessGrantControls
$controls._Operator = "OR"
$controls.BuiltInControls = "MFA"
$session = New-Object -TypeName Microsoft.Open.MSGraph.Model.conditionalAccessSessionControls
$sessioncontrols = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessSignInFrequency
$sessioncontrols.Type = "days"
$sessioncontrols.Value = 30
$sessioncontrols.IsEnabled = $true
$session.SignInFrequency = $sessioncontrols
$persistent = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessPersistentBrowser
$persistent.IsEnabled = $true
$persistent.Mode = "never"
$session.PersistentBrowser = $persistent
New-AzureADMSConditionalAccessPolicy -DisplayName "GRANT: Require MFA for Admin users and never persistent sessions" -State "Disabled" -Conditions $conditions -GrantControls $controls -SessionControls $session
The error i get is
New-AzureADMSConditionalAccessPolicy : Error occurred while executing NewAzureADMSConditionalAccessPolicy
Code: BadRequest
Message: 1032: ConditionalActionPolicy validation failed due to InvalidConditionsForPersistentBrowserSessionMode.
anyone have any ideas?
I have tried in my environment and got the same error like below:
If you are including persistent browser mode in your script, then make sure to select All applications for session control as mentioned in this MsDoc.
By Changing the IncludeApplications from office365 to All like below:
$conditions.Applications.IncludeApplications = "All"
I was able to create conditional access policy successfully :
I also tried keeping included app as office365,but changed $persistent.IsEnabled=$false .This worked maybe because it can only be enabled for all apps as suggested in the MsDoc.

Make Azure Authentication Run Silently without Password Prompt

I have a PowerShell script that connects to Azure, then downloads data. The script runs great with human interaction, but I'm trying to run it silently as a scheduled task. Currently, every time the script runs, it prompts for user credentials. I change 'Always' to 'Never' and it doesn't seem to store the credentials for any length of time.
$clientId = "<CLIENTIDHERE>" # PowerShell clientId
$redirectUri = "<REDIRECTURIHERE>"
$MSGraphURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/$tenantId"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$authResult = $authContext.AcquireToken($MSGraphURI, $clientId, $redirectUri, "Always")
$token = $authResult.AccessToken
Ideally the credentials would be passed through based on the credentials running in the scheduled task. If that isn't an option, at least I'm hoping to put the username and password in the script and have the script send those credentials to authenticate. How does one authenticate silently to Azure?
You could check the script shared by Bogdan Gavril from this thread .
#Require -Version 5.0
using namespace Microsoft.IdentityModel.Clients.ActiveDirectory
$adalDll = [Reflection.Assembly]::LoadFile("<path_to>\Microsoft.IdentityModel.Clients.ActiveDirectory.dll")
$ADAuthorityURL = "https://login.windows.net/common/oauth2/authorize/"
$resourceURL = "https://analysis.windows.net/powerbi/api"
$AADuserName = "foo"
$AADpassword = "bar"
Write-Host "Retrieving the AAD Credentials...";
$credential = New-Object UserPasswordCredential($AADuserName, $AADpassword);
$authenticationContext = New-Object AuthenticationContext($ADAuthorityURL);
$authenticationResult = [AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authenticationContext, $resourceURL, $AADClientID, $credential).Result;
$ResultAAD = $authenticationResult.AccessToken;
I was able to figure this out. The initial authentication code I presented used an Azure-specific pop-up window to grab your credentials. Using the following link [1] I converted the code to the PowerShell Get-Credential method instead. From there, I used the information in this link [2] (Example 7) to configure the Get-Credential method to pull from plain text instead of a pop-up Window.
Now plain text passwords isn't ideal, but for our needs, it was good enough.
$clientId = "<CLIENTIDHERE>" # PowerShell clientId
$redirectUri = "REDIRECTURIHERE"
$MSGraphURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/$tenantId"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$User = "<USERNAMEHERE>"
$PWord = ConvertTo-SecureString -String "<PASSWORDHERE>" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credential.UserName,$credential.Password
$authResult = $authContext.AcquireToken($MSGraphURI, $clientId, $AADCredential)
$token = $authResult.AccessToken
[1] https://blogs.technet.microsoft.com/cloudlojik/2017/09/05/using-powershell-to-connect-to-microsoft-graph-api/
[2] https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/get-credential?view=powershell-6

Disable all site creation except for a certain group

I want to lock down site creation to a certain group of admin suresh. We have created a group for this, but what do I tell the SharePoint Admin to do in order to achieve this?
To lock down site creation, you basically need to run a few PowerShell commands as below using Azure AD PowerShell. Run them commands with Global admin priviledges.
I am assuming that you have created an Azure AD group with certain users who will have access to create the site.
$creds = Get-Credential
Connect-AzureAD -Credential $creds
$group = Get-AzureADGroup -All $True | Where-Object {$_.DisplayName -eq "ENTER GROUP DISPLAY NAME HERE"}
$policySetting = Get-AzureADDirectorySetting | where-object {$_.displayname -eq "Group.Unified"}
if($policySetting -eq $null) {
$template = Get-AzureADDirectorySettingTemplate | Where-Object {$_.DisplayName -eq "Group.Unified"}
$settings = $template.CreateDirectorySetting()
$settings["EnableGroupCreation"] = $false
$settings["GroupCreationAllowedGroupId"] = $group.ObjectId
$policySetting = New-AzureADDirectorySetting -DirectorySetting $settings
}
else{
$policySetting["EnableGroupCreation"] = $false
$policySetting["GroupCreationAllowedGroupId"] = $group.ObjectId
Set-AzureADDirectorySetting -Id $policySetting.Id -DirectorySetting $policySetting
}
Links:
Installing the Azure AD module
Code modified from - Managing Office 365 group creation using Azure AD PowerShell v2

Add column to SharePoint Online 2013 list via Powershell v3

Can anybody tell me how to do this? None of the examples I have found seem to work.
My site is https://blah.sharepoint.com/technology and my list is called 'pfa'. I want to add some text columns.
I DO have connectivity with SharePoint Online via my Powershell, as I have managed to get some results back from various commands.
Thanks.
How to provision field in SharePoint Online via CSOM in PowerShell
CSOM API comes with:
FieldCollection.Add method - adds a field to the field
collection
FieldCollection.AddFieldAsXml method - creates a field based on
the specified schema, Boolean value, and field options
to add a list or site column.
The example below demonstrates how to add GeoLocation field into Contacts List:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
function Provision-Field([Microsoft.SharePoint.Client.ClientContext]$Context,[string]$ListTitle,[string]$FieldSchema)
{
$list = $Context.Web.Lists.GetByTitle($ListTitle)
$List.Fields.AddFieldAsXml($FieldSchema,$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($List)
$Context.ExecuteQuery()
}
$UserName = "username#contoso.onmicrosoft.com"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$URL = "https://contoso.sharepoint.com/"
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($URL)
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,$Password)
$Context.Credentials = $Credentials
Provision-Field $Context "Contacts" "<Field Type='Geolocation' DisplayName='Location'/>"
How to provision field in SharePoint Online via REST in PowerShell
Endpoints:
http://<site url>/_api/web/fields('<field id>')
http://<site url>/_api/web/lists(guid'<list id>')/fields('<field id>')
The article Consuming the SharePoint 2013 REST API from PowerShell describes how send HTTPS requests to SharePoint REST web services.
Using the Invoke-RestSPO function from the article, the following example demonstrates how to add Note field to List using REST API in PowerShell:
Function Add-SPOField(){
Param(
[Parameter(Mandatory=$True)]
[String]$WebUrl,
[Parameter(Mandatory=$True)]
[String]$UserName,
[Parameter(Mandatory=$False)]
[String]$Password,
[Parameter(Mandatory=$True)]
[String]$ListTitle,
[Parameter(Mandatory=$True)]
[String]$FieldTitle,
[Parameter(Mandatory=$True)]
[System.Int32]$FieldType
)
$fieldMetadata = #{
__metadata = #{'type' = 'SP.Field' };
Title = $FieldTitle;
FieldTypeKind = $FieldType;
} | ConvertTo-Json
$Url = $WebUrl + "_api/web/Lists/GetByTitle('" + $ListTitle + "')/fields"
$contextInfo = Get-SPOContextInfo $WebUrl $UserName $Password
Invoke-RestSPO $Url Post $UserName $Password $fieldMetadata $contextInfo.GetContextWebInformation.FormDigestValue
}
. ".\Invoke-RestSPO.ps1" #InInvoke-RestSPO function
$UserName = "username#contoso.onmicrosoft.com"
$Password = Read-Host -Prompt "Please enter your password"
$WebUrl = "https://contoso.sharepoint.com/"
Add-SPOField -WebUrl $WebUrl -UserName $UserName -Password $Password -ListTitle "Documents" -FieldTitle "Comments" -FieldType 3
References
Fields REST API reference
Consuming the SharePoint 2013 REST API from PowerShell
Here is someone who created a list with the CSOM through PowerShell with SharePoint Oneline http://www.hartsteve.com/2013/06/sharepoint-online-powershell/
The PowerShell stuff for SharePoint online is limited to some basic admin tasks only. When you used the CSOM in PowerShell, you can do a lot more.

Resources