将文本文件中的数据格式化为 CSV 文件

问题描述 投票:0回答:1

我正在用 VB Script 编写脚本来格式化 Active Directory 数据。我正在使用 Bat 脚本生成 txt 格式的输出,我想制作一个 VB 脚本来格式化带有标题的数据。

我的批处理脚本是

dsquery * -limit 0 -filter (objectclass=computer) -attr Name distinguishedName operatingSystem operatingSystemVersion whenChanged whenCreated > fullq.txt

我目前有的VB Script是这个

Option Explicit

Dim FSO, TextPath, CSVPath
Dim Textline, oText, oCSV
Dim CN, OU, i

Set FSO = CreateObject("Scripting.FileSystemObject")

TextPath = "fullq.txt"
Set oText = FSO.OpenTextFile(TextPath,1)

CSVPath = "fullq.csv"
Set oCSV = FSO.CreateTextFile(CSVPath, 2 ,False)

oCSV.WriteLine("Name,DistinguishedName,OperatingSystem,OperatingSystemVersion,whenChanged,whenCreated")
oCSV.WriteLine

oText.SkipLine
Do Until oText.AtEndOfStream
    Textline = oText.ReadLine()

    OU = Split(TextLine, ",")
    CN = Mid(OU(0), 5)

    oCSV.Write CN & ","
    For i = 1 To UBound(OU)
        oCSV.Write OU(i)
        If i < UBound(OU) Then
            oCSV.Write("/")
        End If
    Next
    oCSV.Writeline
Loop

oCSV.WriteLine
oCSV.Close

我遇到的问题是 operatingSystem、operatingSystemVersion、whenCreated 和 whenChanged 数据在 distinguishedName 列中。我希望它在他们各自的专栏中。上面的代码主要针对DistinguishedName。我添加了新属性,它们是 operatingSystem、operatingSystemVersion、whenChanged、whenCreated。对于 distinguishedName,我想用“/”替换逗号,而我希望将其余属性写在它们各自的列中。我不能使用 PowerShell,因为公司阻止了它。

CSV 中的输出如下所示:

Name,DistinguishedName,OperatingSystem,OperatingSystemVersion,whenChanged,WhenCreated

PC1,OU=1/OU=2/OU=3/DC=4/DC=COM    Window    123    12/12/12 10:10:10 12/12/12 10:10:10 , , ,
  • 注意逗号代表新列

如上所述,我尝试了此 VB 脚本,但操作系统、操作系统版本、创建时间和更改时间数据位于 distinguishedName 列中。我希望它在他们各自的专栏中。

这就是 fullq.txt 的样子:

Name        DistinguishedName              OperatingSystem        OperatingSystemVersion   whenChanged        WhenCreated
PC1         OU=1/OU=2/OU=3/DC=4/DC=COM     Window                    123 
      12/12/12 10:10:10     12/12/12 10:10:10 
batch-file vbscript active-directory
1个回答
0
投票

鉴于提供的

fullq.txt
样本,输入可以在
"  "
(两个空格)上拆分,然后忽略空条目和修剪结果:

Const Excel = True

Set oFSO = CreateObject("Scripting.FileSystemObject")

TextPath = "fullq.txt"
Set oText = oFSO.OpenTextFile(TextPath,1)

CSVPath = "fullq.csv"
Set oCSV = oFSO.CreateTextFile(CSVPath,2,True)

If Excel Then oCSV.WriteLine "SEP=,"
oCSV.WriteLine "Name,DistinguishedName,OperatingSystem,OperatingSystemVersion,whenChanged,whenCreated"

oText.SkipLine

Do Until oText.AtEndOfStream
    NewLine = ""
    Textline = oText.ReadLine
    aTextLine = Split(Textline,"  ")
    For i = 0 To UBound(aTextLine)
      If aTextLine(i)<>"" Then
        If NewLine<>"" Then NewLine = NewLine & ","
        NewLine = NewLine & Trim(aTextLine(i))
      End If
    Next
    oCSV.Writeline NewLine
Loop

oText.Close
oCSV.Close

请注意示例输入不包含逗号,因此我删除了以逗号分隔的代码。

© www.soinside.com 2019 - 2024. All rights reserved.