user770022
user770022

Reputation: 2959

Why does this outputting numbers in the file not the machine name?

The file that I'm outputting doesnt contain the $machine and if its valid or not, it contains numbers. How do I get this to output the machine name and if its valid or not?

Import-Module ActiveDirectory
$enddate = Get-Date 
$machines=(Get-ADComputer -filter * -SearchBase 'OU=this,OU=is,OU=my,DC=domain,DC=com' -Properties * | Select Name, lastlogondate |Where-Object {$_.LastLogonDate -lt ($enddate).AddMonths(-2)} |Sort  lastlogondate).name
foreach ($machine in $machines) 
{
  if (test-Connection -ComputerName $machine -count 1 -ErrorAction SilentlyContinue) 
         {
            Write-Output "$machine is valid" 
         }
            Write-Output "$machine is not valid" | Export-Csv 
  c:\machine_not_valid.csv -Append -NoClobber -NoTypeInformation
}

Upvotes: 0

Views: 39

Answers (1)

G42
G42

Reputation: 10019

Export-Csv expects an object, not a string. It then uses the properties of this object as headers for the CSV.

It is outputting numbers because it is receiving string as input, which has the single property Length

You also have an error in your code where the "$machine is not valid" part is outside of the if statement and not in an else statement.

If you have multiple values, Export-Csv is the way to go. If you only have one, use Out-Fileas you will not need to create an object:

Import-Module ActiveDirectory
$enddate = Get-Date 
$machines=(Get-ADComputer -filter * -SearchBase 'OU=this,OU=is,OU=my,DC=domain,DC=com' -Properties * | Select Name, lastlogondate |Where-Object {$_.LastLogonDate -lt ($enddate).AddMonths(-2)} |Sort  lastlogondate).name

foreach ($machine in $machines) 
{
  if (test-Connection -ComputerName $machine -count 1 -ErrorAction SilentlyContinue) 
         {
            Write-Output "$machine is valid" 
         }else{
            Write-Output "$machine is not valid" | Export-Csv c:\machine_not_valid.csv -Append -NoClobber
         }  
}

Upvotes: 2

Related Questions