我是 PowerShell 的新手,并且有一个脚本,它在 Active Directory 中循环搜索某些计算机。我得到了几个变量,然后运行函数来检查诸如 WMI 之类的东西。和注册表设置。
在控制台中,我的脚本运行良好且简单 Write-Host命令根据需要在屏幕上打印数据。我知道 Export-Csv使用管道时……但我不想从管道打印。
我想将变量写入文本文件,继续循环,并检查 AD 中的下一台计算机...在下一行输出相同变量的下一次迭代。这是我的写主机:
Write-Host ($computer)","($Speed)","($Regcheck)","($OU)
输出文件:
$computer,$Speed,$Regcheck | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200
它给了我数据,但每个变量都在自己的行上。为什么?我希望所有变量都用逗号分隔在一行中。有没有一种类似于 VB writeline 的简单方法来做到这一点?我的 PowerShell 版本似乎是 2.0。
请您参考如下方法:
我通常在这些循环中构建自定义对象,然后将这些对象添加到一个我可以轻松操作、排序、导出到 CSV 等的数组中:
# Construct an out-array to use for data export
$OutArray = @()
# The computer loop you already have
foreach ($server in $serverlist)
{
# Construct an object
$myobj = "" | Select "computer", "Speed", "Regcheck"
# Fill the object
$myobj.computer = $computer
$myobj.speed = $speed
$myobj.regcheck = $regcheck
# Add the object to the out-array
$outarray += $myobj
# Wipe the object just to be sure
$myobj = $null
}
# After the loop, export the array to CSV
$outarray | export-csv "somefile.csv"