Your example code is confusing! You never place anything in the variable $results and, at the end of the script you export it to the same file you exported $output to!
The code below doesn't change what your example does. It's simply trying to understand what you're trying to do. Is $results supposed to have any contents? You're using "ForEach (<expression>)" to manage the loop, but that statement doesn't allow for any pipelining, and because you never write anything (you're always assigning the results to a variable), $results won't have any content!
Connect-AzAccount -UseDeviceAuthentication
$result = @() # I'm guessing here becasue there's no reference
# to this variable except when it's exported to a CSV!
Get-Content D:\azure.txt |
ForEach-Object{
Write-Host $_
$azvm = Get-AzVM -Name $_
$subid = ($azvm.Id -split '/')[2]
$subname = (Get-AzSubscription -SubscriptionId $subid).Name
# Should $results be updated here as well ??????
[PSCustomObject]@{
Name = $vmname
ResourceGroupName = $azvm.ResourceGroupName
Subscription = $subname
}
} | Export-Csv -Path D:\output.csv -NoTypeInformation
# Why is $results written to the same file???
$results | Export-Csv -Path D:\output.csv -NoTypeInformation