Trying to retrieve a token via PowerShell to PowerBI.
I manage to recieve the token but I guess it's being WordWrapped because using the variable gives me an error. If I copy the string and removes row cuts It works.
How can I prevent the token from being WordWrapped (It prints the value in rows not in one line)?
My Code - Version 1
#Username for login in Azure
$username = "name#domain.com"
#Password for login in Azure encrypted
$password = "0100000011100000000020000000000000..."
#Takes the username and convert the encrypted password and stores them in $cred variable
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username,($password | ConvertTo-SecureString)
#Uses the credentials to login to PowerBI
Login-PowerBI -Credential $cred
#Retrieves the login token that was created at login
$PowerBIToken = Get-PowerBIAccessToken
#The token is stored in $PowerBIToken.values but has "Bearer MYTOKEN" format, remove "Bearer "
$PowerBIToken = $PowerBIToken.values -replace 'Bearer '
#Adds " before and after the token since it is required I think to use the token
$PowerBIToken = "`"$PowerBIToken`""
#Writes to host the information formatted to verify If it is correct
Write-Host $PowerBIToken
#Disconnect the access to PowerBI
Disconnect-PowerBIServiceAccount
Clear-PBITableRows -authToken $PowerBIToken -DataSetId "11111111-7777-ffff-6666-dddddddddddd" -TableName "RealTimeData"
My Code - Version 2
#Username for login in Azure
$username = "name#domain.com"
#Password for login in Azure encrypted
$password = "0100000011100000000020000000000000..."
#Takes the username and convert the encrypted password and stores them in $cred variable
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username,($password | ConvertTo-SecureString)
#Uses the credentials to login to PowerBI
Login-PowerBI -Credential $cred
#Retrieves the login token that was created at login
$PowerBIToken = Get-PowerBIAccessToken
#Writes to host the information formatted to verify If it is correct
Write-Host $PowerBIToken.values
#Disconnect the access to PowerBI
Disconnect-PowerBIServiceAccount
Clear-PBITableRows -authToken $PowerBIToken.values -DataSetId "11111111-7777-ffff-6666-dddddddddddd" -TableName "RealTimeData"
Both versions above gives this error
Invoke-PBIRequest : The remote server returned an error: (403) Forbidden. - ''
At C:\Program Files\WindowsPowerShell\Modules\PowerBIPS\PowerBIPS.psm1:1410 char:5
+ Invoke-PBIRequest -authToken $authToken -method Delete -resource ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WebException
+ FullyQualifiedErrorId : System.Net.WebException,Invoke-PBIRequest
Without adding " to the token gives this error
Clear-PBITableRows : Cannot process argument transformation on parameter 'authToken'. Cannot convert value to type System.String.
At C:\Temp\PowerBI\PowerBI-AccessToken.ps1:12 char:35
+ Clear-PBITableRows -authToken $PowerBIToken -DataSetId "f866e111- ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Clear-PBITableRows], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Clear-PBITableRows
But if I copy the token string printed on the Write-Host command and put it instead of the $PowerBIToken variable in the final row Clear-PBITableRows... and removes all row cuts (wordWrappes) that command works as intended.
Related
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?
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?
I'm using the following module
https://psmsgraph.readthedocs.io/en/latest/
When attempting to pass in the following $AuthCode
#{AuthCodeCredential=System.Management.Automation.PSCredential; ResultURL=https://localhost/?code=AQABAAIAAADX8GCi6Js6SK82TsD2Pb7rsheCqji8MFS19OlJ8dFqrxjfk9
TTz9sPIyErZzaOD45niqpvZz5vnViz6tAU2BoKGQfX1-tW781HweG4jHoznO09NQpJDTiDl8i8yv6O_xT7RqUzitK59gssyyOPjc-4k5BEVa0hPJpXJCFHwUokCRzRBo4tS6Frv5XbxQkR8huM2Y1pK8o6Mq
PxKMPxGSfcrzS7vRjh-99qeD-DsXbc1eGGh1AQsWfTl1wqUlUcLJnMstF6ePnxIuM2XpRbFo7kYZ-5md7xrSD4Fw9L02NQjA-7TuOFM_4xXeM6gKL9SG8iW9Hxow0aNUm8ZtsLPBvAPJWJVrzhglVqz9pmmV
c9nAD1ujn2au2J9OlT_zwlXsJyHb3Gf4GqjQraYm91dV_7HzRj92LlCwjAwPypXFAhllYXPflUCgUtUYvvJfxSVS5Nc1meRUXlk-qedwv1RpbbT-pNHMPUuJmbEEM-sxAY1Oxg9GC93oH3S-rSMF5kZydr40
UOFwlnRIp10Vti6VA3IAA&session_state=25644a38-645f-4c8b-a6d9-be01838fa932; Application=Guid: 91ba65d8-2aa9-4771-9f9c-d05756da6931 Name: PowerShell Module; Au
thCodeBaseURL=https://login.microsoftonline.com/<mytenantid>/oauth2/authorize; Response=System.Collections.Hashtable; Issued=19/06/2
018 6:46:38 PM; Success=System.Management.Automation.PSScriptProperty; Expires=System.Management.Automation.PSScriptProperty; IsExpired=System.Management.Au
tomation.PSScriptProperty}
I get the following error:
Get-GraphOauthAccessToken : The remote server returned an error: (400) Bad Request.
At line:24 char:21
+ ... cessToken = Get-GraphOauthAccessToken -BaseURL 'https://login.microso ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WebException
+ FullyQualifiedErrorId : System.Net.WebException,Get-GraphOauthAccessToken
Here is the full code:
Import-Module -name 'PSMSGraph'
#In the credential prompt, provide your application's Client ID as the username and Client Secret as the password
$ClientCredential = Get-Credential
$GraphAppParams = #{
Name = 'PowerShell Module'
ClientCredential = $ClientCredential
RedirectUri = 'https://localhost/'
Tenant = '<mytenantid>'
}
$GraphApp = New-GraphApplication #GraphAppParams
Write-Host "Application"
Write-Host $GraphApp
Write-Host "-------------"
# This will prompt you to log in with your O365/Azure credentials.
# This is required at least once to authorize the application to act on behalf of your account
# The username and password is not passed back to or stored by PowerShell.
$AuthCode = Get-GraphOauthAuthorizationCode -BaseURL 'https://login.microsoftonline.com/<mytenantid>/oauth2/authorize' -Application $GraphApp
Write-Host 'Authorization Code'
Write-Host $AuthCode
Write-Host '----------------'
# see the following help for what resource to use.
# get-help Get-GraphOauthAccessToken -Parameter Resource
$GraphAccessToken = Get-GraphOauthAccessToken -BaseURL 'https://login.microsoftonline.com/<mytenantid>/oauth2/token' -AuthenticationCode $AuthCode -Resource "https://graph.microsoft.com"
$GraphAccessToken | Export-GraphOAuthAccessToken -Path 'c:\Temp\AccessToken.XML'
My problem is that there are numerous URLS that I could connect to and conflicting ideas of what my tenant id is so I'm not sure if I have either correct. This is for a company not a single user.
Edit - at the end of the day, all I want to be able to do is pull reports that are visible in https://portal.office.com/adminportal/home#/reportsUsage
I am new to powershell and I am trying to figure out how to insert my username and password into a website to login. Below is what I have come up with but failing to get it to work. Also the username and password are AD accounts if that matters.
URL of the site that will be launched.
$Url = “http://www.example.com”
$title = "User Authentication Required"
$message = "Enter user credentials for example.com"
$user = ""
$user_creds = $host.ui.PromptForCredential($title, $message, $user, "")
$IE = New-Object -com internetexplorer.application;
$IE.visible = $true;
$IE.navigate($url);
Wait a few seconds.
while ($IE.Busy -eq $true)
{Start-Sleep -Milliseconds 2000;}
The following UsernameElement, PasswordElement, and LoginElement need to be modified first.
# of the script for more details.
$IE.Document.getElementById(“userid”).value = $User_creds.Username
$IE.Document.getElementByID(“password”).value = $User_creds.password
$IE.Document.getElementById(“button-1034-btnIconEl”).Click()
This is the error I am getting now...
The property 'value' cannot be found on this object. Verify that the property
exists and can be set.
At C:\logon test.ps1:27 char:1
+ $IE.Document.getElementById("userid").value = $User_creds.Username
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
The property 'value' cannot be found on this object. Verify that the property
exists and can be set.
At C:\logon test.ps1:28 char:1
+ $IE.Document.getElementByID("password").value = $User_creds.password
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
If I run this in v2 it still does not input the username but for the password it gives an error of System.Management.Automation. The enter code to login is working. Can someone please explain how can I get a username and password to input into the website page and the password needs to be hidden/secured.
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()