在PowerShell中将.csv格式(Import-Csv)转换为字符串 [英] Converting .csv format (Import-Csv ) to string in PowerShell
本文介绍了在PowerShell中将.csv格式(Import-Csv)转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将PowerShell脚本编写为
I am trying to write a PowerShell script to
- 读取CSV文件
- 循环浏览CSV文件中的每一行.
- 在每个循环中,我都希望将CSV标头和行值传递给另一个脚本,均采用
System.String
类型的格式.
- Read in a CSV file
- loop over each row in the CSV file.
- Within each loop I want to pass the CSV header and row values to another script, both in
System.String
type format.
特别是,我正在努力转换为字符串类型格式-做到这一点的最佳方法是什么.
In particular, I am struggling with the conversion to the string type format- what is the best way to do this.
脚本1:
$csvPath = 'C:\Temp\Scripts\trial_csv.csv'
# Get the header
$header = Get-Content $csvPath -TotalCount 1
$IntermediateOutput = "'C:\Temp\Scripts\output'"
$scriptPath = 'C:\Temp\Scripts\Temp.ps1'
# Get the data
Get-Content $csvPath |
Select -Skip 1 |
ForEach-Object {
$argumentList = @()
$argumentList += ("-Header", $header)
$argumentList += ("-row", $row)
$argumentList += ("-IntermediateOutput", $IntermediateOutput)
$argumentList += ("-index", $i )
Invoke-Expression "& `"$scriptPath`" $argumentList"
}
脚本2:
从脚本1接收输入:
Param(
[Parameter(Mandatory=$True)]
[String]$header, # The header of CSV file
[Parameter(Mandatory=$True)]
[String]$row, # The row of the file, like "1,0,2,.."
[Parameter(Mandatory=$True)]
[String]$IntermediateOutput, # Intermediate directory
[Parameter(Mandatory=$True)]
[String]$index # Index
)
Do something later (todo)
$a = $header
$b = $row
$c = $IntermediateOutput
$d = $index
推荐答案
如果未引用CSV文件中的数据,则应该可以直接从.csv文件使用它,而无需执行Import-Csv :
If the data in your CSV file isn't quoted, you should be able to use it directly from the .csv file without need to do the Import-Csv:
$csvPath = 'C:\Temp\Scripts\trial_csv.csv'
$IntermediateOutput = "'C:\Temp\Scripts\output'"
$Index = 1
# Get the header
$header = Get-Content $csvPath -TotalCount 1
# Get the data
Get-Content $csvPath |
Select -Skip 1 |
ForEach-Object {
$argumentlist = "-Header '{0}' -row '{1}' -IntermediateOutput {2} -Index {3}" -f $header,$_,$IntermediateOutput,$Index
# Execute script with argument list
$Index++
}
这篇关于在PowerShell中将.csv格式(Import-Csv)转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文