2

I want to write a script that creates a directory which does not exist and create a file in that folder. The script should also be able to assign a value to the file. The following is my code, but it does not assign the value to the file. In this case, i'm trying to insert the array into the file.

$myarray=@()

for($x=0;$x -lt 20; $x++) {

$myarray += $x

}

New-Item -Path C:\temp -Force -Name myarray.log -ItemType File -Value $myarray 

when I open the file, myarray.log all I see is 'System.Object[]' but not the array. Need some help here.

Yini
  • 85
  • 1
  • 1
  • 6

2 Answers2

2

It writes 'System.Object[]' because that's what the $myarray.ToString() outputs. One solution would be:

New-Item -Path C:\temp -Force -Name myarray.log -ItemType File -Value $($myarray -join ' ') 

This will write all the elements of the array in the file separated by spaces.

More solutions here: How do I convert an array object to a string in PowerShell?

Community
  • 1
  • 1
marosoaie
  • 2,352
  • 23
  • 32
1

marosoaie has answered your question, but you can also replace:

$myarray=@()

for($x=0;$x -lt 20; $x++) {

    $myarray += $x

}

with

$myarray = 1..20

to create an array of the numbers from 1 to 20. Short example:

PS C:\> 1..5
1
2
3
4
5
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87