gpt4 book ai didi

string - 用于存储字符串的 PowerShell 数组

转载 作者:行者123 更新时间:2023-12-04 14:45:20 25 4
gpt4 key购买 nike

我有一个文件列表,我将这些文件分成几部分。这有效,但我希望能够单独引用每个部分。问题在于我的阵列不想/无法接收字符串。文件命名格式为 custID_invID_prodID 或 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
}
}

我看到的错误消息是:

Unable to index into an object of type System.String.



我怎样才能做到这一点?

最佳答案

我建议使用对象而不是大量的字符串数组。我在下面有一个示例,其中我替换了文件列表,因为我没有使用普通数组的文件结构。只需删除该数组声明并放入您的 Get-ChildItem打电话,它应该可以正常工作。

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

上面的函数将返回带有 CustomerID 的对象, InvoiceID , ProductIDValue特性。在上面的示例中,调用了该函数并将返回的数组值设置为 $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

关于string - 用于存储字符串的 PowerShell 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21884828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com