以下代码远程获取计算机信息。我无法将输出发送到日志文件。另外,如何在单独的日志文件中记录所有未经检测的计算机?
Code:
$ArrComputers = gc .\computernames.txt
Clear-Host
ForEach ($Computer in $ArrComputers)
{
$computerSystem = get-wmiobject Win32_ComputerSystem -Computer $Computer
$computerBIOS = get-wmiobject Win32_BIOS -Computer $Computer
$Version = Get-WmiObject -Namespace "Root\CIMv2" -Query "Select * from Win32_ComputerSystemProduct" -computer $computer | select version
write-host "System Information for: " $computerSystem.Name -BackgroundColor DarkCyan
"-------------------------------------------------------"
"Model: " + $computerSystem.Model
"Serial Number: " + $computerBIOS.SerialNumber
"Version: " + $Version
""
"-------------------------------------------------------"
}
答案 0 :(得分:1)
记录非常简单。您只需要将输出存储在变量中,然后使用Out-File
cmdlet:
$ArrComputers = gc .\computernames.txt
$OutputLog = ".\output.log" # Main log
$NotRespondingLog = ".\notresponding.log" # Logging "unqueried" hosts
$ErrorActionPreference = "Stop" # Or add '-EA Stop' to Get-WmiObject queries
Clear-Host
ForEach ($Computer in $ArrComputers)
{
try
{
$computerSystem = get-wmiobject Win32_ComputerSystem -Computer $Computer
$computerBIOS = get-wmiobject Win32_BIOS -Computer $Computer
$Version = Get-WmiObject -Namespace "Root\CIMv2" `
-Query "Select * from Win32_ComputerSystemProduct" `
-computer $computer | select -ExpandProperty version
}
catch
{
$Computer | Out-File -FilePath $NotRespondingLog -Append -Encoding UTF8
continue
}
$Header = "System Information for: {0}" -f $computerSystem.Name
# Outputting and logging header.
write-host $Header -BackgroundColor DarkCyan
$Header | Out-File -FilePath $OutputLog -Append -Encoding UTF8
$Output = (@"
-------------------------------------------------------
Model: {0}
Serial Number: {1}
Version: {2}
-------------------------------------------------------
"@) -f $computerSystem.Model, $computerBIOS.SerialNumber, $Version
# Ouputting and logging WMI data
Write-Host $Output
$Output | Out-File -FilePath $OutputLog -Append -Encoding UTF8
}
答案 1 :(得分:0)
在当前状态下,您的代码会为Get-WmiObject
命令无法访问的每台计算机发出错误。我会考虑在第一个-ErrorAction SilentlyContinue -ErrorVariable Err
命令的末尾使用Get-WmiObject
。这将阻止错误进入您的屏幕并堵塞您的输出。然后,只有在ErrorVariable为空时,才能调用对Get-WmiObject
的其他两个调用。如果存在,请记录计算机的名称,然后输出到文件。
您无法将任何其他内容记录到文件的原因是因为您使用的是Write-Host
。我会考虑使用PSObject来返回信息。这将允许您以有组织的方式查看屏幕上的输出,同时还允许您将输出写入文件。
此外,使用带有-ExpandProperty
的{{1}}开关将阻止您返回Version属性的哈希表。