PowerShell Newbie, so please forgive any misuse of lingo. Anyway, I’m trying to create an Array that has 4 properties and multiple values per property. I then want to be able to programmatically insert values into the array. I’ve included an example of the data that I expect, and some code to initialize the array and insert values into it.
Is there a different way to insert values into the array? I can’t seem to find anything online. I intend to use a while loop to do the inserts.
Your question and the example sounds/looks quite abstract. You may explain what you’re “real world use case” is. Then we might be able to recommend something meaningful.
To use the += operator is most of the time a bad idea because it destroys the array and creates a new one with newly added data. You may use a loop instead.
It is an object, not an array. Think of an object as an array of hash tables. The += is not best practice, so take a look at this as an example:
$svcs = 'AudioSrv', 'BITS','EventLog','Netlogon'
$results = foreach ($svcName in $svcs) {
#Get data for the specific service
$currentService = Get-Service -Name $svcName
#Output rolls up to the $results variables
[PSCustomObject]@{
Status = $currentService.Status
Name = $currentService.Name
DisplayName = $currentService.DisplayName
}
}
#Variable with all results
$results
This is part of an ETL process. I am making an API call that checks for records between Date1 and Date2 and writes them to a file that has a name like the following, FileName_Mystring1_MyString2.xml.
The MyString1 and MyString2 are just the Date1 and Date2 respectively in string format, so that they can be appended to the filename.
I need to dynamically populate the pscustomObject that I’m creating. I won’t always use the same date range(difference between Date1 and Date2).
Once I have the pscustomObject loaded with various date ranges, then I was planning on using a foreach loop to execute an api call for every date range.
Please let me know if that makes sense. I can also try and code this out in powershell before you answer.
As a note, a date is a string coming from a CSV or a manual object unless you cast or parse it to a DateTime. If the API requires the date to be in a specific format, need to make it a date time first to do date formatting, math, etc.