SharePoint OnLine Using PowerShell PNP - powershell

I am a young SharePoint OnLine user. I want Excel documents from all my sites to open directly with Excel and not Excel-OnLine. As I have a lot of sites and it would be long to make the sites one by one, I try to made a PowerShell without success :
$tenantName = "myTenant"
$username = "my#email.com"
$password = "myPassword"
$url = "MySharePointSiteToTest"
# Reference au module Pnp Client
# En cas de problème, vérifier les chemains d'accès !
$pnpModule = Get-Module SharePointPnPPowerShell* -ListAvailable
$pnpPath = $pnpModule.ModuleBase
Add-Type -Path "C:\PSTools\Modules\SharePointPnPPowerShellOnline\2.15.1705.0\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\PSTools\Modules\SharePointPnPPowerShellOnline\2.15.1705.0\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\PSTools\Modules\SharePointPnPPowerShellOnline\2.15.1705.0\Microsoft.SharePoint.Client.UserProfiles.dll"
Add-Type -Path "C:\PSTools\Modules\SharePointPnPPowerShellOnline\2.15.1705.0\Microsoft.Online.SharePoint.Client.Tenant.dll"
# internal params
$adminUrl = "https://$tenantName-admin.sharepoint.com"
$rootUrl = "https://$tenantName.sharepoint.com"
Write-Host *********************************
Write-Host "Admin Url : $adminUrl"
Write-Host "Root Url : $rootUrl"
Write-Host *********************************
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
# Admin connection
$adminCtx = New-Object Microsoft.SharePoint.Client.ClientContext($adminUrl)
# SharePoint Online with PNP
$psCredential = New-Object System.Management.Automation.PSCredential($username, $securePassword)
$spCredential = Get-Credential -Credential $psCredential
# PnP Connect
Connect-PnPOnline -Url $url -Credentials $spCredential
#Permet d'activer la fonctionalitée de l'ID correspondant
Enable-PnPFeature -Identity 8a4b8de2-6fd8-41e9-923c-c7c3c00f8295 -Force
I don't get an error. Obviously I have to forget something in the code

Related

How to use different owner in new-pnpsite command in powershell

I use New-PNPSite from PNP Module to create a new SharePoint communication site like this
$username = "admin#gmail.com"
$secpasswd = ConvertTo-SecureString -String "password" -AsPlainText -Force
$UserCredential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $username, $secpasswd
$Url = 'https://companyAdmin.sharepoint.com/'
Connect-PnPOnline -url $Url -Credentials $UserCredential
New-PNPSite -Type CommunicationSite -Title "Testing 2" -Owner "differentuser#gmail.com" -url "https://company.sharepoint.com/sites/jontesting2" -Lcid 1033
but I'm getting this error for some reason
New-PNPSite : {"SiteId":"","SiteStatus":3,"SiteUrl":""}
if I use the admin address admin#gmail.com in the owner parameter then I don't get the error and I'm able to create a new site. Any idea why it might be?
I wanted to use the admin account to create a new site for different owners that's why.

How to create a sharepoint site collection remotely via powershell?

How to create a new site collection remotely via Powershell
I have tried the following and all failed
Trial one:
# Create a PSCredential Object using the "User" and "Password" parameters that you passed to the job
$SecurePassword = '...............' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList "domain\user", $SecurePassword
$spms = New-PSSession -ComputerName servername -Credential $cred
$Parameters= #{
Session = $spms
ArgumentList ="siteurl","sitename",'domain\user','domain\user2'
ScriptBlock = { Param ($SiteURL,$SiteName,$SiteOwner,$SecondSiteOwner)
Add-PSSnapin Microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
Function Recreate_Site_Collection ($SiteURL,$SiteName,$SiteTemplate,$SiteOwner,$SecondSiteOwner){
# Delete Site Collection
$site = get-spsite -Identity $SiteURL -ErrorAction SilentlyContinue
if($site){
Write-host "Removing the site $SiteURL" -f Red
Remove-SPSite -Identity $SiteURL -Confirm:$false
}
# Create Site Collection
Write-host "creating the site $SiteURL" -f green
echo $SiteOwner
echo $SecondSiteOwner
New-SPSite -Name $SiteName -Url $SiteURL -Template $SiteTemplate -OwnerAlias $SiteOwner -SecondaryOwnerAlias $SecondSiteOwner -Confirm:$false
}
$SiteTemplate = "DEV#0" #Developer Site Template
Recreate_Site_Collection $SiteURL $SiteName $SiteTemplate $SiteOwner $SecondSiteOwner
}}
Invoke-Command #Parameters
Error:
The user cannot be found.
however, if I run the same code on the server with the same variables it goes ok when I run the PowerShell as an admin
Trial two:
# Create a PSCredential Object using the "User" and "Password" parameters that you passed to the job
$SecurePassword = '..........' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList "domain/user", $SecurePassword
$spms = New-PSSession -ComputerName servername -Credential $cred
$Parameters= #{
Session = $spms
ArgumentList = "siteurl","sitename",'domain/user',"1033","DEV#0"
ScriptBlock = { Param ($PortalUrl,$SiteName,$userName,$LCID,$WebTemplate)
$adminSiteUrl = "centraladminurl"
$user = "user"
$pwd = '..............'
$securePwd = ConvertTo-SecureString $pwd -AsPlainText -Force
$cred = New-Object PSCredential($user, $securePwd)
$wsdlUrl = $adminSiteUrl + "/_vti_adm/Admin.asmx?WSDL"
$svc = New-WebServiceProxy -Uri $wsdlUrl -Credential $cred
$svc.Timeout = 300000 # 5 minute timeout
$svc.CreateSite(
$siteUrl, # URL
$siteTitle, # Title
$Description, # Description
$LCID, # LCID 1033 arabic
$WebTemplate, # WebTemplate
$user, # Owner Login
"user", # Owner Name
"mail",
$PortalUrl ,
"portalname"
)}}
Invoke-Command #Parameters
Error:
Exception calling "CreateSite" with "10" argument(s): "Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown."
however, also when running the same script on the server itself with PowerShell run as admin it works with the same variables
please help
I need to automate SharePoint deployment from Jenkins which require a remotely PowerShell script and the main step is creating the site it cannot be established
It's definitely a permissions issue, but it can be kind of a pain to find. My user (the one running the script - probably your Jenkins user) was:
a local admin on the server,
listed in https://sharepointsite/ > Site Settings > Permissions > Site Collection Administrators.
but still got weird errors when running remotely:
# These commands did not work - I'm quoting the errors:
Enter-PSSession -ComputerName MySPServer
Add-PSSnapIn Microsoft.SharePoint.PowerShell
$URI = 'https://MySharePoint.domain.com'
# Can't pipe Site object to Web
Get-SPSite $URI | Get-SPWeb
'Get-SPWeb : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'
# Can't get SP users using web:
$web = Get-SPWeb $URI
Get-SPUser 'DOMAIN\user' -Web $web
'Get-SPUser : Cannot find an SPWeb object with Id or Url: 7aee0dc1-fe3b-4f9b-bd4b-000000000000 and Site Id: 8b662499-bb26-41ce-978e-000000000000.'
# Can't list properties of a site object
Get-SPSite $URI | fl
'Exception has been thrown by the target of an invocation.'
# Can't create a new site because the user can't be found:
New-SPSite -Url $URI -Name 'Test' -Description 'Test Site' -Template 'DEV#0' -OwnerAlias 'DOMAIN\user'
'New-SPSite : User cannot be found.'
I found that my user was not showing up as a site admin in powershell for some reason. Note that I'm running directly on the server here in order to view the users:
$URI = 'https://MySharePoint.domain.com'
$web = Get-SPWeb $uri
Get-SPUser "$env:USERDOMAIN\$env:USERNAME" -Web $web | Select UserLogin,IsSiteAdmin,IsSiteAuditor,AllowBrowseUserInfo
'UserLogin IsSiteAdmin IsSiteAuditor AllowBrowseUserInfo
--------- ----------- ------------- -------------------
DOMAIN\user False False True'
So I added myself as a site admin for my main site like so:
# Set my user as collection admin:
Get-SPUser 'DOMAIN\User' -Web $web | Set-SPUser -IsSiteCollectionAdmin:$true
# Check permissions again:
Get-SPUser "$env:USERDOMAIN\$env:USERNAME" -Web $web | Select UserLogin,IsSiteAdmin,IsSiteAuditor,AllowBrowseUserInfo
'UserLogin IsSiteAdmin IsSiteAuditor AllowBrowseUserInfo
--------- ----------- ------------- -------------------
DOMAIN\user True True True'
Get-SPSite $uri | fl UserIsSiteAdminInSystem
'UserIsSiteAdminInSystem : True'
And now all of the above commands work normally. It seems like the powershell module for sharepoint requires some access to the main webservice object in order to resolve usernames. I'm not sure what level of access is really required, but this worked for me.

while execute a powershell using service account getting unknown_user_type error

I have one simple powershell script where i'm authorizing salesforce logic app connector.
When i execute script using service account credentials I'm getting below error -
Connect-AzureRmAccount : unknown_user_type: Unknown User Type
At C:\Users\test.ps1:34 char:5
+ Connect-AzureRmAccount -Credential $pscredential -Tenant $Tenant ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Connect-AzureRmAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
what is going wrong here any clue?
i'm executing below script to authorize salesforce connector api connection into azure logic app
Param(
[string] $ResourceGroupName = 'ResourceGroupName',
[string] $Subscription = 'Subscription',
[string] $ConnectionName = 'ConnectionName',
#Defines which Authorization type to authenticate the connector with.
#AuthorizationTypes: 'ServiceAccount', 'ServicePrincipal'
[string] $AuthorizationType = 'ServiceAccount'
)
#region mini window, made by Scripting Guy Blog
Function Show-OAuthWindow {
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object -TypeName System.Windows.Forms.Form -Property #{Width=600;Height=800}
$web = New-Object -TypeName System.Windows.Forms.WebBrowser -Property #{Width=580;Height=780;Url=($url -f ($Scope -join "%20")) }
$DocComp = {
$Global:uri = $web.Url.AbsoluteUri
if ($Global:Uri -match "error=[^&]*|code=[^&]*") {$form.Close() }
}
$web.ScriptErrorsSuppressed = $true
$web.Add_DocumentCompleted($DocComp)
$form.Controls.Add($web)
$form.Add_Shown({$form.Activate()})
$form.ShowDialog() | Out-Null
}
#endregion
$pscredential = Get-Credential
#You should not need to change this Id
$Tenant = Get-AzureRmTenant -TenantId "TenantId"
if ($AuthorizationType -eq 'ServiceAccount') {
Connect-AzureRmAccount -Credential $pscredential -Tenant $Tenant -Subscription $Subscription
}
elseif ($AuthorizationType -eq 'ServicePrincipal') {
Connect-AzureRmAccount -ServicePrincipal -Credential $pscredential -Tenant $Tenant -Subscription $Subscription
}
As mentioned in the comment, I suppose you want to login with a service principal, I can also reproduce your issue.
If you want to login with a service principal, you need to pass the -ServicePrincipal parameter.
You could refer to the complete script below.
$azureAplicationId ="<applicationId>"
$azureTenantId= "<TenantId>"
$azurePassword = ConvertTo-SecureString "<client-secret>" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
Besides, I notice you use the old AzureRm module command Connect-AzureRmAccount. You should note the AzureRm module was deprecated and will not be updated anymore, so I recommend you to uninstall it and install the new Az module. If you still want to use the old module, just change Connect-AzAccount to Connect-AzureRmAccount in my script.

Login-AzureRmAccount wont log in using PSCredential

I am writing a PowerShell script to be able to access my Azure account. From the PowerShell command line, I can type Login-AzureRmAccount, manually enter my login information, and details of my account then display in the terminal inside PowerShell. However, if I try to make the script do the same thing, I get the following error:
And here is my code. Commented out is other ways i have tried so far.
# Credential Section
$azureAccountName ='login info here'
$azurePassword = ConvertTo-SecureString 'pass here' -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAccountName, $azurePassword)
Login-AzureRmAccount -Credential $psCred
#$tenantId = "tenant id here"
#$login = "login info here"
#$login1 = 'login info here'
#$pass1 = 'pass here'
#Create Credentials
#$pass = ConvertTo-SecureString 'pass here' -AsPlainText –Force
#$cred = New-Object -TypeName pscredential –ArgumentList $login1, $pass1
#Automate Future Logins
#Login-AzureRmAccount -Credential $psCred #-ServicePrincipal –TenantId $tenantId
$Subscription = Select-AzureSubscription -Default -SubscriptionName "sub info here"
$StorageAccountName = Get-AzureStorageAccount –StorageAccountName "account name here"
$StorageAccountKey = (Get-AzureStorageKey -StorageAccountName $StorageAccountName).Primary
$context = New-AzureStorageContext $StorageAccountName -StorageAccountKey $StorageAccountKey -SubscriptionName $Subscription
Write-Output $context
I entered the login and pass manually when i typed Login-AzureRmAccount into the terminal but the script doing the same thing would not login. Any thoughts?
If you are using a microsoft account like - outlook/hotmail account, it is bound to throw errors like the above. This is how Azure AD is designed. Please use any org account or create your own Azure AD and use the user credentials of that Azure AD to login using the "Login-AzureRMAccount".
These commands work for me
# Credential Section
$azureAccountName ="aaa#edmistorm.onmicrosoft.com"
$azurePassword = ConvertTo-SecureString "aaaaaabbb" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAccountName, $azurePassword)
Login-AzureRmAccount -Credential $psCred
$Subscription = Select-AzureSubscription -SubscriptionId 6f1ac837-2c76-4fd2-b6ce-8b991a0dec0ad
You may want to follow this thread as well
https://github.com/Azure/azure-powershell/issues/1309

Create Folder in DocLib of a Teamsite - Office 365 - Sharepoint Online

I want to create an example folder in a Document Library of a created Teamsite on Sharepoint Online using Powershell but am running into an error.
After I have created the Teamsite I use the following script:
#Retrieve list
$DocLibName = "Dokumente"
$FolderTitle = "Beispiel"
$List = $ctx.Web.Lists.GetByTitle($DocLibName)
$folder = $list.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder)
$folder["Title"] = $FolderTitle
$folder.Update();
$ctx.Load($List)
$ctx.ExecuteQuery()
Error Message
The type [Microsoft.SharePoint.SPFileSystemObjectType] was not found : Make sure that the assembly that contains this type is loaded.
Line:79 Char:1
+ $ Folder = $ List.addItem ("" [Microsoft.SharePoint.SPFileSystemObjectType ] :: Folde ...
It is not possible to use an index to a null array.
Line:80 Char:1
+ $ Folder ["Title"] = $FolderTitle
It is not possible to call a method for an expression of the NULL .
Line:81 Char:1
+ $Folder.Update();
How can this be resolved?
You are getting this error since Microsoft.SharePoint.SPFileSystemObjectTypetype belongs to SharePoint Server Side API which is not compatible with Office 365.
Below is demonstrated how to create a folder in SharePoint Online site via PowerShell (utilizes SharePoint CSOM API)
Function Create-Folder()
{
Param(
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.Folder]$ParentFolder,
[Parameter(Mandatory=$True)]
[String]$FolderName
)
$folder = $ParentFolder.Folders.Add($folderName)
$ParentFolder.Context.Load($folder)
$ParentFolder.Context.ExecuteQuery()
return $folder
}
Function Get-Context($Url,$Username,$Password){
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$ctx.Credentials = $credentials
return $ctx
}
Usage
$Url = "https://contoso.sharepoint.com/"
$UserName = "jdoe#contoso.onmicrosoft.com"
$Password = ""
$TargetFolderName = "Archive2016"
$ctx = Get-Context -Url $Url -Username $Username -Password $Password
$parentFolder = $ctx.Web.Lists.GetByTitle("Documents").RootFolder
$folder = Create-Folder -ParentFolder $parentFolder -FolderName $TargetFolderName
Write-Host "Folder [$TargetFolderName] has been created succesfully. Url: $($folder.ServerRelativeUrl)"
For creating a folder hierarchy the following script could be utilized:
Function Create-FolderHierarchy()
{
Param(
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.Folder]$ParentFolder,
[Parameter(Mandatory=$True)]
[String]$FolderUrl
)
$folderNames = $FolderUrl.Trim().Split("/",[System.StringSplitOptions]::RemoveEmptyEntries)
$folderName = $folderNames[0]
$curFolder = $ParentFolder.Folders.Add($folderName)
$ParentFolder.Context.Load($curFolder)
$ParentFolder.Context.ExecuteQuery()
if ($folderNames.Length -gt 1)
{
$curFolderUrl = [System.String]::Join("/", $folderNames, 1, $folderNames.Length - 1)
return Create-FolderHierarchy -ParentFolder $curFolder -FolderUrl $curFolderUrl
}
return $curFolder
}
If you are interested in scenario for uploading files while preserving a folder structure, take a look at How to: Upload files into Office 365 via PowerShell post, it contains ready made script for that purpose.