Andrew N.
Andrew N.

Reputation: 3

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

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'." 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.

Upvotes: 0

Views: 1187

Answers (1)

mjolinor
mjolinor

Reputation: 68301

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

Upvotes: 1

Related Questions