Getting json data loaded from text file into hashtable - powershell

My text file has below text in Json format. Its huge file below is sample. I would like this data loaded in hash table so later in script i can query data for processing.
{
"cohwpcu01": {
"lx-wpcpo1kji04": 6397,
"ut14003": 6761,
"HFS Citrix 12-2014": 9952,
"ut08647": 7678
}
"cohwpcu02": {
"lx-wpcpo1kji05": 6397,
"ut140056": 6761,
"HFS Citrix 12-2019": 9952,
"ut08650": 7678
}
}
I have tried below
$hash=Get-Content -Path .\hash_table.txt|ConvertFrom-StringData
ConvertFrom-StringData : Data line '{' is not in 'name=value' format.
At line:1 char:42
$hash=Get-Content -Path .\hash_table.txt|ConvertFrom-StringData
~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [ConvertFrom-StringData], PSInvalidOperationException
FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.ConvertFromStringDataCommand
Any idea how do i make hash table out of these data ???
Thank you

Related

How to check if custom culture exists

I have created one custom culture as 'gh-es'. I am trying to check if its already registered.its working fine if culture is registered but if not it throw an error in start only.
I am unable to find how to check if a culture is present or to check if its exists
$CustomCulture= [cultureinfo]::GetCultureInfo('gh-es')
If($CustomCulture -ne null)
{
Write-output "culture already registered"
}
Else
{
$CultureName = 'gh-es'
$BaseCulture=[cultureinfo]::GetCultureInfo('es-US')
$BaseRegion = New-Object System.Globalization.RegionInfo 'es-US'
try {
# Set up CultureAndRegionInfoBuilder
Add-Type -AssemblyName sysglobl
$CultureBuilder = New-Object System.Globalization.CultureAndRegionInfoBuilder
#($CultureName,[System.Globalization.CultureAndRegionModifiers]::None) $CultureBuilder.LoadDataFromCultureInfo($BaseCulture)
$CultureBuilder.LoadDataFromRegionInfo($BaseRegion)
$CultureBuilder.Register()
}
catch
{
throw
}
}
this is what i mean by using try/catch to handle an error when checking for a culture ...
try {
[cultureinfo]::GetCultureInfo('666-santa')
}
catch
{
'something glitched'
}
the output = something glitched
without the try/catch, the output is an error msg ...
Exception calling "GetCultureInfo" with "1" argument(s): "Culture is not supported.
Parameter name: name
666-santa is an invalid culture identifier."
At line:1 char:1
+ [cultureinfo]::GetCultureInfo('666-santa')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CultureNotFoundException

A positional parameter cannot be found that accepts argument '+' error using SqlClient in Powershell

I am getting an error in my powershell script for a runbook on Azure:
Write-Error : A positional parameter cannot be found that accepts argument '+'.
At Test-Update-IndexesForallShardsFromShardManagerRunbook:61 char:61
+
+ CategoryInfo : InvalidArgument: (:) [Write-Error], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteErrorCommand
Based on the logs I see on my Azure autmation account from a job that ran, I pinpointed the origin of the error in my script somewhere in the following code:
$updateStatisticSql = "UPDATE STATISTICS [$Using:tableName] ( [$Using:statName] );"
$CmdUpdateStats=new-object system.Data.SqlClient.SqlCommand($updateStatisticSql, $Conn1)
$CmdUpdateStats.CommandTimeout=1500
Try
{
$Ds=New-Object system.Data.DataSet
$Da=New-Object system.Data.SqlClient.SqlDataAdapter($CmdUpdateStats)
[void]$Da.fill($Ds)
}
Catch
{
# Will catch the exception here so other statistics can be processed.
Write-Error "Statistic " + $tableName + "(" + $statName + ") could not be updated. Investigate the statistic."
}
It seems after adding logging after each line, that it doesn't log after the "fill" function, so I assume something is going wrong there. But I am not seeing the relation between the error and this function. It also doesn't seem a script breaking error, since it never goes into the catch and the rest of the scripts runs fine. I also validated that the statistics are updated, even though the error I am getting.
So the error you are seeing is because you are trying to build a string using concatenation which means you have spaces and spaces are used to delimit parameters when calling cmdlets. Put all the concatenation into parens:
Write-Error ("Statistic " + $tableName + "(" + $statName + ") could not be updated. Investigate the statistic.")

Unable to modify value of a nested property in PS custom object

I have a PS custom object:
TourCode : s
TournamentNumber : 524
TournamentName : Mitsubishi Electric Championship at Hualalai
EnvironmentType : PGA Tour
TournamentRootPath : /mitsubishi-electric-championship-at-hualalai
SValues : {#{S1=championstour; S2=tournaments; S3=mitsubishi-electric-championship-at; S4=}}
I can easily modify values of the top level properties like TourCode or TournamentName:
PS C:\Users\yuriy> $testTournament.TourCode = 'r'
PS C:\Users\yuriy> $testTournament
TourCode : r
TournamentNumber : 524
TournamentName : Mitsubishi Electric Championship at Hualalai
EnvironmentType : PGA Tour
TournamentRootPath : /mitsubishi-electric-championship-at-hualalai
SValues : {#{S1=championstour; S2=tournaments; S3=mitsubishi-electric-championship-at; S4=}}
But I'm stuck getting strange error message when trying to modify properties S1, S2, S4, or S4 within SValues property:
PS C:\Users\yuriy> $testTournament.SValues.S3 = 'newvalue'
The property 'S3' cannot be found on this object. Verify that the property exists and can be set.
At line:1 char:1
+ $testTournament.SValues.S3 = 'newvalue'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Why is it saying it cannot find the property? I can get its value easily by referring to it like this:
PS C:\Users\yuriy> $testTournament.SValues.S3
mitsubishi-electric-championship-at
What am I doing wrong?
UPD: Output of gm -i $testTournament.SValues is on screenshot: http://i.imgur.com/BeRr2aJ.png
JSON fragment is on screenshot: http://i.imgur.com/BBK2nsi.png (similar data)
The JSON file is read and converted using this code:
$testData = Get-Content -Raw -Path "Test Data.json" | ConvertFrom-Json
Then $testTournament is created:
$testTournament = $testData.Tournaments | Get-Random

Override Creation for Monitors and Rules

I want to create PowerShell scripts to override some parameter of my monitor and rule. I used the below code, but I have some errors. I want override my overidable parameter not enabled or something else. How can I doe this?
$mps = Get-SCOMManagementPack | ? {$_.Name -like "test"}
$overrideMp = Get-SCOMManagementPack -DisplayName "Overrides"
$overridename = "testmonitor.Overrides"
$monitor = 'testmonitor'
$override = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackMonitorPropertyOverride($overrideMp,$overridename)
$override.Monitor = $monitor
$override.Property = 'WarningThreshold'
$override.Value = 80
$override.DisplayName = "Overrides"
$overrideMp.Verify()
$overrideMp.AcceptChanges()
Errors:
error1: Exception setting "Property": "Cannot convert value "WarningThreshold" to
type "Microsoft.EnterpriseManagement.Configuration.ManagementPackMonitorProperty".
Error: "Unable to match the identifier name WarningThreshold to a valid enumerator
name. Specify one of the following enumerator names and try again: Enabled,
TraceEnabled, Algorithm, AlgorithmPercentage, DefaultState, GenerateAlert,
AutoResolve, AlertPriority, AlertOnState, AlertSeverity, AlertMessage,
AlertParameter1, AlertParameter2, AlertParameter3, AlertParameter4,
AlertParameter5, AlertParameter6, AlertParameter7, AlertParameter8,
AlertParameter9, AlertParameter10, MemberInMaintenance, MemberUnavailable,
IgnoreMemberInMaintenance, IgnoreMemberUnavailable""
At line:1 char:2
+ $override.Property = $parametername
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
error2 : Exception calling "AcceptChanges" with "0" argument(s): "Database error.
MPInfra_p_ManagementPackInstall failed with exception: Failed to validate item:
testrule1"
At line:193 char:1
+ $MP.AcceptChanges()
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ManagementPackException
The error message looks rather clear to me. There is no property WarningThreshold in the ManagementPackMonitorProperty enumeration. I don't have much experience with SCOM, but you probably need to override the property AlertOnState for monitors where the property AlertSeverity has the value Warning.
Try something along the lines of this:
$mps | Get-SCOMMonitor | Where-Object {
# (other selection criteria) -and
$_.AlertSettings.AlertSeverity -eq 'Warning'
} | ForEach-Object {
$ctx = Get-SCOMClass -Id $_.Target.Id
# ...
$override = New-Object ...
$override.Monitor = $_
$override.Property = 'AlertOnState'
$override.Value = 80
$override.Context = $ctx
# ...
}
Code adopted from here (probably the same place where you found it). Not sure if this works, though. Like I said, I have very little experience with SCOM, and I don't have a SCOM server available for testing.
I'll try to debug it tomorrow in the office.
BTW, there is a third-party tool for override management called MPTuner: http://mpwiki.viacode.com/default.aspx?g=mptuner
It's free so you should try.
Roman.
It's quite confusing, but there are two different type of overrides for each workflow type. For a monitor there are:
MonitorPropertyOverride
MonitorConfigurationOverride
You are using the first one, wgich is for standard parameters only, like Enabled, for example. For any custom parameters use Configuration Override.

Call to EnvDTE.TextSelection.FindPattern from PowerShell fails with type mismatch

I'm building a custom scaffolder to use with MvcScaffolding. Trying to automate adding code to the beginning of a method, I came up with the following code:
$codeElement = Get-ProjectType "MyType"
foreach ($member in $codeElement.Members)
{
if ($member.Name -eq "CreateMappings")
{
$editPoint = $member.StartPoint.CreateEditPoint()
# here's where it's crashing
$editPoint.FindPattern("\{")
$editPoint.Insert("text")
}
}
When I run my custom scaffolder, FindPattern fails with
Exception calling "FindPattern" with "1" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At Path\File.ps1:62 char:26
+ $editPoint.FindPattern <<<< ("\{")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
As opposed to this macro, which runs just fine:
Sub macro()
Dim objTD As TextDocument = DTE.ActiveDocument.Object("TextDocument")
Dim editPoint As EditPoint = objTD.StartPoint.CreateEditPoint()
If (editPoint.FindPattern("\{", vsFindOptions.vsFindOptionsRegularExpression)) Then
editPoint.CharRight()
editPoint.Insert("text")
End If
End Sub
What am I doing wrong?