2017-08-01 67 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

相關問題