Getting Powershell Output to a File

Hello Experts,

I have a Powershell script that displays the output I want on the screen, but I'm not sure how to send it to a text or csv file as well.  I'm sure it is an easy thing to do, I'm just drawing a blank.  Here is my code:

$DaysInactive = 90
$Time = (Get-Date).Adddays(-($DaysInactive))
$DeadComputers = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties LastLogonTimeStamp | select name
foreach ($i in $DeadComputers)
{
if (Test-Connection -ComputerName $i.name -BufferSize 16 -Count 1 -Quiet) {Write-Host $i.name is online}
else {Write-Host $i.name is offline}
}

Thanks in advanced for your help.
LVL 1
ndalmolin_13Asked:
Who is Participating?
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
Here you are,

Don'tuse "Write-Host" except when you want the text to go to the console, and no-where else.

Putting text in quotes will print it normally.

(You can also use Write-Output "Text" but if you omit write-output it automatically assumes quoted text with no other commands is to be written using that method)

$DaysInactive = 90
$Time = (Get-Date).Adddays(-($DaysInactive)) 
$DeadComputers = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties LastLogonTimeStamp | select name
$Results=foreach ($i in $DeadComputers){
	if (Test-Connection -ComputerName $i.name -BufferSize 16 -Count 1 -Quiet) {
		"$($i.name) is online"
	} else {
		"$($i.name) is offline"
	}
}
# Export to a regular text File
$Results | Out-File "C:\Admin\Output.txt"
# Export to a CSV
$Results | Export-CSV"C:\Admin\Output.csv"

Open in new window

0
 
Dustin SaundersDirector of OperationsCommented:
Add a new property to your select results, then set it in your foreach loop.

Export those results to CSV  using Export-CSV.

Ex.
$DaysInactive = 90
$Time = (Get-Date).Adddays(-($DaysInactive)) 
$DeadComputers = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties LastLogonTimeStamp | select name,status

foreach ($i in $DeadComputers)
{
if (Test-Connection -ComputerName $i.name -BufferSize 16 -Count 1 -Quiet) {
    Write-Host $i.name is online
    $i.Status = "Online"
    }
else {
    Write-Host $i.name is offline
    $i.Status = "Offline"
    }
}

$DeadComputers | Export-CSV -Path "C:\test\deadcomputers.csv" -NoTypeInformation

Open in new window

2
 
ndalmolin_13Author Commented:
Thanks
0
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
Glad to help :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.