ConvertTo-html using powershell - 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?

Related

PowerShell & Power BI Rest API

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

powershell webscrape into columns

Im attempting to scrape a website.
When testing I can get the values I'm looking for by doing...
$WebResponse = Invoke-WebRequest -Uri https://www.livesquawk.com/latest-news
($WebResponse.ParsedHtml.DocumentElement.GetElementsByTagName('div') | Where { $_.ClassName -match 'latest_news_each_title'}).InnerText
($WebResponse.ParsedHtml.DocumentElement.GetElementsByTagName('div') | Where { $_.ClassName -match 'latest_news_each_time'}).InnerText
But when I try to put it into a two column return, I get errors and multiple lines of same data?
What am I doing wrong? I'm out of ideas. Thanks in advance.
$WebResponse = Invoke-WebRequest -Uri https://www.livesquawk.com/latest-news
$lists = $WebResponse.ParsedHtml.DocumentElement.GetElementsByTagName('div')
$nodes = $lists[0].childNodes
$r = $lists | % {
[pscustomobject]#{
Time = $_.getElementsByClassName('latest_news_each_time')[0].innerText.Substring(0) | Where-Object { $_ -match "\d+.*" } | foreach { $Matches.Values }
News = $_.getElementsByClassName('latest_news_each_title')[0].innerText
}
}
$R
Since they aren't really grouped together and you already have the logic to get each, you could two arrays and a simple for loop to build the objects.
$WebResponse = Invoke-WebRequest -Uri https://www.livesquawk.com/latest-news
$title = ($WebResponse.ParsedHtml.DocumentElement.GetElementsByTagName('div') | Where { $_.ClassName -match 'latest_news_each_title'}).InnerText
$time = ($WebResponse.ParsedHtml.DocumentElement.GetElementsByTagName('div') | Where { $_.ClassName -match 'latest_news_each_time'}).InnerText
for($i = 0; $i -le $title.count; $i++)
{
[PSCustomObject]#{
Time = $time[$i]
News = $title[$i]
}
}

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

Powershell + Zabbix API

I get error 32500 - No permissions to referred object or it does not exist.
I know that something wrong with groups.
Connection:
if(!$credential){
$credential = Get-Credential
}
$baseurl = 'http://zabbix'
$params = #{
body = #{
"jsonrpc"= "2.0"
"method"= "user.login"
"params"= #{
"user"= $credential.UserName
"password"= $credential.GetNetworkCredential().Password
}
"id"= 1
"auth"= $null
} | ConvertTo-Json
uri = "$baseurl/api_jsonrpc.php"
headers = #{"Content-Type" = "application/json"}
method = "Post"
}
$result = Invoke-WebRequest #params
host create:
$params.body = #{
jsonrpc= "2.0"
method= "host.create"
params= #{
host = "host";
interfaces = #{type = 1;main=1;useip=1;ip="10.10.0.0";dns= "";port="10050"};
groups =#{groupid="197"}
#"templates"=#{"templateid"="14415"};
}
auth = ($result.Content | ConvertFrom-Json).result
id = 2
} | ConvertTo-Json
$result = Invoke-WebRequest #params
$result = $result.Content | ConvertFrom-Json
$result | fl
Does anyone know what the problem is?
Your final JSON should doublequote the group ID. The way you generate the JSON apparently does not do that.
Try this
$groups = #()
$groups += #{"groupid"="64"}
$groups += #{"groupid"="5"}
$params.body =
#{
"jsonrpc" = "2.0"
"method" = "host.create"
"params" = #{
"host" = "Linux server"
"interfaces" = #{
"type"= 1
"main"= 1
"useip"= 1
"ip"= "192.168.3.1"
"dns"= ""
"port"= "10050"
}
"groups" = $groups
}
"auth" = $Tocken
"id" = 1} | ConvertTo-Json -Depth 20