如果名称在A列中匹配,则以CSV格式覆盖单元格

时间:2017-04-04 15:24:40

标签: powershell csv

我正在编译Powershell脚本以从CSV文件导入帐户,向用户询问几个问题并将现有数据覆盖回CSV文件。

该脚本效果很好,除非它到达Export-CSV,它会附加数据或覆盖整个文件。

有没有办法覆盖A列中匹配名称旁边的单元格,如果该帐户是新的,可以添加新行?

$accountName = Read-Host "What is the account name?"

$alldata = Import-Csv "C:\Users\$logontr\Desktop\NewAccounts\TestOutput0.csv"
$data = $alldata | Where-Object { $_."Account" -eq $accountName }

$serialNumber = Read-Host "Confirm Serial Number"

if ($data -ne $null) {
  # re-export the data, excluding the account
  $alldata | Where-Object { $_."Account" -ne $accountName } | Export-Csv C:\Users\$logontr\Desktop\NewAccounts\TestOutput0.csv -NoClobber -NoTypeInformation -Encoding ASCII
}

[pscustomobject]@{
  Account = $accountName
  Serial = $serialNumber
  SoftwareAssurance = $date.ToString("dd/MM/yyyy")
  Validated = Get-Date -Format d
  DataCollection = $DCRun
  DataCollectionDate = $DCRunDate
} | Export-Csv C:\Users\$logontr\Desktop\NewAccounts\TestOutput0.csv -NoClobber -NoTypeInformation -Encoding ASCII

由于

1 个答案:

答案 0 :(得分:0)

您是否有适当的检查以确保用户实际完成该过程?此解决方案可以正常运行,但需要进行一些错误检查,因此当用户取消中途时,您最终不会删除帐户。

$alldata = Import-CSV "C:\Users\$logontr\Desktop\NewAccounts\TestOutput0.csv"
$data =  $alldata | Where-Object { $_."Account" -eq $accountName }

# Code that gets information from user goes here.

if($data -ne $null){
    # re-export the data, excluding the account
    # edited to add -Force flag
    $alldata | Where-Object { $_."Account" -ne $accountName } | Export-csv C:\Users\$logontr\Desktop\NewAccounts\TestOutput0.csv -NoClobber -NoTypeInformation -Encoding ASCII -Force
}

# use existing append code
[pscustomobject]@{
Account = $accountName
Serial = $serialNumber
SoftwareAssurance = $date.ToString("dd/MM/yyyy")
Validated = Get-Date -Format d
DataCollection = $DCRun
DataCollectionDate = $DCRunDate
} | Export-csv C:\Users\$logontr\Desktop\NewAccounts\TestOutput0.csv -Append -NoClobber -NoTypeInformation -Encoding ASCII

# if the user does not complete the task, re-export the csv
# $alldata | Export-csv C:\Users\$logontr\Desktop\NewAccounts\TestOutput0.csv -NoClobber -NoTypeInformation -Encoding ASCII