Gra*_*y D 6 arrays string powershell
我有一个文件列表,我分成几部分.这有效,但我希望能够单独引用每个部分.问题在于我的数组不希望/能够接受字符串.文件命名格式为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
}
}
Run Code Online (Sandbox Code Playgroud)
我看到的错误信息是:
无法索引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
Run Code Online (Sandbox Code Playgroud)
上述函数将返回对象与CustomerID,InvoiceID,ProductID和Value属性.在上面的示例中,调用函数并将返回的数组值设置为Get-ChildItem属性.我的其他页面可以轻松访问它,我很容易编辑出关于将错误写入服务器数据库的部分.
该CustomerID页面配置(摘录):
InvoiceID CustomerID ProductID Value --------- ---------- --------- ----- inv1 cust1 prod1 1 inv2 cust2 prod2 2 inv3 cust3 prod3 3 inv4 cust4 prod4 4Run Code Online (Sandbox Code Playgroud)
如何编辑我的文件,以便我的应用程序中的任何页面(源自母版页)发生的任何错误,只需通过母版页显示此基本信息,而不是将页面重定向到另一个URL?
| 归档时间: |
|
| 查看次数: |
47877 次 |
| 最近记录: |