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.

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks but im required to get it from a loop kind of an assignment anyways thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.