PowerShell array to store strings
arrays, powershell, string
Solution
I'd suggest working with objects instead of a lot of string arrays. I have an example below in which I have replaced the file listing, since I don't have the file structure in place, with an ordinary array. Just remove that array declaration and put in your `Get-ChildItem` call and it should work just fine.
function ConvertTo-MyTypeOfItem
{
PARAM (
[ValidatePattern("([^_]+_){3}[^_]+")]
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$StringToParse
)
PROCESS {
$custId, $invId, $prodId, [int]$value = $StringToParse -split "_"
$myObject = New-Object PSObject -Property @{
CustomerID = $custId;
InvoiceID = $invId;
ProductID = $prodId;
Value = $value
}
Write-Output $myObject
}
}
# In the test scenario I have replaced getting the list of files
# with an array of names. Just uncomment the first and second lines
# following this comment and remove the other $baseNames setter, to
# get the $baseNames from the file listing
#$files = Get-ChildItem test *.txt
#$baseNames = $files.BaseName
$baseNames = @(
"cust1_inv1_prod1_1";
"cust2_inv2_prod2_2";
"cust3_inv3_prod3_3";
"cust4_inv4_prod4_4";
)
$myObjectArray = $baseNames | ConvertTo-MyTypeOfItem
$myObjectArray
The above function will return objects with the `CustomerID`, `InvoiceID`, `ProductID` and `Value` properties. In the sample above, the function is called and the returned array value is set to the `$myObjectArray/code> variable. When output in the console it will give the following output:
InvoiceID CustomerID ProductID Value
--------- ---------- --------- -----
inv1 cust1 prod1 1
inv2 cust2 prod2 2
inv3 cust3 prod3 3
inv4 cust4 prod4 4
Problem
I have a list of files that I am breaking up into parts. That works, but I want to be able to reference each part individually. The issue is with my array not wanting/being able to take in a string. The file naming format is custID_invID_prodID or custID_invID_prodID_Boolvalue. ``` $files = Get-ChildItem test *.txt [string]$custId = $files.Count [string]$invID = $files.Count [string]$prodID = $files.Count [int]$Boolvalue = $files.Count foreach($file in (Get-ChildItem test *.txt)) { for($i = 0; $i -le $files.Count; $i++){ $custId[$i], $invID[$i], $prodID[$i], $Boolvalue[$i] = $file.BaseName -split "_" Write-Host $custId, $invID, $prodID, $Boolvalue } } ``` The error message I am seeing is: Unable to index into an object of type System.String. How can I do this?