【发布时间】:2014-07-16 13:26:19
【问题描述】:
我是 powershell 新手。这是我正在尝试编写的一个脚本,简而言之,它将把计算机从 AD 拉到一个变量中。获取列表并遍历每个列表并执行以下操作:
- 测试连接(在线、离线)
- 测试操作系统架构
- 测试子项
- 将计算机、连接状态、子键值写入 csv 文件
每次我尝试输出到文件时,无论是 out-file 还是 export-csv,它都不能正确输出。它要么放置“长度”和值,要么放置一些长字符串。理想情况下,我希望导出到 csv,以便我可以操作数据。函数“DoesItemExist”是一个测试注册表是否存在的函数。代码如下:
#find computers names that start with H or D
$computers=Get-ADComputer -Filter {(name -like "H*") -or (name -like "D*")} -Properties
Name | select name
#save path to csv file
$SaveAs = 'c:\msolhelp\edocs.csv'
#loop through the computers collection
foreach($line in $computers)
{
#test if computer is online
if(Test-Connection -Cn $line -BufferSize 16 -Count 1 -ea 0 -quiet)
{
#write computer name to file
#test registry path for 64 bit machine
$OS=((Get-WmiObject Win32_Operatingsystem -ComputerName $line).OSArchitecture)
if ($OS = '64-bit')
#if 64 bit check for correct regkey and grab value and appends to file
{
$regpath = 'SOFTWARE\Wow6432Node\'
#check for subkey and append value to file
$val = (DoesItemExist -path $regpath -regEntry "PatchLevel")
If ($val) {
Get-ItemProperty "HKLM:SOFTWARE\Wow6432Node\" | Select-
Object -Property PatchLevel | Export-Csv -Path $SaveAs -Append -
NoTypeInformation }
else {Get-ItemProperty "HKLM:SOFTWARE\Wow6432Node\" |
Select-Object -Property CurrentVersion | Export-Csv -Path $SaveAs -Append -
NoTypeInformation}
}
#if false, it must be a 32 bit machine (different registry path)
else
{
#set path for 32 bit machine
$regpath = 'HKLM\SOFTWARE\'
#check for correct subkey
$val = (DoesItemExist -path $regpath -regEntry "PatchLevel")
If ($val) {
Get-ItemProperty "HKLM:SOFTWARE\" | Select-Object -
Property PatchLevel | Export-Csv -Path $SaveAs -Append -NoTypeInformation }
else {
Get-ItemProperty "HKLM:SOFTWARE\" | Select-Object -
Property CurrentVersion | Export-Csv -Path $SaveAs -Append -
NoTypeInformation}
}
}
#if test-connect fails, append file with 'offline'
else {
"$line, offline"
continue
}
}
【问题讨论】:
-
基本想法似乎是您正在运行此脚本,该脚本将与计算机联系以获取信息,并且该信息将被写入文件。拥有 DoesItemExist 函数会很不错,因为您的脚本似乎没有检查 $computers 中计算机的远程注册表。只是运行脚本的计算机。您能否展示一些看起来错误的示例输出,以便我们知道您想要实现的目标?
-
“没有正确显示”是一个不充分的问题描述。你得到了什么输出,这与你期望的输出有什么不同?
-
| select -expand name通常一个 csv 在每一行都有相同的列项。