vbs输出结果到文本文件

Output result to a text file in vbs

请帮助更正我的代码,我需要将结果显示在屏幕上并将其记录到文本文件中。

Set WshShell = CreateObject("WScript.Shell")

MsgBox ConvertToKey(WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId"))
WScript.Echo "ConvertToKey(WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId"))" > C:\WindowsKey.txt

Function ConvertToKey(Key)
Const KeyOffset = 52
i = 28
Chars = "BCDFGHJKMPQRTVWXY2346789"
Do
Cur = 0
x = 14
Do
Cur = Cur * 256
Cur = Key(x + KeyOffset) + Cur
Key(x + KeyOffset) = (Cur \ 24) And 255
Cur = Cur Mod 24
x = x -1
Loop While x >= 0
i = i -1
KeyOutput = Mid(Chars, Cur + 1, 1) & KeyOutput
If (((29 - i) Mod 6) = 0) And (i <> -1) Then
i = i -1
KeyOutput = "-" & KeyOutput
End If
Loop While i >= 0
ConvertToKey = KeyOutput
End Function

这是经过更正的脚本。注意删除 MsgBox 行,更正 WScript.Echo 行(删除 non-VBScript 重定向代码)并添加正确的缩进:

Set WshShell = CreateObject("WScript.Shell")
WScript.Echo ConvertToKey(WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId"))

Function ConvertToKey(Key)
  Const KeyOffset = 52
  i = 28
  Chars = "BCDFGHJKMPQRTVWXY2346789"
  Do
    Cur = 0
    x = 14
    Do
      Cur = Cur * 256
      Cur = Key(x + KeyOffset) + Cur
      Key(x + KeyOffset) = (Cur \ 24) And 255
      Cur = Cur Mod 24
      x = x -1
    Loop While x >= 0
    i = i -1
    KeyOutput = Mid(Chars, Cur + 1, 1) & KeyOutput
    If (((29 - i) Mod 6) = 0) And (i <> -1) Then
      i = i -1
      KeyOutput = "-" & KeyOutput
    End If
  Loop While i >= 0
  ConvertToKey = KeyOutput
End Function

现在,代替 double-clicking 脚本,打开 Cmd 提示符并输入此命令(更改脚本名称以匹配您的 vbs 文件):

cscript getkey.vbs>%temp%\WindowsKey.txt

重定向是 Cmd shell 的东西,不是 VBScript 的东西。

另请注意,上述操作会将文件保存到您的 Temp 文件夹中。您试图保存到 C: 根目录下的文件。这将导致 accessed denied 错误。

或者,您可以将脚本更改为直接写入文件,如下所示:

Set WshShell = CreateObject("WScript.Shell")
Key = ConvertToKey(WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId"))

Const ForWriting = 2
Set oFSO = CreateObject("Scripting.FileSystemObject")
Temp  = WshShell.ExpandEnvironmentStrings("%Temp%")
Set oFile = oFSO.OpenTextFile(Temp & "\WindowsKey.txt",ForWriting,True)
oFile.Write Key
oFile.Close

WScript.Echo Key

Function ConvertToKey(Key)
  Const KeyOffset = 52
  i = 28
  Chars = "BCDFGHJKMPQRTVWXY2346789"
  Do
    Cur = 0
    x = 14
    Do
      Cur = Cur * 256
      Cur = Key(x + KeyOffset) + Cur
      Key(x + KeyOffset) = (Cur \ 24) And 255
      Cur = Cur Mod 24
      x = x -1
    Loop While x >= 0
    i = i -1
    KeyOutput = Mid(Chars, Cur + 1, 1) & KeyOutput
    If (((29 - i) Mod 6) = 0) And (i <> -1) Then
      i = i -1
      KeyOutput = "-" & KeyOutput
    End If
  Loop While i >= 0
  ConvertToKey = KeyOutput
End Function

None 其中是新的,许多其他答案都涵盖了它,您已经指出了其中的一些答案。毫无疑问,这个问题将作为重复问题关闭,但您似乎需要一些额外的帮助,所以就在这里。