'How to make a filename by date with powershell

I'm pretty new to Powershell and would like to output the result of a command to a file name. I try the following within the powershell shell:

$a = (Get-Date).DayofYear 
$b = get-date -format "yy"
$date = "$b$a"
echo $date

This works fine.

But I'd like to have a cmd-file with the output »$date.txt«. How to proceed?

Thanks for all help in advance.



Solution 1:[1]

This should do the trick:

$a = (Get-Date).DayofYear 
$b = get-date -format "yy"
$date = "$b$a"
$date | out-file -FilePath "$date.txt"

... or depending on preference

$date | out-file -FilePath ($date + ".txt")

As per your comments, you can do this from CMD like so:

powershell.exe "((Get-Date).DayofYear).ToString() + (get-date -format 'yy').ToString()| % {$_ |Out-File ($_ + '.txt')}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1