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
Related
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
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?
I have the following script that will deploy an Octopus Deploy release based on the parameters I provide it.
param(
[string] $releaseVersion,
[array] $future
)
foreach($line in Get-Content C:\admin\customers.txt) {
$ErrorActionPreference = "Stop";
# Define working variables
$octopusURL = "http://10.2.2.62:8022/api"
$octopusAPIKey = "API-Key"
$headers = #{ "X-Octopus-ApiKey" = $octopusAPIKey }
$spaceName = "Default"
$projectName = "C9-Deployment"
$environmentName = "LabFarm2"
$tenantNames = $line
$date = get-date -Format yyyy-MM-dd
$expiredate = $(date).AddDays(1).ToString("yyyy-MM-dd")
# Get space id
$spaces = Invoke-WebRequest -Uri "$octopusURL/spaces/all" -Headers $headers -ErrorVariable octoError | ConvertFrom-Json
$space = $spaces | Where-Object { $_.Name -eq $spaceName }
Write-Host "Using Space named $($space.Name) with id $($space.Id)"
# Get project by name
$projects = Invoke-WebRequest -Uri "$octopusURL/projects/all" -Headers $headers -ErrorVariable octoError | ConvertFrom-Json
$project = $projects | Where-Object { $_.Name -eq $projectName }
Write-Host "Using Project named $($project.Name) with id $($project.Id)"
# Create space specific url
$octopusSpaceUrl = "$octopusURL/$($space.Id)"
# Get release by version
$releases = Invoke-RestMethod -Uri "$octopusSpaceUrl/projects/$($project.Id)/releases" -Headers $headers -ErrorVariable octoError
$release = $releases.Items | Where-Object { $_.Version -eq $releaseVersion }
Write-Host "Using Release version $($release.Version) with id $($release.Id)"
# Get environment by name
$environments = Invoke-RestMethod -Uri "$octopusSpaceUrl/environments?partialName=$([uri]::EscapeDataString($environmentName))&skip=0&take=100" -Headers $headers -ErrorVariable octoError
$environment = $environments.Items | Where-Object { $_.Name -eq $environmentName }
Write-Host "Using Environment named $($environment.Name) with id $($environment.Id)"
$tenants = Invoke-WebRequest -Uri "$octopusSpaceUrl/tenants/all" -Headers $headers -ErrorVariable octoError | ConvertFrom-Json
$tenantNames | ForEach-Object {
$name = $_
$tenant = $tenants | Where-Object { $_.Name -eq $name }
if ($future -eq $null) {
write-host "This deployment is for tonight"
$deploymentBody = #{
ReleaseId = $release.Id
EnvironmentId = $environment.Id
TenantId = $tenant.Id
QueueTime = "${date}T23:00:00"
QueueTimeExpiry = "${expiredate}T05:00:00"
} | ConvertTo-Json
}
if ($future -ne $null) {
write-host "This deployment will take place on $future"
#Problem Line 64 below
$expirefuturedate = (get-date $future).Adddays(1).ToString("yyyy-MM-dd")
$deploymentBody = #{
ReleaseId = $release.Id
EnvironmentId = $environment.Id
TenantId = $tenant.Id
QueueTime = "${future}T23:00:00"
#problem line 70 below
QueueTimeExpiry = "${expirefuturedate}T05:00:00"
} | ConvertTo-Json
}
Write-Host "Creating deployment with these values: $deploymentBody"
$deployment = Invoke-WebRequest -Uri $octopusSpaceUrl/deployments -Method POST -Headers $headers -Body $deploymentBody -ErrorVariable octoError
}
}
So the problem is on line 64 and 70 where I try to take add one day to the Future parameter. If I run this with only the ReleaseVersion parameter set it will run fine without issues. But if I add a parameter for future like "-Future 2021-03-11" I get the following error:
PS C:\Users\bbelden.CLOUD9\Documents\powershell\Octopus> .\Deploycustom_parm.ps1 -releaseversion 8.1.2103.193 -future 20
21-03-11
Using Space named Default with id Spaces-1
Using Project named C9-Deployment with id Projects-101
Using Release version 8.1.2103.193 with id Releases-12243
Using Environment named LabFarm2 with id Environments-161
This deployment will take place on 2021-03-11
ForEach-Object : Cannot convert 'System.Object[]' to the type 'System.DateTime' required by parameter 'Date'.
Specified method is not supported.
At C:\Users\bbelden.CLOUD9\Documents\powershell\Octopus\Deploycustom_parm.ps1:47 char:16
+ $tenantNames | ForEach-Object {
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [ForEach-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.ForEachObjectCommand
Now if I just remove the line 64 completely and manually set a time date stamp in line 70 like the following:
if ($future -ne $null) {
write-host "This deployment will take place on $future"
#$expirefuturedate = (get-date $future).Adddays(1).ToString("yyyy-MM-dd")
$deploymentBody = #{
ReleaseId = $release.Id
EnvironmentId = $environment.Id
TenantId = $tenant.Id
QueueTime = "${future}T23:00:00"
QueueTimeExpiry = "2021-03-11T05:00:00"
} | ConvertTo-Json
}
It will work fine.
So I am not really sure what I am missing here. Please let me know if there is something I am doing wrong. I believe it has to do with the Array, because if I comment that line out the issue will go away, but I need a way to transform the $future variable to adding one day to it.
Thanks
This should explain your error:
PS /home/> $future=[array]'2021-03-11'
PS /home/> (get-date $future).Adddays(1).ToString("yyyy-MM-dd")
Get-Date: Cannot convert 'System.Object[]' to the type 'System.DateTime' required by parameter 'Date'. Specified method is not supported.
PS /home/> $future=[datetime]'2021-03-11'
PS /home/> (get-date $future).Adddays(1).ToString("yyyy-MM-dd")
2021-03-12
I am trying to get the source network address for an RDP connection to send an email when a user connects to the server. I have everything but the source address. My script is triggered by event 1149 in the RemoteConnectionManager Operational log. I only need to access either the event data or source address from the system.
$SmtpClient = new-object system.net.mail.smtpClient
$MailMessage = New-Object system.net.mail.mailmessage
$SmtpClient.Host = "mail.scomage.com"
$mailmessage.from = ("BWAQBW#BWAServer.com")
$mailmessage.To.add("support#scomage.com")
$mailmessage.Subject = “BWAQB RDP”
$mailmessage.Body = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name + “ logged into BWA QB Server”
$smtpclient.Send($mailmessage)
Final script after excellent help by Steven:
$LastEvent = Get-WinEvent -FilterHashtable `
#{ LogName = "Microsoft-Windows-TerminalServices-
RemoteConnectionManager/Operational"; Id = 1149} |
Select-Object *,
#{ Name = 'UserName'; Expression = `
{ if ($_.Properties[0].Value) { $_.Properties[0].Value } else { "Administrator" } } },
#{ Name = 'SourceIP'; Expression = { $_.Properties[2].Value } } |
Sort-Object TimeCreated |
Select-Object -Last 1
$MailParams =
#{
SmtpServer = "mail.scomage.com"
From = "BWAQBW#BWAServer.com"
To = "support#scomage.com"
Subject = "BWAQB RDP " + $LastEvent.UserName + " " + $LastEvent.SourceIP
Body = $LastEvent.UserName + " logged into BWA QB Server at " + `
$LastEvent.TimeCreated.ToString('g') + " From: " + $LastEvent.SourceIP
}
Send-MailMessage #MailParams
Script to send logon email:
$Event = Get-WinEvent -FilterHashTable #{
LogName='Security'; ID=4624; StartTime=$DateLess10; } |
Where-Object{$_.Properties[8].Value -eq 10 } |
Sort-Object TimeCreated |
Select-Object -Last 1
if( $Event.Properties[8].Value -eq 10 )
{
$MailParams =
#{
SmtpServer = "mail.scomage.com"
From = "BWAQBW#BWAServer.com"
To = "support#scomage.com"
Subject = "BWAQB Remote Login " + $Event.Properties[5].Value + " " + $Event.Properties[18].Value
Body = $Event.Properties[5].Value + " logged into BWA QB Server at " + `
$Event.TimeCreated.ToString('g') + " From: " + $Event.Properties[18].Value
}
Send-MailMessage #MailParams
}
Updated Based on Comments
Looks like the source address for the connection is recorded as the 3rd property in event 1149. Properties are an object array of type [System.Diagnostics.Eventing.Reader.EventProperty[]] which just means you have to access the sub-property .Value .
An example to get the last event:
$LastEvent =
Get-WinEvent -FilterHashtable #{ LogName = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational"; Id = 1149} |
Select-Object *,
#{ Name = 'UserName'; Expression = { $_.Properties[0].Value } },
#{ Name = 'SourceIP'; Expression = { $_.Properties[2].Value } } |
Sort-Object TimeCreated |
Select-object -Last 1
Since I'm not sure Get-WinEvent will guarantee chronological order the the Sort-Object cmdlet is used. So it should result in the the last 1149 event. However, it doesn't guarantee it will be for the user that was returned by System.Security.Principal.WindowsIdentity]::GetCurrent().Name. I don't know what kind of machine this is or under what circumstances the script will be run. For example if it's a multi-user system (implied by Terminal Server) I suspect there's an edge case where last event may not be for the current user.
So, I'm guessing that we should isolate the last event for that user. We can do that with one of these samples:
Option 1:
$NTUserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$UserName = $NTUserName.Split('\')[-1]
$Events =
Get-WinEvent -FilterHashtable #{ LogName = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational"; Id = 1149} |
Select-Object *,
#{ Name = 'UserName'; Expression = { $_.Properties[0].Value } },
#{ Name = 'SourceIP'; Expression = { $_.Properties[2].Value } } |
Group-Object -Property UserName -AsHashTable -AsString
$LastEvent = ($Events[$UserName] | Sort-Object TimeGenerated)[-1]
Option 2:
$NTUserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$UserName = $NTUserName.Split('\')[-1]
$LastEvent =
Get-WinEvent -FilterHashtable #{ LogName = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational"; Id = 1149} |
Select-Object *,
#{ Name = 'UserName'; Expression = { $_.Properties[0].Value } },
#{ Name = 'SourceIP'; Expression = { $_.Properties[2].Value } } |
Where-Object{ $_.UserName -eq $UserName } |
Sort-Object TimeCreated |
Select-Object -Last 1
In both cases $LastEvent should have the last 1149 event for the current user. The first option has less sorting, because it is only sorting events for the specific user. you can use $LastEvent.SourceIP for the email.
A secondary note: You don't need to use System.Net.Mail.SMTPClient. you can use Send-MailMessage combined with command splatting that might look like:
$MailParams =
#{
SmtpServer = "mail.scomage.com"
From = "BWAQBW#BWAServer.com"
To = "support#scomage.com"
Subject = "BWAQB RDP"
Body = $UserName + " logged into BWA QB Server at " + $LastEvent.TimeCreated.ToString('g') + " From: " + $LastEvent.SourceIP
}
Send-MailMessage #MailParams
Note: Above was also updated after your comments to take advantage of the newer revisions. Note: .ToString('g') results in date format like '6/30/2020 9:17 PM'
I'm not sure if the body or subject is exactly right, but you can work that out.
Function jay {
[cmdletbinding(SupportsShouldProcess)]
Param(
[Parameter(Position = 0, Mandatory, HelpMessage = "Enter the new repository name")]
[ValidateNotNullorEmpty()]
[string]$Name,
[string]$Description,
[switch]$Private,
[switch]$NoWiki,
[switch]$NoIssues,
[switch]$NoDownloads,
[switch]$AutoInitialize,
#license templates found at https://github.com/github/choosealicense.com/tree/gh-pages/_licenses
[ValidateSet("MIT", "apache-2.0", "gpl-3.0", "ms-pl", "unlicense")]
[string]$LicenseTemplate,
[Alias("token")]
[ValidateNotNullorEmpty()]
[string]$UserToken = 'github token here',
#write full native response to the pipeline
[switch]$Raw
)
Write-Verbose "[BEGIN ] Starting: $($MyInvocation.Mycommand)"
#display PSBoundparameters formatted nicely for Verbose output
[string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd()
Write-Verbose "[BEGIN ] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*2)$_"}) | Out-String) `n"
#create the header
$head = #{
Authorization = 'Basic ' + $UserToken
}
#create a hashtable from properties
$hash = #{
name = $Name
description = $Description
private = $Private -as [boolean]
has_wiki = (-Not $NoWiki)
has_issues = (-Not $NoIssues)
has_downloads = (-Not $NoDownloads)
auto_init = $AutoInitialize -as [boolean]
}
if ($LicenseTemplate) {
$hash.add("license_template", $LicenseTemplate)
}
$body = $hash | ConvertTo-Json
Write-Verbose "[PROCESS] Sending json"
Write-Verbose $body
#define parameter hashtable for Invoke-RestMethod
$paramHash = #{
Uri = "https://api.github.com/user/repos"
Method = "Post"
body = $body
ContentType = "application/json"
Headers = $head
UseBasicParsing = $True
DisableKeepAlive = $True
}
#should process
if ($PSCmdlet.ShouldProcess("$name [$description]")) {
$r = Invoke-RestMethod #paramHash
if ($r.id -AND $Raw) {
Write-Verbose "[PROCESS] Raw result"
$r
}
elseif ($r.id) {
write-Verbose "[PROCESS] Formatted results"
$r | Select-Object #{Name = "Name"; Expression = { $_.name } },
#{Name = "Description"; Expression = { $_.description } },
#{Name = "Private"; Expression = { $_.private } },
#{Name = "Issues"; Expression = { $_.has_issues } },
#{Name = "Wiki"; Expression = { $_.has_wiki } },
#{Name = "URL"; Expression = { $_.html_url } },
#{Name = "Clone"; Expression = { $_.clone_url } }
}
else {
Write-Warning "Something went wrong with this process"
}
if ($r.clone_url) {
$msg = #"
To push an existing local repository to Github run these commands:
-> git remote add origin $($r.clone_url)"
-> git push -u origin master
"#
Write-Host $msg -ForegroundColor Green
}
}
Write-Verbose "[END ] Ending: $($MyInvocation.Mycommand)"
}
I am working on this Powershell script to accept creating Github repo from my local pc to Github. But every time I try to enter description it fails and provides me this error. Could someone please help me out
Invoke-RestMethod : {"message":"Requires
authentication","documentation_url":"https://developer.github.com/v3/repos/#create"}
At C:\Users\norep\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:96 char:14
It looks like you're trying to use your Github API token with Basic Authentication, but according to the Github API v3 documentation that token is an OAuth token. Your header should look like this instead:
$head = #{
Authorization = 'token ' + $UserToken
}
You would use the Basic auth header if you were providing a base64 encoded string of your username and password (in the format of USERNAME:PASSWORD):
$basicAuthBytes = [System.Text.Encoding]::UTF8.GetBytes('USERNAME:PASSWORD')
$basicAuthBase64String = [Convert]::ToBase64String( $basicAuthBytes )
$head = #{
Authorization = "Basic ${basicAuthBase64String"
}