How to use different owner in new-pnpsite command in powershell - 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.

Related

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.

Invoke-ASCmd : Authentication failed: User ID and Password are required when user interface is not available

I am trying to refresh credentials of an (already)deployed Tabular Model via CICD using Azure DevOps.
Making use of Invoke-ASCmd in PowerShell to refresh the credentials. The script works fine from local when I provide the Tenant ID, App ID and the Key. However it fails when I run it from Azure Devops with error - User ID and Password are required when user interface is not available.
Here is the script:
$azureTenantId= "TenantId"
$azurePassword = ConvertTo-SecureString "Key" -AsPlainText -Force
$azureAplicationId ="AppID"
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
Invoke-ASCmd `
-Server "AnalysisServerName" `
-Database "AdventureWorks" `
-Query "{
""createOrReplace"": {
""object"": {
""database"": ""AdventureWorks"",
""dataSource"": ""AzureBlobs/https://abc blob core windows net/""
},
""dataSource"": {
""type"": ""structured"",
""name"": ""AzureBlobs/https://abc blob core windows net/"",
""connectionDetails"": {
""protocol"": ""azure-blobs"",
""address"": {
""account"": ""abc"",
""domain"": ""blob.core.windows.net""
},
""authentication"": null,
""query"": null
},
""credential"": {
""AuthenticationKind"": ""Key"",
""kind"": ""AzureBlobs"",
""path"": ""https://abc.blob.core.windows.net/"",
""PrivacySetting"": ""Organizational"",
""Key"": ""Key""
}
}
}
}"
You can try using Add-AzureAnalysisServicesAccount to login to an instance of Azure Analysis Services server. See below:
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzureAnalysisServicesAccount -RolloutEnvironment 'eastus.asazure.windows.net' -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
Invoke-ASCmd ...
Check document Add-AzureAnalysisServicesAccount for more information. See this similar thread.
You can also try providing the credentials for Invoke-ASCmd command:
Invoke-ASCmd -Server "" -Database "" -Credential $psCred -TenantId $azureTenantId -ServicePrincipal -Query ""
Import-Module Azure.AnalysisServices
$azureappid ="tesappid"
$azureTenantId= "testid"
[ValidateNotNullOrEmpty()] $userPassword = "testpwd"
$userPassword = ConvertTo-SecureString -String $userPassword -AsPlainText -Force
$userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $azureappid, $userPassword
Add-AzureAnalysisServicesAccount -RolloutEnvironment 'eastus.asazure.windows.net' -Credential $userCredential -TenantId $azureTenantId -ServicePrincipal
Invoke-Ascmd ....

How can I give a password as parameter using the Graph API for Azure-AD and Intune?

Following the example found here: https://github.com/microsoftgraph/powershell-intune-samples/blob/master/Authentication/Auth_From_File.ps1
More specifically:
$UserPassword = get-Content "$Password" | ConvertTo-SecureString
$userCredentials = new-object Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential -ArgumentList $userUPN,$UserPassword
$authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, $resourceAppIdURI, $clientid, $userCredentials).Result;
I've tried the following:
$UserPassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
$userCredentials = new-object Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential -ArgumentList $userUPN,$UserPassword
$authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, $resourceAppIdURI, $clientid, $userCredentials).Result;
However, I've been getting the error that
Authorization Access Token is null, please re-run authentication...
which can be found further in the code.
if($authResult.AccessToken){
[...]
Write-Host
Write-Host "Authorization Access Token is null, please re-run authentication..." -ForegroundColor Red
Write-Host
break
Am I correct in thinking that I probably need to give the password in a different way?
Alright, I think I found whatever went wrong. I tried running another script and had to manually enter the credentials. This prompted me to accept a whole lot of permissions from Microsoft. I think that was the problem. This code now works:
$userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($User, "OptionalDisplayableId")
$UserPassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
$userCredentials = new-object Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential -ArgumentList $userUPN,$UserPassword
$authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, $resourceAppIdURI, $clientid, $userCredentials).Result;
Still, thank you Mathias and Marc for trying to help :)

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

Can't use send-mailmessage when using PSFTP Module

I've made a Powershell script which uploads data to a NAS.
After the Upload is completed the script should send an Email message.
When the script tries to send a mailmessage I get an error saying I used an incorrect security certificate.
This error only shows up when I use the PSFTP module. When i run the sendmail code on its own it works just fine.
The FTP session itself isn't alive anymore so this shouldn't be a problem.
Can someone point me in the right direction to sort this problem out?I've made a Powershell script which uploads data to a NAS.
After the Upload is completed the script should send an Email message.
When the script tries to send a mailmessage I get an error saying I used an incorrect security certificate.
This error only shows up when I use the PSFTP module. When i run the sendmail code on its own it works just fine.
The FTP session itself isn't alive anymore so this shouldn't be a problem.
Can someone point me in the right direction to sort this problem out?
$Execution = Get-ExecutionPolicy
If($Execution -eq "RemoteSigned")
{
Write-Host "HOI" -BackgroundColor Black -ForegroundColor Green
}
Else
{
Set-ExecutionPolicy Remotesigned
}
1.Module PSFTP importing
Import-Module PSFTP
$secpasswd = ConvertTo-SecureString “Wachtwoord” -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential (“Admin”, $secpasswd)
Variables
$Session = "Alive"
$ftp = "IP"
$Credentials = "Admin"
$FtpFile = "C:\Test\Back-up.ps1"
$ftpDestination = "FTPLOCATIE"
2.Connect to FTP with module PSFTP
Set-FTPConnection -Server $ftp -Credentials $mycreds -Session $Session
( Connect to ftp)
3.TPItem for uploading to NAS
Get-ChildItem $FtpFile | Add-FTPItem -Session $Session -Path $ftpDestination -Overwrite
4.Section for mailing,variables
$secpasswd = ConvertTo-SecureString “Wachtwoord” -AsPlainText -Force
$mycredsMail = New-Object System.Management.Automation.PSCredential (“Email-address”, $secpasswd)
5. Section for mailing
$Smtp = "smtp.office365.com"
$Port = "587"
$To = "Email"
$Subject = "Back-up"
$From = "Email
6. this is where i want send the mail i use ssl
Send-MailMessage -to $To -from $From -Subject $Subject -SmtpServer $Smtp -Credential $mycredsMail -Port $Port -UseSsl