PowerShell & Power BI Rest API - powershell

Essentially what I'm after is the results of rest API Gateways - Get Datasource Users but retaining the ID (in this example $Line.id from my imported CSV file).
The end result should be a CSV with the following fields -
ID, emailAddress, datasourceAccessRight, displayName, identifier, principalType
I'm new to PowerShell and surprised I got this far but can't figure out this final bit.
Cheers
$webclient=New-Object System.Net.WebClient
$webclient.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$Dir = "C:\pbi_pro_user_logs\"
Login-PowerBI
$GateWayFile = Import-CSV -Path "C:\pbi_pro_user_logs\Gateway_Detail.csv"
$Output = #()
foreach ($Line in $GateWayFile){
$Item = $Line.id
$url = "https://api.powerbi.com/v1.0/myorg/gateways/HIDDEN/datasources/"+$Item+"/users"
$Output += (Invoke-PowerBIRestMethod -Url $url -Method Get | ConvertFrom-Json)
}
$Result = $Output.value
$Result | Export-Csv $Dir"GateWay_users.csv" -NoTypeInformation

Try this, using a calculated property from Select-Object:
$GateWayFile = Import-CSV -Path "C:\pbi_pro_user_logs\Gateway_Detail.csv"
$Output = Foreach ($Line in $GateWayFile){
$url = "https://api.powerbi.com/v1.0/myorg/gateways/HIDDEN/datasources/"+$Line.id+"/users"
$Item = (Invoke-PowerBIRestMethod -Url $url -Method Get | ConvertFrom-Json)
# output all properties of the item, plus the ID:
$ItemWithID = $Item | Select *,#{l='Id';e={$line.id}}
Write-Output $ItemWithID
}
# This depends on how you want your csv structured, but for example:
$Result = $Output | Select Id,Value
Or, if Value is a whole object that ID should be assigned inside of, then change the selection lines:
$ItemWithID = $Item.Value | Select *,#{l='Id';e={$line.id}}
$Result = $Output

Related

Powershell Foreach loop to return ID data

I am currently trying to create a foreach loop to take each value from a list and search for it in return data from an API. For some reason I am getting NULL data when I try to loop it.
$agentList = (Import-CSV -Path 'O:\Test\AgentList.txt')
$Params = #{
"Uri" = "https://10.245.55.88:8834/agents"
"Method" = "GET"
"Headers" = #{
"X-ApiKeys" = "accessKey=$($AccessKey); secretKey=$($SecretKey)"
}
}
$agentsNotInSC = Invoke-Restmethod #Params
$agentID = foreach ($agent in $agentList) {
$agentID = $agentsNotInSC.agents | Where-Object { $_.name -eq $agent }
$agentID.id
}
$agentID | Export-Csv -Path "O:\Test\IDAgent.CSV" -NoTypeInformation
trying to get all the return data and export it to a CSV

ConvertTo-html using powershell

I have a list of string data .. I generate a csv file and it works but when I need to generate as html report its not working ..
# Unpack Access Token
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token
$SetDate = Get-Date($SetDate) -format yyyy-MM-dd
$GraphSignInLogs = "https://graph.microsoft.com/v1.0/auditLogs/signIns"
$result = (Invoke-RestMethod -Uri $GraphSignInLogs -Headers $Headers -Method Get)
$alluserhistory = #()
foreach ($resitem in $result){
$userhistory = New-Object psobject -Property #{
User = $resitem.userDisplayName
UPN = $resitem.userPrincipalName
AzureAppUsed = $resitem.appDisplayName
UserApp = $resitem.clientAppUsed
IP = $resitem.ipAddress
Date = $resitem.createdDateTime
OS = ($resitem.deviceDetail).operatingSystem
browser = ($resitem.deviceDetail).browser
City = ($resitem.location).city
Country = ($resitem.location).countryOrRegion
CompanyName = $resitem.companyName
}
$alluserhistory += $userhistory
}
$alluserhistory|
Select-Object User, UPN, AzureAppUsed |
ConvertTo-html -As TABLE |
Out-File "Desktop/3.html"
it output only the main titles without data is there any way I can generate html file?

how to export powershel result to csv

I want to export what I already filtered in ForEach-Object. The problem is that I can't export the filtered data.
I tried the following:
$getTapes.rows | Export-Csv C:\\123\\123456.txt but this has exported all the information without filter.
$getTapes = Invoke-RestMethod -Method GET -ContentType $content -Uri $Uri -Headers #{'Authorization' = $Authorization}
$today = Get-Date
$getTapes.rows | ForEach-Object {
$tape = $_;
if ( $tape.custom_fields.Ueberschreibschutz.value -ge $today ) {
Write-Host "Treffer ID=" $tape.asset_tag " Name=" $tape.name " SNR=" $tape.serial " Mediensatz=" $tape.custom_fields.Mediensatz.value
}
}
$getTapes.rows |export-Csv C:\\123\\123456.txt
I expect:
Treffer ID= 1 Name= 12 SNR= 12345 Mediensatz= M
Treffer ID= 2 Name= 32 SNR= 54321 Mediensatz= W
You should not use Write-Host to collect data. That's only to output pixels on the screen. Instead you should create a custom object you can use as you want later on ... like this:
$Result = $getTapes.rows | ForEach-Object {
if ( $_.custom_fields.Ueberschreibschutz.value -ge $today ) {
[PSCustomObject]#{
TrefferID = $_.asset_tag
Name = $_.name
SNR = $_.serial
Mediensatz = $_.custom_fields.Mediensatz.value
}
}
}
$Result | Export-Csv -Path C:\123\123456.csv -NoTypeInformation
Write-host do nothing except it shows you the result in the console, so it will not modify or delete the things you don't want in $getTapes.rows.
Instead you can define a variable $result and iterate over the $getTapes.rows using Foreach-Object, and add the result if it meets your if condition.
Try this:
$getTapes = Invoke-RestMethod -Method GET -ContentType $content -Uri $Uri -Headers #{'Authorization' = $Authorization}
$today = Get-Date
$getTapes.rows | ForEach-Object -begin {$result = "" } {
$tape = $_;
if ( $tape.custom_fields.Ueberschreibschutz.value -ge $today ) {
$result += "Treffer ID= $($tape.asset_tag) Name= $($tape.name) SNR= $($tape.serial) Mediensatz= $($tape.custom_fields.Mediensatz.value)`n"
}
} -end {$result | export-Csv C:\123\123456.txt}

Appending to a URL with powershell

function Get-Data(){
[PSObject[]]$pid = ''
$getUri1 = 'https://playbook2.com/data/project/folder/28220'
$projectIds = wget $getUri1 -UseDefaultCredentials |
ConvertFrom-JSON | Select data | select -Expand data | select id
Write-Host $projectIds
#obtain all the project ids
ForEach-Object{
[PSObject[]]$pid += $projectIds.id
}
Write-Host $pid
$uri3 = "https://playbook2.com/data/project/export/projects-tasks?projectIds[]="
$getIds = [PSObject[]]$pid -join "&projectIds[]="
$getUri2 = $uri3 + $getIds
$of = "\\ant\dept\DCGSI\Extracts\Time_Tracking_Tasks.xlsx"
Write-Host $getUri2
#retrieve excel files of tasks from each sub-folder
wget $getUri2 -outfile $of -UseDefaultCredentials
}
This code is an adaptation of some other code that I wrote. The 5 other scripts work fine. The main difference is that the other code has to loop through multiple folders and gets the project IDs under each folder, but this code only has to go through a single folder. Now in the other code the $uri3, $getIds code works fine and I get an export. The problem I am seeing in this code is that it isn't joining the URL the way I expect.
https://playbook2.com/data/project/export/projects-tasks?projectIds[]=######&projectIds[]=####### is the expected and previously seen output to get all the project data i need.
The problem with the above script is that it is giving https://playbook2.com/data/project/export/projects-tasks?projectIds[]=&projectIds[]=######&projectIds[]=####### which is invalid.
is there a way that I can tell it to do just $pid for the first item in the object and then -join the "&projectIds[]=" on the next n until the end of the list? I tried
[PSObject[]]$pid | select -Skip 1 -join "&projectIds[]="
and
[PSObject[]]$pid | Select-Object -Skip 1 -join "&projectIds[]="
but that results in nothing being appended.
I found a couple of "mistakes" in your script.
First is that you are using the variable $pid which is an system default variable. You can check the system global variables by typing
Get-Variable
Secondly $pid is defined with an empty string. The correct way to initialize a PSObject is with $myVar = New-Object PSObject. Replace [PSObject[]]$pid = '' with $myProjectIds = New-Object PSObject
For readability I took the liberty to rewrite your script.
function Get-Data(){
$GetProjectsUri = 'https://playbook2.com/data/project/folder/28220'
$ExportProjectsUri = 'https://playbook2.com/data/project/export/projects-tasks?'
$ExportFilePath = "\\ant\dept\DCGSI\Extracts\Time_Tracking_Tasks.xlsx"
$GetProjectsJson = Invoke-WebRequest -Uri $GetProjectsUri -UseDefaultCredentials
Write-Output $GetProjectsJson
$Projects = ConvertFrom-JSON -InputObject $GetProjectsJson
Write-Output $Projects
foreach ($Project in $Projects) {
$ProjectId = $Project.data.id
# Check if ProjectId exists
if ($ProjectId) {
$ExportProjectsUri = $ExportProjectsUri + 'projectIds[]=' + $ProjectId
}
}
Write-Output $ExportProjectsUri
Invoke-WebRequest Invoke-WebRequest -Uri $ExportProjectsUri -outfile $ExportFilePath -UseDefaultCredentials
}
Cheers
Glenn

PNP powershell SharePoint Online set modern page bannerimageurl

My goal is to use PNP commandlets to set the SharePoint online modern bannerimageurl property for a page.
First I get a list of the pages and their current title and bannerimageurl values
# Get alist of all pages and their banner URLs
$items = Get-PnPListItem -List "SitePages" -Fields ID,Title,BannerImageUrl
$items | %{new-object PSObject -Property #{Id=$_["ID"];Title=$_["Title"];BannerImageUrl=$_["BannerImageUrl"].Url}} | select ID,Title,BannerImageUrl
But even if I then run the following code to set the BannerImage of one page (say ID2)
Set-PnPListItem -List "SitePages" -Id 2 -Values #{"BannerImageUrl" = " https://contoso.sharepoint.com/sites/mycomsite3/bannerimages/bread-braid-tedster-sml.jpg";}
When I run the following again the item 2 shows up as having a changed BannerImageUrl
$items = Get-PnPListItem -List "SitePages" -Fields ID,Title,BannerImageUrl
$items | %{new-object PSObject -Property #{Id=$_["ID"];Title=$_["Title"];BannerImageUrl=$_["BannerImageUrl"].Url}} | select ID,Title,BannerImageUrl
BUT when I actually view the page in the browser that is item 2 there has been no change to the banner image ??
Please tell me what I'm doing wrong when I set the BannerImageUrl.
Your experience and knowledge greatly accepted.
I've written a PS Function for that exact same problem based on the JS Solution here, in case you still need it:
function UpdateBannerImage {
param(
[string]$listName,
[int]$itemId,
[string]$newBannerUrl
)
#get list item
$item = Get-PnPListItem -List $listName -Id $itemId -Fields LayoutWebpartsContent, BannerImageUrl
if($item["LayoutWebpartsContent"] -match 'data-sp-controldata="([^"]+)"'){
# get substring w/ regex
$temp = $item["LayoutWebpartsContent"] | Select-String -Pattern 'data-sp-controldata="([^"]+)"'
$content = $temp.Matches.Groups[1].Value
# replace [] bc sometimes it throws later
$content = $content.replace("[","[").replace("]","]")
# decode
$dec = [System.Web.HttpUtility]::HtmlDecode($content)
# from JSON
$jnContent = ConvertFrom-Json $dec
#set values
if (!$jnContent.serverProcessedContent) {
$jnContent.serverProcessedContent = {};
}
if (!$jnContent.serverProcessedContent.imageSources) {
$jnContent.serverProcessedContent.imageSources = New-Object PSObject;
$jnContent.serverProcessedContent.imageSources | add-member Noteproperty imageSource $newBannerUrl
}
if(!$jnContent.serverProcessedContent.imageSources.imageSource){
$jnContent.serverProcessedContent.imageSources | add-member Noteproperty imageSource $newBannerUrl
}
$jnContent.serverProcessedContent.imageSources.imageSource = $newBannerUrl
# need to always create new properties, otherwise nothing changes
$curTitle = "";
if($jnContent.properties){
$curTitle = $jnContent.properties.title;
}
$jnContent.properties = New-Object PSObject;
$jnContent.properties | add-member Noteproperty title $curTitle
$jnContent.properties | add-member Noteproperty imageSourceType 2
# to JSON
$newContent = $jnContent | ConvertTo-Json -Compress
$enc = [System.Web.HttpUtility]::HtmlEncode($newContent)
$enc = $enc.replace("{","{").replace(":",":").replace("}","}").replace("[","[").replace("]","]")
# replace full item property
$fullContent = $item["LayoutWebpartsContent"].replace("[","[").replace("]","]");
$fullContent = $fullContent -replace $content, $enc
$fullContent.replace("[","[").replace("]","]")
# set & update
$item["LayoutWebpartsContent"] = $fullContent
$item.Update()
# not really sure if needed, but also update bannerURL
Set-PnPListItem -List $listName -Id $itemId -Values #{"BannerImageUrl" = $newBannerUrl; }
}
}
new here sorry if i mess up the format, also uploaded for safety here :P