Gateway Binding using the API - powerbi

I get an Error 400 (Bad Request) using the code below. I have looked at it for hours. Does anyone see anything wrong? Any suggestions? I've tried the suggestions in this link, but no luck: https://community.powerbi.com/t5/Developer/BindToGateway-Powershell-REST-API-POST-failing-Need-Help/m-p/852851
#Login to Power BI using PowerBIPS App registration.
Write-Host "Start Login"
$ApplicationId = "abc123"
$SecurePassword = "password" | ConvertTo-SecureString -AsPlainText -force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList
$ApplicationId, $SecurePassword
Connect-PowerBIServiceAccount -ServicePrincipal -Credential $credential -TenantId "ten123"
Write-Host "Login Success"
Write-Host "Get Workspace info for workspace: AC Common_TST"
$workspaceName = "AC Common_TST"
$datasetName = "DateDim"
$workspace = Get-PowerBIWorkspace -Name $workspaceName
$workspaceObject = ( Get-PowerBIWorkspace -Name "AC Common_TST" )
$groupid=$workspaceObject.id
$newGatewayId = "gatewayid" # the ID of PRDGateway1
$dataset = Get-PowerBIDataset -WorkspaceId $workspace.Id | Where-Object Name -eq $datasetName
$datasetid = $dataset.id
$workspaceId = $workspace.Id
Write-Host "GroupID is "$workspace.id
Write-Host "Dataset ID is "$dataset.id
# POST body
$postParams = #'
{
"gatewayObjectId": "gatewayid",
"datasourceObjectIds": [
"dsid"
]
}
'#
$jsonPostBody = $postParams | ConvertTo-JSON
$uri = "https://api.powerbi.com/v1.0/myorg/groups/$workspaceid/datasets/$datasetId/Default.BindToGateway"
Invoke-PowerBIRestMethod -URL $uri -Method POST -Body $jsonPostBody
Resolve-PowerBIError -Last

Related

Creating AWS SSM Document to run Powershell commands

Im trying to make an SSM Document that runs the following Powershell script:
New-Item -ItemType Directory -Force -Path C:\temp
$checkupdatesscript = "`$UpdateSession = New-Object -ComObject Microsoft.Update.Session"
$checkupdatesscript | Out-File C:\temp\checkwindowsupdates.ps1
Add-Content -Path C:\temp\checkwindowsupdates.ps1 -Value "`$UpdateSearcher = `$UpdateSession.CreateupdateSearcher()"
Add-Content -Path C:\temp\checkwindowsupdates.ps1 -Value "`$Updates = #(`$UpdateSearcher.Search(`"IsHidden=0 and IsInstalled=0`").Updates)"
Add-Content -Path C:\temp\checkwindowsupdates.ps1 -Value "`$Updates | Select-Object Title > C:\temp\windowsupdates.txt"
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "C:\temp\checkwindowsupdates.ps1"
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Check Windows Updates" -Description "checks for any outstanding windows updates every 5 minutes"
I have created the following SSM Document in YAML:
---
schemaVersion: "2.2"
description: "Creates script and scheduled task to check for any outstanding windows updates every 5 minutes"
mainSteps:
- action: "aws:runPowerShellScript"
name: "RunCommands"
inputs:
runCommand:
- "New-Item -ItemType Directory -Force -Path C:\temp"
- "$checkupdatesscript = \"`$UpdateSession = New-Object -ComObject Microsoft.Update.Session\""
- "$checkupdatesscript | Out-File C:\temp\checkwindowsupdates.ps1"
- "Add-Content -Path C:\temp\checkwindowsupdates.ps1 -Value \"`$UpdateSearcher = `$UpdateSession.CreateupdateSearcher()\""
- "Add-Content -Path C:\temp\checkwindowsupdates.ps1 -Value \"`$Updates = #(`$UpdateSearcher.Search(`\"IsHidden=0 and IsInstalled=0`\").Updates)\""
- "Add-Content -Path C:\temp\checkwindowsupdates.ps1 -Value \"`$Updates | Select-Object Title > C:\temp\windowsupdates.txt\""
- "$action = New-ScheduledTaskAction -Execute \"Powershell.exe\" -Argument \"C:\temp\checkwindowsupdates.ps1\""
- "$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)"
- "Register-ScheduledTask -Action $action -Trigger $trigger -TaskName \"Check Windows Updates\" -Description \"checks for any outstanding windows updates every 5 minutes\""
But am receiving an error when attempting to create the document. The error is "InvalidDocumentContent: null"
I am assuming I have messed up the YAML but can't seem to figure out what.
The issue did lie within the YAML. I had not escaped the backslashes in the file paths. The correct yaml should look like this:
---
schemaVersion: "2.2"
description: "Creates script and scheduled task to check for any outstanding windows updates every 5 minutes"
mainSteps:
- action: "aws:runPowerShellScript"
name: "RunCommands"
inputs:
runCommand:
- "New-Item -ItemType Directory -Force -Path C:\\temp"
- "$checkupdatesscript = \"`$UpdateSession = New-Object -ComObject Microsoft.Update.Session\""
- "$checkupdatesscript | Out-File C:\\temp\\checkwindowsupdates.ps1"
- "Add-Content -Path C:\\temp\\checkwindowsupdates.ps1 -Value \"`$UpdateSearcher = `$UpdateSession.CreateupdateSearcher()\""
- "Add-Content -Path C:\\temp\\checkwindowsupdates.ps1 -Value \"`$Updates = #(`$UpdateSearcher.Search(`\"IsHidden=0 and IsInstalled=0`\").Updates)\""
- "Add-Content -Path C:\\temp\\checkwindowsupdates.ps1 -Value \"`$Updates | Select-Object Title > C:\\temp\\windowsupdates.txt\""
- "$action = New-ScheduledTaskAction -Execute \"Powershell.exe\" -Argument \"C:\\temp\\checkwindowsupdates.ps1\""
- "$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)"
- "Register-ScheduledTask -Action $action -Trigger $trigger -TaskName \"Check Windows Updates\" -Description \"checks for any outstanding windows updates every 5 minutes\""

Why Am I Seeing These Errors in My SSRS Powershell Script in One Environment but Not Another?

I have a Powershell Script I'm working on for post-migration SSRS report administration tasks.
In this particular scenario we have a DEV environment (where I've been primarily testing) which hosts a single instance of SSRS, and a Prod environment which is a scaled out deployment across 4 nodes.
I'm new to Powershell (just discovered it 2 days ago...) and the script I have is pretty simple:
Clear-Host 
$Username = "domain\myUsername"
$Password = "myPassword"
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($Username,(ConvertTo-SecureString -String $Password -AsPlainText -Force))
# Dev Connection String
$webServiceUrl = 'http://DEVwebServer.domain.com/reportserver/reportservice2010.asmx?WSDL'
# Prod Connection String
# $webServiceUrl = 'http://PRODwebServerNode1.domain.com/reportserver/reportservice2010.asmx?WSDL'
$rs = New-WebServiceProxy -Uri $webServiceUrl -Credential $Cred
 
$reports = $rs.ListChildren("/Some Folder Under Root", $true) | Where-Object { $_.TypeName -eq "Report" }
$type = $ssrsProxy.GetType().Namespace;
$schedDefType = "{0}.ScheduleDefinition" -f $type;
$schedDef = New-Object ($schedDefType)
$warning = #();
foreach ($report in $reports) {
$sched = $rs.GetExecutionOptions($report.Path, [ref]$schedDef);
$snapShotExists = $rs.ListItemHistory($report.Path);
if($sched -eq "Snapshot") {
Write-Host "Following report is configured to run from Snapshot:" -ForegroundColor Yellow
Write-Host ("Report Name: {0}`nReport Path: {1}`nExecution Type: {2}`n" -f $report.Name, $report.Path, $sched)
if ($snapShotExists) {
Write-Host "Does Snapshot Exist..?`n" -ForegroundColor Yellow
Write-Host "Yes!`tNumber of Snapshots: " $snapShotExists.Count -ForegroundColor Green
$snapShotExists.CreationDate
Write-Host "`n------------------------------------------------------------"
}
elseif (!$snapShotExists) {
Write-Host "Does Snapshot Exist..?`n" -ForegroundColor Yellow
Write-Host ("No!`n") -ForegroundColor Red
Write-Host "Creating Snapshot.......`n" -ForegroundColor Yellow
$rs.CreateItemHistorySnapshot($report.Path, [ref]$warning);
Write-Host "Snapshot Created!`n" -ForegroundColor Green
$snapShotExists.CreationDate
Write-Host "`n------------------------------------------------------------"
}
}
}
The purpose of the script is simply to recursively iterate over all of the reports for the given folder in the $reports variable, check to see if the execution type is set to "Snapshot", if it is check to see if a "History Snapshot" exists, and if one does not exist, create one.
When I run this in Dev it works just fine, but when I run in PROD I get the following error repeated for each $report in my foreach loop:
Any ideas on why this would work in one and not the other and how to overcome this error?
I was able to get this working on the Prod instance by making some adjustments using this answer as a guide:
By updating my call to New-WebServiceProxy to add a Class and Namespace flag, I was able to update the script in the following ways:
...
# Add Class and Namespace flags to New-WebServiceProxy call
$rs = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $webServiceUrl -Credential $Cred
 
$reports = $rs.ListChildren("/Business and Technology Solutions", $true) | Where-Object { $_.TypeName -eq "Report" }
# Declare new "ScheduleDefintion object using the Class declared in the New-WebServiceProxy call
$schedDef = New-Object RS.ScheduleDefinition
$warning = #();
foreach ($report in $reports) {
# Referencing the "Item" property from the ScheduleDefinition
$execType = $rs.GetExecutionOptions($report.Path, [ref]$schedDef.Item)
...
I don't think the adding of the Class and Namespace flags on the New-WebServiceProxy call was exactly what did it, as I think it's just a cleaner way to ensure you're getting the proper Namespace from the WebService. Maybe just a little sugar.
I think the key change was making sure to the "Item" property from the schedule definition object, although I'm not sure why it was working in Dev without doing so...

Invoke-RestMethod not accepting letters with accent

I have a service on SharePoint 2013 which is responsible for managing custom menu.
I'm trying to use this service from PowerShell like this:
$MenuItem = New-Object -TypeName PSObject
$MenuItem | Add-Member -MemberType NoteProperty -Name LinkEN -Value $pageLink
$MenuItem | Add-Member -MemberType NoteProperty -Name LinkFR -Value $pageLink
$MenuItem | Add-Member -MemberType NoteProperty -Name TitleEN -Value $pageParam.ListTitle;
$MenuItem | Add-Member -MemberType NoteProperty -Name TitleFR -Value $pageParam.ListTitle;
$body = #{ _menuItem = $MenuItem; _parent = $null } | ConvertTo-Json
$url = $url + "/_vti_bin/MenuService.svc/AddMenuItem"
$result = Invoke-RestMethod -Uri $url -Method Post -UseDefaultCredentials -ContentType "application/json; charset=utf-8" -Body $body
It works fine up to the moment when I'm trying to send letter with an accent (e.g. è) through parameters (for example: $pageParam.ListTitle = "ètè").
In this situation I'm getting the following error:
Invoke-RestMethod : Request Error The server encountered an error
processing the request. See server logs for more details. At
FixDocumentPages.ps1:145 char:19
+ $result = Invoke-RestMethod -Uri $url -Method Post -UseDefaultCredential ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I have breakpoint in the server code, but it never gets that far.
Below are the SharePoint logs from this incident:
Entering monitored scope (Request(POST: http://wssppoc:5000/_vti_bin/MenuService.svc/AddMenuItem )). Parent No Name=Request(POST:http ://wssppoc:5000/_vti_bin/MenuService.svc/AddMenuItem) 4af4519d-0879-c02e-e1ad-bb2bcbb09abb Non-OAuth request. IsAuthenticated=False, UserIdentityName=, ClaimsCount=0 4af4519d-0879-c02e-e1ad-bb2bcbb09abb Micro Trace Tags: 0 nasq,1 agb9s 4af4519d-0879-c02e-e1ad-bb2bcbb09abb
Leaving Monitored Scope (Request(POST:http ://wssppoc:5000/_vti_bin/MenuService.svc/AddMenuItem)). Execution Time=1,7839 4af4519d-0879-c02e-e1ad-bb2bcbb09abb
Entering monitored scope (Request(POST:http://wssppoc:5000/_vti_bin/MenuService.svc/AddMenuItem)). Parent No Name=Request(POST:http ://wssppoc:5000/_vti_bin/MenuService.svc/AddMenuItem) 4af4519d-087a-c02e-e1ad-b0990e08ad35 Micro Trace Tags: 0 nasq 4af4519d-087a-c02e-e1ad-b0990e08ad35
Leaving Monitored Scope (Request(POST:http://wssppoc:5000/_vti_bin/MenuService.svc/AddMenuItem)). Execution Time=0,6495 4af4519d-087a-c02e-e1ad-b0990e08ad35
Entering monitored scope (Request(POST:http://wssppoc:5000/_vti_bin/MenuService.svc/AddMenuItem)). Parent No Name=Request(POST:http ://wssppoc:5000/_vti_bin/MenuService.svc/AddMenuItem) 4af4519d-087a-c02e-e1ad-bb3e80204d39 Non-OAuth request. IsAuthenticated=True, UserIdentityName=0#.w|test\administrator, ClaimsCount=29 4af4519d-087a-c02e-e1ad-bb3e80204d39 Micro Trace Tags: 0 nasq,1 agb9s 4af4519d-087a-c02e-e1ad-bb3e80204d39
Leaving Monitored Scope (Request(POST:http://wssppoc:5000/_vti_bin/MenuService.svc/AddMenuItem)). Execution Time=3,9189 4af4519d-087a-c02e-e1ad-bb3e80204d39 ContentIntegrationEngine: Execution started, flow identifier is 4659ab80-0016-499b-a3ff-c1961ca797bd.
Does anyone have any idea what could be wrong?
Sam answer is leading to the proper solution. Which is using:
[System.Text.Encoding]::UTF8.GetBytes()
Working code is:
$MenuItem = New-Object -TypeName PSObject
$MenuItem | Add-Member -MemberType NoteProperty -Name LinkEN -Value $pageLink
$MenuItem | Add-Member -MemberType NoteProperty -Name LinkFR -Value $pageLink
$MenuItem | Add-Member -MemberType NoteProperty -Name TitleEN -Value $pageParam.ListTitle;
$MenuItem | Add-Member -MemberType NoteProperty -Name TitleFR -Value $pageParam.ListTitle;
$body = #{ _menuItem = $MenuItem; _parent = $null } | ConvertTo-Json
$url = $url + "/_vti_bin/MenuService.svc/AddMenuItem"
$body = [System.Text.Encoding]::UTF8.GetBytes($body);
$result = Invoke-RestMethod -Uri $url -Method Post -UseDefaultCredentials -ContentType "application/json; charset=utf-8" -Body $body

How I can show and add items to Sharepoint List via Powershell?

hi I want to show and add items in Sharepoint via Powershell (I use for testing a list and a libary)
The name is Powershell-Test
the Url is
http//intranet/departments/it/abt/Lists/Powershell-Test/AllItems.aspx
I enable remote on the Sharepoint Server and make a remote connection to this from my localhost.
Enter-PSSession -ComputerName [sharepoint server] -Authentication Negotiate -Credential [Domain\name]
if((Get-PSSnapin -Name Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue) -eq $null)
{
Add-PSSnapin Microsoft.Sharepoint.Powershell
}
$webURL = "http//intranet/departments/it/abt/Lists/"
$listname = "Powershell-Test"
$web = Get-SPWeb $webURL
$web.lists | format-table title
$list = $web.LIsts[$listName]
$list.items | foreach { $_[„Title“] + „`n“ + $_[„Body“] }
The Problem is that I don#t get the connection to the list :(
How I can to this?
I presume you have permission to access the site.
I also presume you don't have a site or subsite with the name "Lists".
I don't think you can use Get-SPWeb with the path "/Lists/" within it (unless the site was named "lists").
Could you try:
if ((Get-PSSnapin -Name Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.Powershell
}
$siteURL = "http//intranet/departments/it/abt/"
$web = Get-SPWeb $siteURL
$list = $web.Lists["Powershell-Test"]
$list.Items | foreach { $_["Title"] + "`n" + $_["Body"] }

powershell error wmi

Hi i am new to power shell and i cant seem to get this script to run it is to remote execute a command using the command prompt on a computer in a workgroup here is the error i get the script is below i am running the script on a win 7 machine the machine i want to remote execute on is windows xp sp3 the fire wall is off and the com settings are set for default for authentication settings and identify for impersonate and help would be great
here is the Error
Invoke-WmiMethod : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At C:\Users\Kevin\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:57 char:40
+ $newproc = Invoke-WmiMethod <<<< -class Win32_process -name Create `
+ CategoryInfo : NotSpecified: (:) [Invoke-WmiMethod], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.InvokeWmiMethod
$command = Read-Host " Enter command to run"
$user = "\Administrator"
$Domainname = $HostName +$user
$login = Get-Credential $domainname
[string]$cmd = "CMD.EXE /C " +$command
}
process {
$newproc = Invoke-WmiMethod -class Win32_process -name Create `
-ArgumentList ($cmd) -EnableAllPrivileges -ComputerName $HostName -authentication Packetprivacy -Impersonation 3 -Credential $login
if ($newproc.ReturnValue -eq 0 )
{ Write-host -foregroundcolor Green "Command $($command) Ran Sucessfully on $($HostName)"}
I think this is because Get-Credential won't pass the password to the -credential of Invoke-WmiMethod. I do this exact thing by creating the credential password using "convertto-securestring"
I know it's not as secure as you have to put the password in as plain text, but if you're the only one using the script to do maintenance or such..it's no biggie.
Try this:
$command = Read-Host " Enter command to run"
$pass = ConvertTo-SecureString "yourpassword" -Force -AsPlainText
$Domainname = 'Domain'
$user = '\administrator'
$login = $Domainname + $user
$cred = (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $login, $pass)
[string]$cmd = "CMD.EXE /C " +$command
}
process {
$newproc = Invoke-WmiMethod -class Win32_process -name Create `
-ArgumentList ($cmd) -EnableAllPrivileges -ComputerName $HostName -authentication Packetprivacy -Impersonation 3 -Credential $cred
if ($newproc.ReturnValue -eq 0 )
{ Write-host -foregroundcolor Green "Command $($command) Ran Sucessfully