Powershell Write-Eventlog Linebreak

时间:2017-11-27 12:11:17

标签: powershell event-log

我制作的脚本会搜索具有特定操作系统的所有计算机,通过白名单运行它们,如果白名单上没有计算机,我会编写错误日志。日志现在看起来像这样:

@{Name=Computername1; Operatingsystem=Windows 10 Enterprise; DistinguishedName=CN=la,OU=computers,OU=lu,OU=Hosting,DC=a,DC=b,DC=ch; OperatingSystemVersion=10.0 (10586)}

但它应该是这样的:

Name=Computername1
Operatingsystem=Windows 10 Enterprise
DistinguishedName=CN=la,OU=computers,OU=lu,OU=Hosting,DC=a,DC=b,DC=ch
OperatingSystemVersion=10.0 (10586)

我想删除@{},4个信息应该用换行符分隔。

我的代码:

$username = $env:UserName

$getad = Get-ADComputer -Filter {(operatingsystem -like "*Windows 10*" -and OperatingSystemVersion -notlike "*16299*" -and OperatingSystemVersion -notlike "*14393*" -and OperatingSystemVersion -notlike "*14279*" -and OperatingSystemVersion -notlike "*15063*" -and OperatingSystemVersion -notlike "*10159*" -and OperatingSystemVersion -notlike "*16193*" -and OperatingSystemVersion -notlike "*17025*" -and OperatingSystemVersion -notlike "*10074*" -and OperatingSystem -notlike "*LTSB") -or (operatingsystem -like "*Windows Vista*") -or (operatingsystem -like "*Windows XP*") -or  (operatingsystem -like "*95*") -or (operatingsystem -like "*94*") -or ( operatingsystem -like "*Windows 8*" -and OperatingSystemVersion -notlike "*9600*" -and OperatingSystem -notlike "*LTSB") -or (operatingsystem -like "*2000 Professional*") -or (operatingsystem -like "*2000 Server*") -or (operatingsystem -like "*2003*") -or (operatingsystem -like "*Windows NT*") -or (operatingsystem -like "*Windows 7*" -and OperatingSystemVersion -notlike "*7601*" -and OperatingSystem -notlike "*LTSB")} -Properties ('Name', 'operatingsystem', 'DistinguishedName', 'OperatingsystemVersion') | ? {$_.distinguishedname -notlike "*OU=Oldwin10-Test,OU=a,OU=b,OU=c,OU=d,DC=e,DC=f,DC=ch"} 

$whitelisted = Get-Content "C:\Users\$username\Desktop\whitelistedpcs.txt"

$getad | Select-Object Name, Operatingsystem, DistinguishedName, 
OperatingSystemVersion | ForEach-Object {

   if ($whitelisted -match $_.DistinguishedName) {

   }

      else{
        Write-EventLog -LogName Application -Source "OldWinalert" -EntryType Error -EventId 1 -Message "$_"
      }
}   

1 个答案:

答案 0 :(得分:0)

您需要将输出转换为字符串,然后使用-Message将其发送到Out-String参数:

对于你的情况我会尝试这个:

[...] -EntryType Error -EventId 1 -Message ($_ | Format-List | Out-String)

另一种选择:

else{

$Message = @"
Name: $($_.name)
Operating System: $($_.Operatingsystem)
Distinguished Name: $($_.DistinguishedName)
Operating System Version: $($_.OperatingSystemVersion)

"@

Write-EventLog -LogName Application -Source "OldWinalert" -EntryType Error -EventId 1 -Message $Message
}

如果你想要额外的行空间,在括号

之后的每一行末尾添加`n(对于新行)