[英]Converting .csv format (Import-Csv ) to string in PowerShell
I am trying to write a PowerShell script to 我正在尝试编写PowerShell脚本来
System.String
type format. System.String
类型格式。 In particular, I am struggling with the conversion to the string type format- what is the best way to do this. 特别是,我正在努力转换为字符串类型格式-什么是最好的方法?
Script 1: 脚本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"
}
Script 2: 脚本2:
Receive inputs from script 1: 从脚本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
You can obtain headers directly from a newly created $csv
object. 您可以直接从新创建的
$csv
对象获取标头。 In the below example $header
becomes an array of strings: 在下面的示例中,
$header
成为字符串数组:
$header = ($csv[0].psobject.Properties |
where {$_.MemberType -eq "NoteProperty" }).Name
An alternative is to use Get-Content
cmdlet to read the first line and split it on the ,
character: 另一种方法是使用
Get-Content
cmdlet来读取第一行,并把它分解的,
性格:
$header = (Get-Content $csvPath -TotalCount 1) -split ","
In your code, $header
is equal to null, because $header = Write-Host $rows[1]
does not assign a variable. 在您的代码中,
$header
等于null,因为$header = Write-Host $rows[1]
不分配变量。 It only performs an action. 它仅执行一个动作。
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: 如果未引用CSV文件中的数据,则应该可以直接从.csv文件使用它,而无需执行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++
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.