Replace values in powershell object - arrays

Using powershell to set the HA datastores for my VMware environment. I just don't know how to replace a certain value.
$Cluster = Get-Cluster $ClusterName | Get-View
$HAInfo = $Cluster.Configuration.DasConfig
Result of $HAinfo is this:
Enabled : True
VmMonitoring : vmMonitoringDisabled
HostMonitoring : enabled
VmComponentProtecting : disabled
FailoverLevel : 1
AdmissionControlPolicy : VMware.Vim.ClusterFailoverResourcesAdmissionControlPolicy
AdmissionControlEnabled : True
DefaultVmSettings : VMware.Vim.ClusterDasVmSettings
Option : {das.ignoreRedundantNetWarning}
HeartbeatDatastore : {Datastore-datastore-2367254, Datastore-datastore-1586741}
HBDatastoreCandidatePolicy : userSelectedDs
LinkedView :
Now I'm interested in the HeartbeatDatastore, which now contains:
Type Value
---- -----
Datastore datastore-2367254
Datastore datastore-1586741
I need to replace the Value with new values. I could easily do this by just writing:
$Hainfo.HeartbeatDatastore[1].value = "newvalue"
But I can't be sure whether it contains 0, 1 or 2 values. My problem is that when for example it only contains 1 row (datastore, datastore-2367254), I don't know how I should add a new row with new values.
Not sure if this extra info is needed:
$Hainfo.HeartbeatDatastore | get-member
TypeName: VMware.Vim.ManagedObjectReference
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Type Property string Type {get;set;}
Value Property string Value {get;set;}
Please assist.

Solved it like this:
$HAInfo.HeartbeatDatastore.Clear()
$dsObj1 = New-Object VMWare.Vim.ManagedObjectReference
$dsObj1 = here I fill it with the values I converted
$HAInfo.HeartbeatDatastore += $dsObj1
$dsObj2 = New-Object VMWare.Vim.ManagedObjectReference
$dsObj2 = here I fill it with the values I converted
$HAInfo.HeartbeatDatastore += $dsObj2

Related

iterate an object array and create multiple records with the value from it

I have an Object Array scheduleTable__c, with the below fields:
Product | Description | Jan | Feb | Mar | ...
right now, it will create one record and filling all the fields accordingly. I would like to change this by creating one record for each month inside the Array. I guess the right way to do so is to create another array by iterating over the current array and insert that value.
Replace my function
#AuraEnabled
public static List<scheduleTable__c> createPSs(List<scheduleTable__c> psList){
insert psList;
return psList;
}
by that
#AuraEnabled
public static List<scheduleTable__c> createPSs(List<scheduleTable__c> psList){
String [] arraySC = new List<String>();
for(Integer i = 2; i < psList.size(); i++){
arraySC.push(psList[0]);
arraySC.push(psList[1]);
arraySC.push(psList[i]);
}
insert arraySC;
return arraySC;
}
It doesn't seems to like the fact that it is an array of an object and I am creating a String Array...
I then replaced the array with this but still not able to make it work...
List<scheduleTable__c> arraySC = new List<scheduleTable__c>();
any help will be appreciated.

How to update values in a nested json file by Powershell

I want to update some values of below content which i believe a json file. This is the output of azure devops release definition and I need to reuse the content modifying some fields.
I can simply update values like id and name using these lines
$ReleaseDef.Name = $newReleaseName
$ReleaseDef.path = $folderQA
But I dont know how to update array fields like artifact and triggers. I can get values by calling $ReleaseDef.artifacts.sourceid
but can not set any values there , It throws errors like The property 'sourceid' cannot be found on this object. Verify that the
property exists and can be set.
Please suggest
source : userInterface
revision : 4
description :
createdBy : #{displayName=Jyotiprakash Nayak; url=https://azuredevopsdv
.ril.com/EntApps/_apis/Identities/2ca8bd5d-7797-4177-b7bb-2
6daa0d29ed9; _links=;
id=2ca8bd5d-7797-4177-b7bb-26daa0d29ed9;
uniqueName=domain\Jyotiprakash.Nayak; imageUrl=https://azuredev
opsdv.company.com/EntApps/_apis/GraphProfile/MemberAvatars/win.
Uy0xLTUtMjEtMjIwNzU5NTE2Ni03MjEyNTY2NjUtNTU2MTkwNDkyLTQ4NjY
yMw; descriptor=win.Uy0xLTUtMjEtMjIwNzU5NTE2Ni03MjEyNTY2NjU
tNTU2MTkwNDkyLTQ4NjYyMw}
createdOn : 2019-12-10T09:11:11.057Z
modifiedBy : #{displayName=Jyotiprakash Nayak; url=https://azuredevopsdv
.company.com/EntApps/_apis/Identities/2ca8bd5d-7797-4177-b7bb-2
6daa0d29ed9; _links=;
id=2ca8bd5d-7797-4177-b7bb-26daa0d29ed9;
uniqueName=Domain\Jyotiprakash.Nayak; imageUrl=https://azuredev
opsdv.comapny.com/EntApps/_apis/GraphProfile/MemberAvatars/win.
Uy0xLTUtMjEtMjIwNzU5NTE2Ni03MjEyNTY2NjUtNTU2MTkwNDkyLTQ4NjY
yMw; descriptor=win.Uy0xLTUtMjEtMjIwNzU5NTE2Ni03MjEyNTY2NjU
tNTU2MTkwNDkyLTQ4NjYyMw}
modifiedOn : 2019-12-13T09:16:13.463Z
isDeleted : False
variables :
variableGroups : {}
environments : {#{id=7; name=Stage 1; rank=1; owner=; variables=;
variableGroups=System.Object[]; preDeployApprovals=;
deployStep=; postDeployApprovals=;
deployPhases=System.Object[]; environmentOptions=;
demands=System.Object[]; conditions=System.Object[];
executionPolicy=; schedules=System.Object[];
currentRelease=; retentionPolicy=; processParameters=;
properties=; preDeploymentGates=; postDeploymentGates=;
environmentTriggers=System.Object[]; badgeUrl=https://azure
devopsdv.comapny.com/EntApps/_apis/public/Release/badge/e0b1a36
0-01a5-4eea-af57-b2a461559ac9/7/7}}
artifacts : {#{sourceId=e0b1a360-01a5-4eea-af57-b2a461559ac9:48;
type=Build; alias=_eCAM-Team-CI; definitionReference=;
isPrimary=True; isRetained=False}}
triggers : {#{artifactAlias=_eCAM-Team-CI;
triggerConditions=System.Object[];
triggerType=artifactSource}}
releaseNameFormat : Release-$(rev:r)
tags : {}
pipelineProcess : #{type=designer}
properties : #{DefinitionCreationSource=}
id : 7
name : Release-Template-1
path : \QA
projectReference :
url : https://azuredevopsdv.company.com/EntApps/e0b1a360-01a5-4eea-af
57-b2a461559ac9/_apis/Release/definitions/7
_links : #{self=; web=}
These attributes contain hash table values.
You should be able to update by specifying the key and its new value like so:
$ReleaseDef.artifacts["sourceid"] = "someValueHere"
Thanks all for your valuable helps, I finally made it work through some foreach loops.
```$artifact = $json.artifacts
foreach ($value in $artifact)
{
$value.alias = "_$newReleaseName"
$value.sourceId = "$($projectid):$($BuildID)"
}
foreach ($triggervalue in $snapshot.triggers)
{
$triggervalue.artifactAlias = "_$newReleaseName"
}```

How can I convert collection laravel to array?

My code like this :
$test = $this->vendorRepository->getVendor($request->get('q'));
If I dd($test), the result is collection like this :
I want to convert it to array
I try like this :
dd($test->toArray());
The result like this :
value of id changed to 0
Why did it happen? How can I solve this problem?
This might be because your ID field is a string but laravel is expecting it to be an auto-incrementing integer.
Try adding this to the top of your model:
public $incrementing = false;

How to add hashtable to multidimensional array? Cannot assign values via member-access enumeration

I'm having trouble with adding hashtables to a multidimensional array. I coded the following:
$Data = #{BIBs = #(
#{$BIB = #{BIBName=$BIBName},
#{Standort = $Standort},
#{Bücher = #(
#{BuchName = $BuchName;
Autor = $Autor
})
}}
)}
This code is functioning and creates an output, which I store in a JSON:
{
"BIBs": [
{
"BIB1": [
{
"BIBName": "123"
},
{
"Standort": "123"
},
{
"Bücher": [
{
"Autor": "123",
"BuchName": "123"
}
]
}
]
},
{
"BIB2": [
{
"BIBname": "345"
},
{
"Standort": "345"
},
{
"Bücher": [
{
"Autor": "345",
"Buchname": "345"
}
]
}
]
}
]
}
I have extra code which adds another hashtable to array "BIBs" as you can see.
$jsonfile = "C:\Skripte\bibV2-1000.json"
$Data = Get-Content $jsonfile | ConvertFrom-Json
$Data.BIBs += New-Object -TypeName PSObject -Property #{
$BIB = #{BIBname=$BIBName}, #{Standort=$Standort},
#{Bücher = #(#{Buchname=$BuchName;Autor=$Autor})}
}
When the output is like above, I'm not able to add another hashtable to "Bücher". I checked the type of "Bücher" with
$data.BIBs.BIB1.Bücher.GetType()
and it's actually an array:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
I tried
$Data.BIBs.BIB1.Bücher += #{Person="Max";Alter="35"}
to add a new hashtable, like I did with "BIB2", but I am getting the error:
The property 'Bücher' cannot be found on this object. Verify that the property
exists and can be set.
At line:5 char:1
+ $data.BIBs.BIB1.Bücher += #{Motor="asdf";pers="345"}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Do you know how I add #{Person="Max";Alter="35"} to "Bücher"?
tl;dr
Setting a key / property value via member-access enumeration is not supported (see below).
Instead, you must obtain the specific object whose .Bücher property you want to modify explicitly:
($Data.BIBs.BIB1 | ? Bücher).Bücher += #{ BuchName='neues Buch'; Autor='Johann Doe' }
Note: This assumes that:
only one element of array $Data.BIBs.BIB1 has a .Bücher property (key)
that, if the property / key does exist, it is nonempty and therefore is "truthy" in a Boolean context, such as the expression passed to ? (Where-Object); like member-access enumeration, this simplified Where-Object syntax - ? Bücher instead of ? { $_.Bücher } - is a PSv3+ feature called comparison statement.
Mathias R. Jessen has provided the crucial pointer in comments on the question:
PowerShell has an intentional asymmetry with respect to dot notation across collection-valued properties for getting values vs. setting values.
On getting, PSv3+ applies member-access enumeration, which, in a nutshell, allows you to access a property on a collection and implicitly get that property's value from each element IN that collection, with the results getting collected in an array.
On setting, member-access enumeration is not applied; the rationale is that the risk of unintentional modification of data is too high - see GitHub issue #5271 and in particular this comment by a core member of the PS team.
The unfortunate aspect is that the current error message doesn't tell you that.
It stems from the fact that when attempting to set a property at the collection level, the property is looked for only directly on the collection (instead of on its elements), where it (usually) doesn't exist.
Let's take a look at a simplified example:
$data = #{ # a hashtable
a = ( # array of hashtables
#{ b1 = 'b1' },
#{ b2 = 'b2' },
#{ b3 =
#{ b31 = 'b31' }, #{ b32 = 'b32' } # array of hashtables
}
)
}
On getting, everything works fine:
PS> $data.a.b3
Name Value
---- -----
b31 b31
b32 b32
Even though $data.a is an [object[]] array, an object (hashtable) with property .b3 was found among its elements, and that object's .b3 value is output.
This is member-access enumeration in action (although the more typical uses is case for the property to exist on all elements of the array and for the individual values to be collected in an [object[]] array).
On setting, PowerShell forgoes member-access enumeration and therefore unsuccessfully looks for a .b3 property only directly on the [object[]] instance that is $data.a and, of course, arrays have no .b3 property:
PS> $data.a.b3 += #{ b33 = 'b33' } # Try to add an element; !! FAILS
The property 'b3' cannot be found on this object.
Verify that the property exists and can be set.
...

Passing arrays of variable in specflow

Is there a way to pass an array of parameters instead of passing each parameter individually?
For example I have the following scenarios:
When i login to a site
then <firstname>, <lastname>, <middleName>, <Desingation>, <Street>, <Apartmentno> are valid
The list can go on above. Instead can I pass all the above variables in an array?
You can pass a comma separated string and then transform it into a list:
When i login to a site
then 'Joe,Bloggs,Peter,Mr,Some street,15' are valid
[Then("'(.*)' are valid")]
public void ValuesAreValid(List<String> values)
{
}
[StepArgumentTransformation]
public List<String> TransformToListOfString(string commaSeparatedList)
{
return commaSeparatedList.Split(",").ToList();
}
if you want the values to come from examples then you could do this instead:
When I login to a site
then '<values>' are valid
Examples
| values |
| Joe,Bloggs,Peter,Mr,Some street,15|
| Joe,Bloggs,Peter,Mr,Some street,16,SomethingElse,Blah|
If you want to use a table then you could do this instead:
When I login to a site
then the following values are valid
| FirstName | LastName | MiddleName | Greeting| Etc | Etc |
| Joe | Bloggs | Peter | Mr | you get| The Idea|
(you could omit the headers if you want and just use the row values I think)
you can also use examples with this:
When I login to a site
then the following values are valid
| FirstName | LastName | MiddleName | Greeting | Etc | Etc |
| <name> | <lastName>| <middleName>| <greeting>| <etc> | <etc> |
This might be of help:
https://github.com/techtalk/SpecFlow/wiki/Step-Argument-Conversions
Add the following code snippet to your Common Step Definition File:
[StepArgumentTransformation]
public string[] TransformToArrayOfStrings(string commaSeparatedStepArgumentValues)
{
string sourceString = commaSeparatedStepArgumentValues;
string[] stringSeparators = new string[] { "," };
return sourceString.Split(stringSeparators, StringSplitOptions.None);
}
SpecFlow will then automatically convert all comma-separated values in the SpecFlow Steps data table into an array of strings.
Then in your individual step binding function, change the type of the input parameter as string[] as in snippet below:
[Then(#"the expected value is '(.*)'")]
public void ThenTheExpectedValueIs(string[] p0)
{
//ScenarioContext.Current.Pending();
Assert.AreEqual(25, Convert.ToInt32(p0[0]));
Assert.AreEqual(36, Convert.ToInt32(p0[1]));
Assert.AreEqual(79, Convert.ToInt32(p0[2]));
}
Then, based on your expected value for a test step, you may want to apply the appropriate type conversion.
Just transfer the data as a string Example:
Then LEDS 0, 1, 7 are on
[Then(#"LEDS (.*) are on(.*)]
public void ThenLEDAreOn(string p0)
{
int count = p0.Split(',').Length - 1;
string[] Leds_on = p0.Split(',');
foreach (string s in LEDs_on)
{
int.TryParse(s, out LEDS[index]);
index++;
}
}
Then you have your values as integers in an array

Resources