Problems in reading a commandline json object using powershell - json

I have a powershell script "test.ps1" which takes a json string as a command line input & tries to parse it.
The powershell script is as below -
param(
[string]$json = $(throw 'test')
)
$currentPath = Get-Location
[Reflection.Assembly]::LoadFile("$currentPath\Newtonsoft.Json.dll")
$result = [Newtonsoft.Json.Linq.JObject]::Parse($json)
foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString()}
But it is giving me the below error -
PS C:\Users\aghosh.RJFDEV\Documents> ./test.ps1 '{"DevResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"}],"QaResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"}],"PreProdResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"}],"ProdResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"},{"TechnologyName":"TFS","RuleName":"Process Template","OutputValue":"Raymond James CMMI V3.5"}]}'
GAC Version Location
--- ------- --------
False v2.0.50727 C:\Users\aghosh.RJFDEV\documents\Newtonsoft.Json.dll
You cannot call a method on a null-valued expression.
At C:\Users\aghosh.RJFDEV\Documents\test.ps1:13 char:82
+ foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString <<<< ()}
+ CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\aghosh.RJFDEV\Documents\test.ps1:13 char:82
+ foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString <<<< ()}
+ CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
My powershell version is 2.0 & the Json.Net library version is 3.5.
Please help me with the error or please suggest any other suitable approach.
Thanking in advance.

Change this line:
foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString()}
To this:
foreach($unit in $result["DevResults"]) {Write-Host $unit["TechnologyName"].ToString()}

Related

How to get a value from powershell where the key has a dot at the beginning?

How do I get the value of a json where the key has "." at the beginning?
$json = '{".expires":"2022-10-13"}' | ConvertFrom-Json
cls
$json..expires #trying to get the value 2022-10-13
Error:
On the line:4 caractere:8
+ $json..expires
+ ~
You must provide a value expression after the '..' operator.
On the line:4 caractere:8
+ $json..expires
+ ~~~~~~~
Token 'expires' unexpected in the expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedValueExpression
The code above gives error if I put a colon, is there another way?
You can enclose the property name in quotes.
$json.".expires"

Issues with calling json file using powershell

I am trying to run simple power-shell command to call json file to deploy some resources on Azure but it give me the same errors each time I try to run the file.The error message I am getting is -
New-AzDeployment : Cannot retrieve the dynamic parameters for the cmdlet. Invalid property identifier character: �. Path '', line 2, position 0.
At line:1 char:1
+ New-AzDeployment -Name $DeploymentName -Location uksouth -TemplateUri ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-AzDeployment], ParameterBindingException
+ FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureDeploymentCmdlet
below is the powershell, I am trying to run -
$DeploymentSubscription = "Visual Studio Enterprise with MSDN"
$DeploymentRSG = "xyz"
$DeploymentName = "vvv"
$ParameterRoute = "D:\xyz\json\VM\"
$ParameterFile = $ParameterRoute + "Build.json"
$TemplateFileRoute = "D:\xyz\VM\"
$TemplateFileName = "Deploy_RG_Resources.json"
$TemplateFile = $TemplateFileRoute + $TemplateFileName
$TemplateFileURi = $TemplateFileRoute + $TemplateFileName
New-AzResourceGroupDeployment -Name $DeploymentName -ResourceGroupName $DeploymentRSG -DeploymentDebugLogLevel All -Verbose -TemplateUri $TemplateFileURi -TemplateParameterFile $ParameterFile
Thanks
That error is very specific.
What you are passing is valid. The help files for the cmdlet shows this command in action.
New-Az​Resource​Group​Deployment
$newAzResourceGroupDeploymentSplat = #{
TemplateParameterFile = "D:\Azure\Templates\EngSiteParams.json"
TemplateObject = $TemplateObject
ResourceGroupName = "ContosoEngineering"
}
New-AzResourceGroupDeployment #newAzResourceGroupDeploymentSplat
Note the fully qualified UNC to the .json file.
But you are doing this..
$ParameterFile = $ParameterRoute + "Build.json"
... and based on your post, that is not the path to your .json file.
Try using -TemplateFile as parameter instead of -TemplateUri if your Template file in on local machine.
This is resolved now .Issue was with the JSON template syntax.Quite weird though I have validate the template many times

GoPro/Powershell: Protocol violation when trying to read .json status file

I try to read the status file of a GoPro Hero5.
If you type "http://10.5.5.9/gp/gpcontrol/status" while connected to the GoPro-Wifi the camera responds with a json status file.
I want to get this status file with powershell, with the Invoke-RestMethod:
Invoke-RestMethod -Uri "http://10.5.5.9/gp/gpControl/status"
This gives me the following error:
Invoke-RestMethod : The server committed a protocol violation.. Section=ResponseHeader Detail=Auf CR muss LF folgen
At line:3 char:13
+ $response = Invoke-RestMethod -Uri "http://10.5.5.9/gp/gpControl/stat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Here is an example on what the status file should look like: https://github.com/KonradIT/goprowifihack/blob/master/HERO4/CameraStatus.md
Any hints how to get the file with powershell would be appreciated!

PowerShell hash-table return values

I have a simple script to return values from a hash table:
param
(
[Parameter(Mandatory = $true)]
[string]$Name
)
function getvalues ($Name) {
$nameList= #{"CFT"=#{"name1"="text1"; "name2"="text2"}}
#return $nameList[$Name]
return ,$nameList
}
$Values = getvalues($Name)
Write-Debug "DEBUG: Name1 = "$Values["name1"]
Write-Debug "DEBUG: Name2 = "$Values["name2"]
When I run it, I get the following error:
Write-Debug : A positional parameter cannot be found that accepts argument '$null'.
At C:\MSFT\add-test.ps1:21 char:2
+ write-Debug "DEBUG: Name1 = "$Values["name1"]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Write-Debug], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteDebugCommand
Write-Debug : A positional parameter cannot be found that accepts argument '$null'.
At C:\MSFT\add-test.ps1:22 char:2
+ write-Debug "DEBUG: Name2 = "$Values["name2"]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Write-Debug], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteDebugCommand
You're terminating your strings and then using the $Values lookup. Either use a + or embed it into the string, or use the -f operator:
write-Debug ("DEBUG: Name1 = " + $Values["name1"])
write-Debug "DEBUG: Name2 = $($Values["name2"])"
write-Debug ("DEBUG: Name3 = {0}" -f $Values["name3"])
Note forms 1 and 3 need parentheses ( ).
Regarding your comment that there are no more errors and no output:
Are you sure your debug preference is set such that you can see the output? The point of Write-Debug and Write-Verbose is that you only see the output when the preference is set as such (and you shouldn't add DEBUG: in your string, it will be added for you). I suspect Write-Verbose is more appropriate for what you're doing.
To test quickly whether it will work, you can actually add -Debug or -Verbose as appropriate.
So for example:
Write-Verbose "Name2 = $($Values["name2"])" -Verbose

How can I get powershell exception descriptions into a string?

I want to have access to the same message that Powershell prints when you send an error record to the output stream
Example:
This is the exception message At
C:\Documents and
Settings\BillBillington\Desktop\psTest\exThrower.ps1:1
char:6
+ throw <<<< (New-Object ArgumentException("This is the
exception"));
+ CategoryInfo : OperationStopped: (:) [],
ArgumentException
+ FullyQualifiedErrorId : This is the exception
I when a get the last ErrorRecord by doing $Error[0] I can't seem to figure out how to get this information in a simple way
I found this 'Resolve-Error' function from the community extensions here which does roughly what I want but it prints a huge semi-formatted list of stuff I don't need that I have to then strip
Is there way of accessing the message that Powershell uses or failing that a simpler way of getting hash of the values I care about so I can put them into a string in a format of my choosing?
How about:
$x = ($error[0] | out-string)
Is that what you wanted?
If you want a bit shorter message (more user friendly sometimes?) than #tomasr suggests this will do:
$error[0].ToString() + $error[0].InvocationInfo.PositionMessage
You will get something like:
Cannot find path 'C:\TEMP\_100804_135716\missing' because it does not exist.
At C:\TEMP\_100804_135716\test.ps1:5 char:15
+ Get-ChildItem <<<< missing
This technical info will be excluded:
+ CategoryInfo : ObjectNotFound: (C:\TEMP\_100804_135716\missing:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
I took it a bit further because I didn't like the multilines from $error[0].InvocationInfo.PositionMessage.
Function FriendlyErrorString ($thisError) {
[string] $Return = $thisError.Exception
$Return += "`r`n"
$Return += "At line:" + $thisError.InvocationInfo.ScriptLineNumber
$Return += " char:" + $thisError.InvocationInfo.OffsetInLine
$Return += " For: " + $thisError.InvocationInfo.Line
Return $Return
}
[string] $ErrorString = FriendlyErrorString $Error[0]
$ErrorString
You can look at what else is availible to construct your own String via:
$Error | Get-Member
$Error[0].InvocationInfo | Get-Member
Foreach ($Errors in $Error){
#Log Eintrag wird zusammengesetzt und in errorlog.txt geschrieben
"[$Date] $($Errors.CategoryInfo.Category) $($Errors.CategoryInfo.Activity) $($Errors.CategoryInfo.Reason) $($Errors.CategoryInfo.TargetName) $($Errors.CategoryInfo.TargetType) $($Errors.Exception.Message)" |Add-Content $Path\errorlog.txt -Encoding UTF8
}
You can also do this and you will get all Informations about the Error
Similar to #tomasr, but shorter:
$($error[0])
For all errors in a script:
$($error)