简体   繁体   English

在一行中将两个数组写入文件Powershell

[英]Writing two arrays in one line to a file, Powershell

I have always been able to find what I have been looking for on stack overflow with the search function. 我始终能够使用搜索功能找到堆栈溢出时一直在寻找的内容。 However this time I am a bit stuck and though I would break out and ask the community. 但是,这次我有点卡住,尽管我会爆发并向社区询问。

I am trying to write to a file with data from two arrays, for example: 我正在尝试使用来自两个数组的数据写入文件,例如:

$arrayString = @(“User1″, “User2″, “User3″)
$arrayInteger = @(1, 2, 3)

The line that I am not sure of is the line to write this to a file I have tried the following: 我不确定的行是将其写入文件的行,我尝试了以下操作:

Add-Content $filePath$ ($arrayString[0] $arrayinteger[0])

When I do this I get the error "Unexpected token "arrayinteger" in expression or statement 当我这样做时,我在表达式或语句中得到错误“意外的令牌“ arrayinteger”

I have also tried: 我也尝试过:

Add-Content $filePath$ ($arrayString[0] + $arrayinteger[0])

To which I get the error "Method invocation failed because [System.IO.DirectoryInfo] doesn't contain a method named 'op_Addition'." 我收到的错误消息是“由于[System.IO.DirectoryInfo]不包含名为'op_Addition'的方法,所以方法调用失败。” my understanding of this is I am trying to "Add" a String and a integer causing a error. 我对此的理解是,我试图“添加”一个字符串和一个导致错误的整数。

However if I attempt to write the line to the console this works: 但是,如果我尝试将行写入控制台,则可以正常工作:

write-host $arrayString[0] $arrayinteger[0]

The goal output I am trying to receive is 我尝试接收的目标输出是

User1 1
User2 2
User3 3

Thanks for your help. 谢谢你的帮助。

Here's a couple of different ways to solve this: 以下是解决此问题的几种不同方法:

$arrayString = @("User1","User2","User3")
$arrayInteger = @(1, 2, 3)

Using subexpressions in an expandable string: 在可扩展字符串中使用子表达式:

$(for ($i=0; $i -le 2;$i++)
 {
   "$($arrayString[$i]) $($arrayInteger[$i])"
 })| set-content $filepath

Using a format string: 使用格式字符串:

 $(for ($i=0; $i -le 2;$i++)
 {
   '{0} {1}' -f $arrayString[$i],$arrayInteger[$i] 
 }) | set-content $filepath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM