将 PowerShell 变量输出到文本文件 [英] Output PowerShell variables to a text file

查看:94
本文介绍了将 PowerShell 变量输出到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 PowerShell 的新手,并且有一个脚本,该脚本在 Active Directory 中循环搜索某些计算机.我得到了几个变量,然后运行函数来检查诸如 WMI 和注册表设置之类的东西.

I'm new to PowerShell and have a script which loops through Active Directory searching for certain computers. I get several variables and then run functions to check things like WMI and registry settings.

在控制台中,我的脚本运行良好且简单Write-Host 命令根据需要在屏幕上打印数据.我知道 Export-Csv 在使用管道...但我不想从管道打印.

In the console, my script runs great and simple Write-Host command prints the data on the screen as I want. I know about Export-Csv when using the pipeline...but I'm not looking to print from the pipeline.

我想将变量写入文本文件,继续循环,并检查 AD 中的下一台计算机...在下一行输出相同变量的下一次迭代.这是我的写主机:

I want to write the variables to a text file, continue the loop, and check the next computer in AD...output the next iteration of the same variables on the next line. Here is my Write-Host:

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.

It gives me the data, but each variable is on its own line. Why? I'd like all the variables on one line with comma separation. Is there a simple way to do this akin to VB writeline? My PowerShell version appears to be 2.0.

推荐答案

我通常在这些循环中构建自定义对象,然后将这些对象添加到我可以轻松操作、排序、导出到 CSV 等的数组中:

I usually construct custom objects in these loops, and then add these objects to an array that I can easily manipulate, sort, export to CSV, etc.:

# 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"

这篇关于将 PowerShell 变量输出到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆