从多台计算机获取WMI数据并导出到CSV [英] Get WMI Data From Multiple Computers and Export to CSV
问题描述
因此,今天拥有一些不错的老式Powershell挫败感.我需要做的是这样:
So having some good old fashion Powershell frustrations today. What I need to do is this:
- 从文件获取计算机列表
- 从Win32_OperatingSystem查询那些计算机的"CSName"和"InstallDate"
- 将InstallDate转换为可用的日期格式.
- 将所有内容导出到.csv
我已经尝试了许多不同的脚本迭代.我遇到了两个主要问题.一是即使使用Export-Csv -Append
,我也无法导出并附加到.Csv.它仅采用第一个值,其余则不执行任何操作.第二点是,在管道|
时,我无法使datetime转换器正常工作.
I've tried so many different iterations of my script. I run into 2 major issues. One is that I can't export and append to .Csv even with Export-Csv -Append
. It just takes the first value and does nothing with the rest. The 2nd is that I can't get the datetime converter to work when piping |
.
以下是我尝试过的一些示例-均无用.
Here's a few samples of what I've tried - none of which work.
此示例仅犯了很多错误.似乎没有从管道中的WMI查询中继承$_
.看起来它正在尝试使用第一个管道中的数据,但我不确定.
This sample simply errors a lot. Doesn't seem to carry $_
over from the WMI query in the pipe. It looks like it is trying to use data from the first pipe, but I'm not sure.
Get-Content -Path .\Computernames.txt | Foreach-Object {
gwmi Win32_OperatingSystem -ComputerName $_) |
Select-Object $_.CSName, $_.ConvertToDateTime($OS.InstallDate).ToShortDateString()
} | Export-Csv -Path Filename -Force -Append -NoTypeInformation
}
这个简单地导出第一个值,而在导出.Csv时放弃其余的值
This one simply exports the first value and gives up on the rest when exporting .Csv
$Computers = Get-Content -Path .\Computernames.txt
foreach ($Computer in $Computers) {
echo $Computer
$OS = gwmi Win32_OperatingSystem -ComputerName $Computer
$OS | Select-Object
$OS.CSName,$OS.ConvertToDateTime($OS.InstallDate).ToShortDateString() |
Export-Csv -Path $Log.FullName -Append
}
这个确实可以获取数据,但是当我尝试选择任何内容时,我会得到空值,但是我可以echo
很好.
This one does get the data, but when I try to select anything, I get null values, but I can echo
just fine.
$OS = gwmi Win32_OperatingSystem -ComputerName $Computers
$OS | Foreach-Object {
Select-Object $_.CSName,$_.ConvertToDateTime($OS.InstallDate).ToShortDateString() |
Export-Csv -Path $Log.FullName -Force -Append -NoTypeInformation
}
这感觉应该很简单.我几乎可以毫不费力地用C#做到这一点,但是我无法让PS来完成我想要的事情.任何帮助将不胜感激!
This feels like it should be ridiculously simple. I can do this in C# with almost no effort, but I just can't get PS to do what I want. Any help would be much appreciated!
推荐答案
来了,
$Array = @() ## Create Array to hold the Data
$Computers = Get-Content -Path .\Computernames.txt
foreach ($Computer in $Computers)
{
$Result = "" | Select CSName,InstallDate ## Create Object to hold the data
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $Computer
$Result.CSName = $OS.CSName ## Add CSName to line1
$Result.InstallDate = $OS.ConvertToDateTime($OS.InstallDate).ToShortDateString() ## Add InstallDate to line2
$Array += $Result ## Add the data to the array
}
$Array = Export-Csv c:\file.csv -NoTypeInformation
这篇关于从多台计算机获取WMI数据并导出到CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!