Reputation:
I'm a (very new) beginner with powershell and need help inputting a code that will add a comma and numerical increment to each line of output which would be a random number. The output is displayed in a file.
$file = "path to file"
for ($i=0; $i -le 4; $i++) {
$a = Get-Random -Minimum 10 -Maximum 50
Add-Content $file $a.ToString("0")
}
so the output of this would be 1 line for each random number such as:
12
30
22
41.. etc
I'd like it to look like this:
1,12
2,35
3,22
4,41
Can anyone please provide a code that would make this happen? any help would be much appreciated.
Upvotes: 1
Views: 168
Reputation: 439892
I suggest a more PowerShell-idiomatic solution that uses the pipeline (|
):
1..4 | ForEach-Object { '{0},{1}' -f $_, (Get-Random -Min 10 -max 50) } | Set-Content $file
1..4
uses the range operator (..
) to create an array of integers from 1
to 4
, inclusively.
ForEach-Object
invokes the associated script block ({ ... }
) for each input object (integer in this case) represented as automatic variable $_
:
'{0},{1}' -f $_, (Get-Random -Min 10 -max 50)
uses the the string-formatting operator (-f
), whose LHS is a format string containing positional placeholders for the RHS values ({0}
is placeholder for the 1st argument, ...), to produce an output string containing the integer at hand, followed by comma and the random number.Set-Content
saves all strings it receives to output file $file
(using the default character encoding, which in Windows PowerShell is the "ANSI" encoding implied by the legacy system locale; use parameter -Encoding
to change that).
Upvotes: 2
Reputation: 2642
Try this:
$file = "C:\Temp\test.txt"
for ($i=1; $i -le 5; $i++) {
$a = Get-Random -Minimum 10 -Maximum 50
$line = $i.ToString() + "," + $a.ToString()
Add-Content $file $line
}
Upvotes: 1