How to remove all list item permissions using PnP Powershell - powershell

I would like to remove all permissions of a list item using PnP Powershell
I have tried this command:
Set-PnPListItemPermission -Identity $item.id -User 'user#contoso.com' -AddRole "Contribute"
However the user running the script/command was also added with Full Control permissions.
Is there any other way to remove all existing permissions for a list item using PnP Powershell ?
Thanks

I tested to connect to SharePoint Online site with a read permission user in PnP PowerShell and then run the Set-PnPListItemPermission command, it will throw Access Denied error instead of adding with Full Control Permissions:
In Summary, to set permssions for list item, it's expecetd to have the Full Control Permission on the site level for the user who is running the script. Otherwise, the Access Denied error will throw.
The Full Control permissions should be applied with the site group, in the list, try to break permission inheritance and remove the group:
# Provide credentials over here
$creds = (New-Object System.Management.Automation.PSCredential "<<UserName>>",(ConvertTo-SecureString "<<Password>>" -AsPlainText -Force))
# Provide URL of the Site over here
# If you do not wish to pass credentials hard coded then you can use: -Credentials (Get-Credential). This will prompt to enter credentials
Connect-PnPOnline -Url http://MyServer/sites/MySiteCollection -Credentials $creds
# Get Context
$clientContext = Get-PnPContext
$targetWeb = Get-PnPWeb
# Get the list object
$targetList = $targetWeb.Lists.GetByTitle("List Name")
# Load List object
$clientContext.Load($targetList)
$clientContext.ExecuteQuery()
# This method will work only if the role inheritence is broken(list has unique role assignments) on the list
$targetList.RoleAssignments.Groups.RemoveByLoginName("test Visitors")
$clientContext.ExecuteQuery()
Disconnect-PnPOnline

Related

How to get tenant properties through PowerShell with SharePointPnP?

I have been given a task to setup a scheduled task which will run daily to pull down the list of allowed domains from SPO. This is not an issue if I use Connect-SPOService and Get-SPOTenant, like this:
Connect-SPOService –url https://xxxx-admin.sharepoint.com
Get-SPOTenant | select -ExpandProperty SharingAllowedDomainList > d:\allowedDomains.txt
The issue issue is that this has to be automated. There is also a requirement to use an ClientId and Secret in the script, rather than providing me with an account which bypasses MFA and has SP Admin rights.
Because of that, I've turned to SharePointPnP, which does allow you to connect with ClientId and Secret. I'm able to connect to connect with the following:
Connect-PnPOnline -url https://xxxx-admin.sharepoint.com -ClientId "xxxxx" -ClientSecret "xxxxx"
Where I'm struggling now is trying to how I can retrieve the SharingAllowedDomainList property through SharePointPnP, or if that is even possible?
#THTX,
Can you please have a try below pnp powershell cmdlet?
Get-PnPTenant
Get-PnPTenantSite
It has SharingAllowedDomainList property:
BR

How to create guest AD user invitation then add to a SharePoint Online site in PowerShell

This script creates a guest user invitation, but errors when trying to add that newly created user to a SharePoint Online site with the following error:
Add-SPOUser : The specified user janedoe#email.com could not be found.
$tenant = "companyname"
Connect-SPOService -url "https://$tenant-admin.sharepoint.com"
Connect-AzureAD -TenantDomain "$tenant.onmicrosoft.com"
New-AzureADMSInvitation -InvitedUserDisplayName "Jane Doe" -InvitedUserEmailAddress "janedoe#email.com" -InviteRedirectURL "https://$tenant.sharepoint.com/sites/client1" -SendInvitationMessage $true
Start-Sleep -s 60
Add-SPOUser -Group "Client Site 1 Visitors" –LoginName "janedoe#email.com" -Site "https://$tenant.sharepoint.com/sites/client1"
Disconnect-SPOService
Disconnect-AzureAD
How long does it take for Azure AD to populate that user into Office 365?
When trying to add the external user email (outside tenancy) to a SP group via the GUI, tabbing away shows the following error:
"Your organization's policies don't allow you to share with these users. Go to External Sharing in the Office 365 admin center to enable it."
To fix this and the PS script error, after the creation of your extranet SP site run the following PS command after connecting to SPO (only need to run ONCE before adding an external user to a site):
Set-SPOSite -identity https://companyname.sharepoint.com/sites/client1 -sharingcapability ExternalUserAndGuestSharing
Now the PS script will work without error. Start-Sleep is not necessary.

Using Powershell to get Azure AD Token (jwt)

I am trying to get a jwt token from AAD using Powershell using Username/Password authentication.
I am writing a powershell script that will to call an API using a bearer token. What I have works if I copy & paste the token from an SPA that uses the API. I am looking for a way to retrieve the token from my powershell.
This looks really promising: https://github.com/Azure-Samples/active-directory-dotnet-native-headless/blob/master/TodoListClient/Program.cs
I feel like I'm smacking my head against a wall trying to create a 'UserPasswordCredential' object. Any clues to how I can do this would be super-helpful.
I have Add-Type-ed:
- Microsoft.IdentityModel.Clients.ActiveDirectory.dll
- Microsoft.IdentityModel.Clients.ActiveDirectory.platform.dll (adds nothing?)
- Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll
- Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll
The docs page for 'UserPasswordCredential' :
https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.clients.activedirectory.userpasswordcredential
It should be in one of the first two dlls
This, under 'Constraints & Limitations', makes me think it may not actually be possible from powershell:
http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/
Looking at the code below, the first acquire token succeeds, the second fails - possibly/probably because $cred is a UserCredential not a UserPasswordCredential.
Is is possible to do this with powershell?
Finally, on a totally different track, how do I find the values for redirectUri and resourceAppIdURI that my application needs? When I look in the AAD console, and browser to my Enterprise Application, I can find the AppId (which I can use as $clientId).
I'm not sure the redirectUri is strictly necessary for me as all I really want is the token, but I can have a good guess at what it should be.
When I try to call the first AquireToken method (without $cred) using my app details, it fails with this message:
Exception calling "AcquireToken" with "4" argument(s): "AADSTS50001: The application named https://myappwithapi/Login was not found in the tenant named me.onmicrosoft.com.
Is it possible for me to find the require value for resourceAppIdURI by looking in my azure portal?
'https://myappwithapi/Login' is from my azure portal > enterprise apps > [app' > properties > HomepageUrl
code:
#setup
$TenantName = "mme.onmicrosoft.com"
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2" # Microsoft
$clientId = "03faf8db-..........................." #
$username = "me#me.onmicrosoft.com"
$password = Read-Host -AsSecureString -Prompt "Enter Password"
# add dlls
$adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"
$adalplatform = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.platform.dll"
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalplatform) | Out-Null
#prep request
$redirectUri = "urn:ietf:wg:oauth:2.0:oob" # Microsoft
$resourceAppIdURI = "https://graph.windows.net"
$authority = "https://login.windows.net/$TenantName"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
# Get Token prompting for creds
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, "Always")
$authResult
# Get the cred
$cred = New-Object -TypeName 'Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential' -ArgumentList $username, $password
#$cred = New-Object -TypeName 'Microsoft.IdentityModel.Clients.ActiveDirectory.UserPassCredential' -ArgumentList $username, $password
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $cred)
$authResult
This post has more the one question in it.
Your base use case 'Using Powershell to get Azure AD Token (jwt)' is a common one and there are several samples and pre-built examples to leverage. For example:
https://github.com/pcgeek86/AzureADToken
A PowerShell module that allows you to get a JSON Web Token (JWT) from Azure Active Directory (AAD).
https://gallery.technet.microsoft.com/Get-Azure-AD-Bearer-Token-37f3be03
This script acquires a bearer token that can be used to authenticate to the Azure Resource Manager API with tools such as Postman. It uses the Active Directory Authentication Library that is installed with the Azure SDK.
See if those two resources resolves your use base line use case.
As for this...
"Is it possible for me to find the require value for resourceAppIdURI by looking in my azure portal?"
You can do this via a remote PowerShell logon to AzureAD. Install the AAD PowerShell module.
https://learn.microsoft.com/en-us/powershell/azure/overview?view=azurermps-5.1.1
https://msdn.microsoft.com/en-us/library/dn135248(v=nav.70).aspx
Download and install MSOL. Sign in with the MSOL
https://www.microsoft.com/en-US/download/details.aspx?id=39267
The Microsoft Online Services Sign-In Assistant provides end user sign-in capabilities
and use the built-in cmdlets to pull your information from your organization settings, and or hit the MSGraph API and query.
https://learn.microsoft.com/en-us/powershell/azure/active-directory/install-adv2?view=azureadps-2.0
You can use the Azure Active Directory PowerShell Module Version for Graph for Azure AD administrative tasks
As for this one:
"how do I find the values for redirectUri and resourceAppIdURI that my application needs?"
This is in your app registration section of your portal. The developer team provide the redir uri not Azure. It's part of the registration process all else is generated by Azure App Reg process.
The app registration process is here and of course you are someone else had to register this app in AzureAD, and thus can retrieve it at any time.:
https://blogs.msdn.microsoft.com/onenotedev/2015/04/30/register-your-application-in-azure-ad
Any registered apps and their details can be retrieved using...
Get-AzureADApplication
Get-AzureADApplication | Select -Property *
(Get-AzureADApplication).ReplyUrls
Get-AzureADApplication | Select -Property AppID, DisplayName,ReplyUrls
https://learn.microsoft.com/en-us/powershell/module/azuread/get-azureadapplication?view=azureadps-2.0

How to set Administrators and permissions in Business Data Connectivity Service using powershell

While we are creating Managed Metadata service using powershell, New-SPMetadataServiceApplication have property -AdministratorAccount and -FullAccessAccount to set Administrator and permissions.
but in New-SPBusinessDataCatalogServiceApplication i have not found properties like that.
How can i add users in administrators and permissions?
Thanks
I got the solution.
Here is an answer.
$principal = New-SPClaimsPrincipal "Domain\SP_Farm" -IdentityType WindowsSamAccountName
$spapp = Get-SPServiceApplication -Name "Search Service Application"
$security = Get-SPServiceApplicationSecurity $spapp -Admin
Grant-SPObjectSecurity $security $principal "Full Control"
Set-SPServiceApplicationSecurity $spapp $security -Admin
The above given code is worked if you want to add user in administrators.
If you want to add user in permissions remove -Admin.

cmdkey in PowerShell doesn't work when run as a logon script?

Trying is use cmdkey in a PowerShell logon script to store credentials in the credential manager. When the script is run from PowerShell ISE everything works, but when it's run as a logon script via Group Policy everything but cmdkey works. Cannot for the life of me figure out why cmdkey will work everywhere except when the script run on logon.
# Checks if CRM for Outlook is isntalled by checking the folder path
$installed = Test-Path "C:\Program Files (x86)\Microsoft Dynamics CRM"
# Checks if the CRM has already been configured using the CoreConfigured registry entry
$configured = Get-ItemProperty -Path HKCU:\software\Microsoft\MSCRMClient -Name "CoreConfigured"
# If CRM is installed and not configured, configure it, if CRM is not installed or installed and configured, exit
If ($installed -eq "True" -and $configured.CoreConfigured -ne 1) {
$message1 = New-object -ComObject Wscript.Shell
$message1.Popup("Preparing to configure Microsoft CRM for Outlook, please make sure Outlook is closed.",10,"Systems")
# Prompts user for email address and Password to configure CRM for Outlook
$c = Get-Credential -Message "To confgiure CRM, please enter your email address and password:"
# puts user credentials into Windows Credential Manager using required CRM URLs
cmdkey /generic:Microsoft_CRM_https://disco.crm.dynamics.com/ /user: $c.Username /pass: $c.Password | Out-Null
cmdkey /generic:Microsoft_CRM_https://disco.crm4.dynamics.com/ /user: $c.Username /pass: $c.Password | Out-Null
$message2 = New-Object -ComObject Wscript.Shell
$message2.Popup("Please wait, a notification will appear when the configuration is complete.",10,"Systems")
# Silenty runs the CRM configuration Wizard with custom XML file
$exe = "C:\Program Files (x86)\Microsoft Dynamics CRM\Client\ConfigWizard\Microsoft.Crm.Application.Outlook.ConfigWizard.exe"
&$exe -p /Q /i 'C:\Program Files (x86)\Microsoft Dynamics CRM\Default_Client_Config.xml' /xa /l 'c:\temp\crminstall.txt' | Out-Null
$message3 = New-Object -ComObject Wscript.Shell
$message3.Popup("Configuration complete! You may now open Outlook!",10,"Systems")
}
else {
exit
}
I imagine cmdkey is using Microsoft's Data Protection API (DPAPI) to encrypt credentials so only the current user can retrieve them. You can't use this API unless the user's session is loaded. When your script runs, it may be too early in the logon process for the security information the DPAPI needs is loaded. I'm not sure how logon scripts work, but try putting a delay in your logon script until you get a value back.
Here's the PowerShell code that encrypts with the DPAPI:
$scope = [Security.Cryptography.DataProtectionScope]::CurrentUser
$encryptedBytes = [Security.Cryptography.ProtectedData]::Protect( $plainBytes, $null, $scope )
$decryptedBytes = [Security.Cryptography.ProtectedData]::Unprotect( $encryptedBytes, $null, 0 )
Add a loop in your logn script that tries to encrypt/decrypt some random array of bytes until it succeeds.
I had the same issue: cmdkey was not working in Powershell when run as a User Logon Script.
In my case the issue was related to the user's group membership. The user was a member of the group "Power Users", but not a member of the group "Users" (or any other group).
According to this article from Microsoft, the group "Power Users" has "no default user rights", while the group "Users" has rights to "perform common tasks, such as running applications, using local and network printers".
The solution was to add my user(s) to the group "Users". This immediately solved the issue and allowed cmdkey to work in Powershell Logon Scripts.
I had this same problem with a PowerShell GPO logon script calling cmdkey.exe. The credentials populated into Credential Manager for Users, but Administrators the credentials did not show up. I found out that the credentials are saving in Credential Manager, but for the elevated user. If you run cmdkey /list in an elevated command prompt you will see the credentials there.