首页 > 解决方案 > VBS在文本文件中写入多行

问题描述

我有一个检查所有用户并检查其上次登录时间的 vbscript。我打开一个文件在文件中写入。但是,我似乎有一个问题,它只写它检查的姓氏,而不是所有的名字。

文本中的结果应该是:

用户 1 用户 2 用户 3 用户 4

但是,这是我目前的结果:

用户4

我该怎么做?

我很抱歉,因为我主要使用 C#,而 VBS 对我来说很新。

Option Explicit
Dim strComputer, objComputer, objUser, FSO, File
Const ForWriting = 2
strComputer = "."
Set objComputer = GetObject("WinNT://" & strComputer)
objComputer.Filter = Array("user")
For Each objUser In objComputer
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile("C:\Users\sgbvx\Desktop\test\test.txt",ForWriting, True)
On Error Resume Next
Wscript.Echo objUser.Name & ", " & objUser.LastLogin
File.WriteLine objUser.Name
File.Write objUser.LastLogin
File.Close
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo objUser.Name & ", "
End If
On Error GoTo 0
Next
File.Close

标签: vbscript

解决方案


所以显然我的代码有一些安排问题,造成了很多错误。

这是我的答案和上面的更新代码:

Option Explicit
Dim strComputer, objComputer, objUser, FSO, File
Const ForWriting = 2
strComputer = "."
Set objComputer = GetObject("WinNT://" & strComputer)
objComputer.Filter = Array("user")
Set FSO = CreateObject("Scripting.FileSystemObject")

//You may change the file name or directory//
Set File = FSO.OpenTextFile("C:\temp\test.txt",ForWriting, True)

//Start of ForEach loop , previously Set FSO and Set File was in this loop//

For Each objUser In objComputer
On Error Resume Next
//Writes Username and LastLogin detail//
File.Write objUser.Name & ", " & objUser.LastLogin
File.WriteLine
If (Err.Number <> 0) Then
On Error GoTo 0
//Writes only Username if LastLogin was not detected//
File.Write objUser.Name & ", "
File.WriteLine
End If
On Error GoTo 0
Next
File.Close

推荐阅读