ExecuteCrmOrganizationRequest fails with PublishThemeRequest - powershell

I'm trying to write a powershell script to publish a theme in my on-premise installation of Dynamics CRM.
According to this page it should be really straight forward, I create an object of type PublishThemeRequest which derives from OrganizationRequest and call the method ExecuteCrmOrganizationRequest.
This is the code I'm running:
Import-Module Microsoft.Xrm.Data.Powershell
Add-PSSnapin Microsoft.Xrm.Tooling.Connector
$orgName = "<my organization name>";
$serverUrl = "http://server_url";
$Cred = Get-Credential -UserName "<my username>" -Message "Please Enter admin credentials for CRM"
$conn = Get-CrmConnection -Credential $Cred -OrganizationName $orgName -ServerUrl $serverUrl
$req = New-Object Microsoft.Crm.Sdk.Messages.PublishThemeRequest
$req.Target = New-CrmEntityReference -EntityLogicalName "theme" -Id "DB80D57A-6410-4D11-B784-0093122802AC"
$result = [Microsoft.Crm.Sdk.Messages.PublishThemeResponse]$conn.ExecuteCrmOrganizationRequest($req, $null)
This is what I get when I execute the code above:
Cannot convert argument "req", with value: "Microsoft.Crm.Sdk.Messages.PublishThemeRequest", for "ExecuteCrmOrganizationRequest" to type
"Microsoft.Xrm.Sdk.OrganizationRequest": "Cannot convert the "Microsoft.Crm.Sdk.Messages.PublishThemeRequest" value of type
"Microsoft.Crm.Sdk.Messages.PublishThemeRequest" to type "Microsoft.Xrm.Sdk.OrganizationRequest"."
At C:\Users\xxxxxxxxxx\Desktop\PublishTheme.ps1:21 char:1
+ $result = [Microsoft.Crm.Sdk.Messages.PublishThemeResponse]$conn.Exec ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
I have been reading the documentation and other websites for a couple of hours now but seem to have hit a wall.
Any ideas of what my problem might be?

Related

PowerShell authenticate and read google calendar events

Using PowerShell, I am trying to authenticate to Google calendar using a service account, and read events. With the help of stack overflow, I was able to install and import the required packages in my PowerShell session.
Newtonsoft.Json
Google.Apis.Core
Google.Apis
Google.Apis.Auth
Google.Apis.Calendar.v3
I then tried to read Google calendar events
# Set the credentials and calendar ID
$credentials = Get-Content "C:\Users\Windows\Desktop\powershell-376318-70973daa61d9.json" | ConvertFrom-Json
$calendarId = "primary"
# Build the calendar service
$service = New-Object Google.Apis.Calendar.v3.CalendarService
$service.Credentials = New-Object Google.Apis.Auth.OAuth2.GoogleCredential($credentials)
# Get the current time
$now = Get-Date
# Get the events for the next hour
$events = $service.Events.List($calendarId)
$events.TimeMin = $now
$events.TimeMax = $now.AddHours(1)
$events.SingleEvents = $true
$events.OrderBy = "startTime"
$events = $events.Execute()
# Print the events
foreach ($event in $events.Items) {
Write-Host "Event: $($event.Summary)"
Write-Host "Start Time: $($event.Start.DateTime)"
Write-Host "End Time: $($event.End.DateTime)"
Write-Host ""
}
But I get this error
New-Object : A constructor was not found. Cannot find an appropriate constructor for type
Google.Apis.Auth.OAuth2.GoogleCredential.
At line:7 char:24
+ ... edentials = New-Object Google.Apis.Auth.OAuth2.GoogleCredential($cred ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
Exception calling "Execute" with "0" argument(s): "The service calendar has thrown an exception. HttpStatusCode is
Forbidden. The request is missing a valid API key."
At line:18 char:1
+ $events = $events.Execute()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : GoogleApiException
Obviously, there's an issue with "Google.Apis.Auth.OAuth2.GoogleCredential". I'm not sure it's even possible to authenticate and read events using a service account, but right now I don't know how to proceed with this.
I want to avoid using OAuth2 client id and client secret for authentication if possible, because I've had issues in the past with token expiries, whereas a service account doesn't expire.
The error message tells you exactly what the problem is:
Cannot find an appropriate constructor for type Google.Apis.Auth.OAuth2.GoogleCredential.
Having a look at the docs shows: There really is no constructor like GoogleCredential(string). But you can use different static methods to create a GoogleCredential object. E. g. FromJson(String):
# Set the credentials and calendar ID
$credentials = Get-Content -Raw -Path "C:\Users\Windows\Desktop\powershell-376318-70973daa61d9.json"
# Build the calendar service
$service = New-Object Google.Apis.Calendar.v3.CalendarService
$service.Credentials = [Google.Apis.Auth.OAuth2.GoogleCredential]::FromJson($credentials)
You can also pass the file directly to GoogleCredential via FromFile:
# Build the calendar service
$service = New-Object Google.Apis.Calendar.v3.CalendarService
$service.Credentials = [Google.Apis.Auth.OAuth2.GoogleCredential]::FromFile('C:\Users\Windows\Desktop\powershell-376318-70973daa61d9.json')

Creating user policy Powershell MicrosoftTeams session error

When I try to create a user policy for my active directory I get this error:
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is
not null or empty, and then try the command again.
At C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\2.3.1\net472\SfBORemotePowershellModule.psm1:22959 char:38
+ ... -Session (Get-PSImplicitRemotingSession -CommandName 'New-CsApplic ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
The code that I'm using is this:
Import-Module MicrosoftTeams
# Get the credentials
$password = ConvertTo-SecureString -AsPlainText -Force -String "password"
$credentials = New-Object System.Management.Automation.PsCredential("email", $password)
# Connect to Microsoft Teams
Connect-MicrosoftTeams -Credential $credentials
New-CsApplicationAccessPolicy -Identity Random -AppIds "appid" -Description "Users"
Grant-CsApplicationAccessPolicy -PolicyName Random -Identity "userObjectId"
I know that the command New-CsApplicationAccessPolicy is creating the error but my guess is that it's caused by the command Connect-MicrosoftTeams because from what I can understand is that Connect-MicrosoftTeams creates a session.
Is there a way to set the session via a parameter or is this something you need to do outside this method?

Sharepoint Timezone Change Powershell

I need to change the timezone for all sites within sharepoint. I run this code that i found online.
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#function to change Timezone regional settings of a SharePoint Online site
Function Set-SPOnlineTimeZone([String]$SiteURL,[String]$TimezoneName,[PSCredential]$Cred)
{
Try
{
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Set up the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $credentials
#Get the Root web from given URL
$Web = $Ctx.web
$Ctx.Load($Web)
#Get the Time zone to update
$Timezones = $Web.RegionalSettings.TimeZones
$Ctx.Load($Timezones)
$Ctx.ExecuteQuery()
$NewTimezone = $Timezones | Where {$_.Description -eq $TimezoneName}
#Update the timezone of the site
$Web.RegionalSettings.TimeZone = $NewTimezone
$Web.Update()
$Ctx.ExecuteQuery()
Write-host -f Green "Timezone has been updated for "$Web.Url
#Get all subsites of the web
$Ctx.Load($Web.Webs)
$Ctx.executeQuery()
#Iterate through each subsites and call the function recursively
Foreach ($Subweb in $Web.Webs)
{
#Call the function to set Timezone for the web
Set-SPOnlineTimeZone -SiteURL $Subweb.URL -TimezoneName $TimezoneName -Cred $AdminCredentials
}
}
Catch [System.Exception]
{
Write-Host -f Red $_.Exception.Message
}
}
#Config parameters for SharePoint Online Admin Center and Timezone description
$AdminSiteURL = "https://crescent-admin.sharepoint.com/"
$TimezoneName ="(UTC+04:00) Abu Dhabi, Muscat"
#Get credentials to connect to SharePoint Online Admin Center
$AdminCredentials = Get-Credential
#Connect to SharePoint Online Tenant Admin
Connect-SPOService -URL $AdminSiteURL -Credential $AdminCredentials
#Get all Site Collections
$SitesCollection = Get-SPOSite -Limit ALL
#Iterate through each site collection
ForEach($Site in $SitesCollection)
{
Write-host -f Yellow "Setting Timezone for Site Collection:"$Site.URL
#Call the function to set Timezone for the site
Set-SPOnlineTimeZone -SiteURL $Site.URL -TimezoneName $TimezoneName -cred $AdminCredentials
}
#Read more: https://www.sharepointdiary.com/2017/06/sharepoint-online-change-time-zone-using-powershell.html#ixzz68Mt3Xrom
I gett the following error
At line:10 char:16
+ ... edentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Exception calling "ExecuteQuery" with "0" argument(s): "The sign-in name or password does not match one in the Microsoft account system."
At line:19 char:1
+ $Ctx.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdcrlException
An error occurred while enumerating through a collection: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested..
At line:22 char:1
+ $Timezones | Select ID, Description
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Share...lient.TimeZone]:<GetEnumerator>d__0) [], RuntimeException
+ FullyQualifiedErrorId : BadEnumeration
The account that i'm using is admin account for office365 (globle admin)however it has 2fa. I'm assumuing there needs to be some other method for this but no idea. Any help will be appreciated
According the Microsofts documentation on the Connect-SP* command, if your account is using 2FA you'll want to omit the credentials from your connect statement and let it prompt you for credentials manually.
https://learn.microsoft.com/en-us/powershell/module/sharepoint-online/connect-sposervice?view=sharepoint-ps
See example 3
If you are using MFA in your environment, I would suggest you use sharepoint pnp powesrhsell.
You could refer to the below articles for more:
https://techcommunity.microsoft.com/t5/SharePoint/Using-SharePoint-Client-Side-Object-Model-with-PowerShell-and/m-p/92734
https://www.c-sharpcorner.com/blogs/using-csom-to-connect-to-a-sharepoint-site-with-multi-factor-authentication-enabled

Powershell - Secure String for Passwords and SFTP

I am trying to implement a way to use a stored secure string so that my SFTP password is not visiable in the script. For example, I'd like to generate a variable $password that could be used instead. I found the following examples online but I can't get them to work unfortunately. I've done something similar in the past but can find my notes or links to the website that explained how to complete the task.
read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
Here is my script. Here is a link to the snapin if anyone is interested. http://www.k-tools.nl/index.php/sftp-in-powershell/
#Add the SFTP snap-in
Add-PSSnapin KTools.PowerShell.SFTP
#Define some variables
$sftpHost = "ftp.domain.com"
$userName = "user"
$userPassword = "password"
$localFile = "C:\bin\emp1.xlsx"
#Open the SFTP connection
$sftp = Open-SFTPServer -serverAddress $sftpHost -userName $userName -userPassword $userPassword
#Upload the local file to the root folder on the SFTP server
$sftp.Put($localFile)
#Close the SFTP connection
$sftp.Close()
Again, thanks for everyones help!
UPDATE
I tried this:
$pass = cat c:\bin\ftpcreds.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "usertest1",$pass
$sftpHost = "ftp.domain.com"
$userName = $mycred.username
$userPassword = $mycred.password
$sftp = Open-SFTPServer -serverAddress $sftpHost -userName $userName -userPassword $userPassword
$sftp.Put($localFile)
$sftp.Close()
And get this error:
Method invocation failed because [Tamir.SharpSsh.jsch.JSchException] doesn't contain a method named 'Put'.
At C:\bin\SFTP Upload Samples.ps1:21 char:1
+ $sftp.Put($localFile)
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [Tamir.SharpSsh.jsch.JSchException] doesn't contain a method named 'Close'.
At C:\bin\SFTP Upload Samples.ps1:36 char:1
+ $sftp.Close()
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Any suggestions?
Thanks!
If your SFTP is wanting to use a decrypted version of your secured password then you'll want to extract it from your $mycred by:
$userpassword = $mycred.getnetworkcredential().password.tostring()

Powershell CMDLET Cross Domain Managment

I'm logged in at domain "domain1" with my account. I wish via powershell to be able to update users in domain "domain2" via my supe ruser account "suaccount" with password "password1". Trust is established between the two.
Running PowerShell 2.0 and .NET 3.5 SP1
I have gotten this far:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$context = New-Object -TypeName
System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype, "domain2", "OU=TestOU,DC=domain2", "suaccount", "password1"
$usr = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList $context
$usr.Name = "AM Test1"
$usr.DisplayName = "AM Test1"
$usr.GivenName = "AM"
$usr.SurName = "Test1"
$usr.SamAccountName = "AMTest1"
$usr.UserPrincipalName = "amtest1#mtest.test"
$usr.PasswordNotRequired = $false
$usr.SetPassword("errr")
$usr.Enabled = $true
$usr.Save()
Pretty new to PowerShell, any pointers? I want to edit/create users on the "other" domain so to speak.
I get the error:
"Exception calling "Save" with "0" argument(s): "General access denied error
"
At C:\Script\Sandbox\Morris PowerShell Application\includes\mo\mo.ps1:104 char:14
+ $usr.Save <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException"
Any pointers?
From comments: Try using for username this format domain2\username, and always use the FQDN for the domain. – Christian yesterday