2017-08-01 59 views
0

我输出的文件不包含$机器,如果它有效或不包含数字。我如何得到这个输出机器名称,如果它的有效或没有?为什么输出文件中的数字不是机器名?

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 
} 

回答

2

Export-Csv期望一个对象,而不是一个字符串。然后,它使用此对象的属性作为CSV的标题。

它输出的数字,因为它是接收string作为输入,它具有单一的财产Length

您还可以在你的代码中的错误,其中"$machine is not valid"部分处于else声明外if声明,而不是。

如果您有多个值,Export-Csv是要走的路。如果您只有一个,请使用Out-File,因为您不需要创建对象:

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 
     } 
} 
+0

谢谢。那就是诀窍。 – user770022

相关问题