Powershell。我想向我的数组$computers添加一个对象,但它说索引超出范围
我想向我的数组$computers添加一个对象 但它说该指数超出了范围Powershell。我想向我的数组$computers添加一个对象,但它说索引超出范围,powershell,Powershell,我想向我的数组$computers添加一个对象 但它说该指数超出了范围 function ajouterperipherique ($id, $emplacement, $type) { $computers = import-csv -path "C:\Temp\Peripherique.csv" echo $computers $newObject = [pscustomobject]@{ idObject = $id
function ajouterperipherique ($id, $emplacement, $type) {
$computers = import-csv -path "C:\Temp\Peripherique.csv"
echo $computers
$newObject = [pscustomobject]@{
idObject = $id
EmplacementObject = $emplacement
TypeObject=$type
}
for ($i = 0; $i -lt $computers.Count; $i++) {
if ($i +1 -eq $computers.count) {
$computers[$computers.count+1]=$newObject
}
}
Write-Host ($newObject | Format-List | Out-String)
}
ajouterperipherique "GLADIATOR" "ordinateur" "Statique"
以下是Lee_Dailey提出的解决方案:
$csvPath='C:\Temp\Peripherique.csv'
function ajouterperipherique {
param(
[string]$ID,
[string]$Emplacement,
[string]$Type,
[string]$Path
)
if(-not(Test-Path $Path) -or -not [IO.Path]::GetExtension($Path) -eq '.csv')
{
throw 'File doest not exist or is not a Csv...'
}
[pscustomobject]@{
Identifiant = $id
Type = $type
Emplacement = $emplacement
}|Export-Csv $Path -NoTypeInformation -Append
}
ajouterperipherique -ID "GLADIATOR" -Emplacement "ordinateur" -Type "Statique" -Path $csvPath
正如评论中所指出的,有几个技巧,您不应该真正使用,或者尽可能避免使用Write Host
你不应该在你的函数中对路径进行硬编码,因为它们是要被重用的,你知道的将来可能改变的硬编码信息从来都不是一个好主意
您可能还想考虑将参数设置为<代码>强制< /代码>,参数在PosiS壳中有些重要,可以使您的生活更轻松。如果您想在将来创建更多函数,我建议您阅读本文:
这是否回答了您的问题?否@zett42请不要鼓励这种构造。如果您只想将一项添加到现有CSV文件中。。。你知道标题。。。然后只需使用所需信息制作一个[PSCustomObject]
,并使用Export CSV
和-Append
参数。这就是参数的用途。。。[咧嘴笑]@Lee_Dailey我看到你总是给最小阻力的路:)@SantiagoSquarzon-我天生懒惰。。。[grin]我有一个错误:导出Csv:无法将Csv内容添加到以下文件:C:\Temp\Peripherique.Csv。添加的对象没有与以下列对应的属性:Identifiant;类型;安置;。要继续使用不同的属性,请添加settingWell,错误几乎是不言自明的。这意味着您现有的Csv没有与您尝试添加的Csv相同的标题。查看我的捕获这是我的Csv此处,我编辑了我的代码,因此它创建了一个与您的Csv具有相同列名的对象。我有相同的错误:(