2012-01-03 97 views
4

我试图从注册表中获取计算机名称并将其写入文件。在这一点上,我从注册表获取计算机名称的函数调用不起作用。任何意见,将不胜感激。如何获取系统的计算机名称并将其输出到VBScript中的文件中

Option Explicit 
On Error Resume Next 

Dim regComputerName, ComputerName 

Set objShell = WScript.CreateObject("WScript.Shell") 
Set objFileSystem = CreateObject("Scripting.FileSystemObject") 

regComputerName = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\Computername" 
ComputerName = obj.shell.RegRead(regComputerName) 

oWrite.WriteLine(ComputerName,C:\text) 

回答

5

阅读注册表值很容易出错,在Windows 7可能需要提升权限有获得计算机名,非常类似现在你在做什么的另一种方式:

Set objNetwork = WScript.CreateObject("WScript.Network") 
ComputerName = objNetwork.ComputerName 
MsgBox ComputerName 

而且,在脚本中的最后一行:oWrite.WriteLine(ComputerName,C:\text)不会有两个原因工作:

  1. C:\text必须加引号,像这样:"C:\text.txt"
  2. 在VB中,只有一个产生值的函数可以用圆括号来调用。呼叫WriteLine喜欢这个:oWrite.WriteLine ComputerName, "C:\text.txt"

最后,你确定你是不是指的VBScript,而不是VB在你的问题?

+0

我指的是VBScript中。谢谢......我会研究这个。 – Soberone 2012-01-04 01:29:33

2

您的代码不工作,因为在这一行错误:

ComputerName = obj.shell.RegRead(regComputerName) 

相反obj.shell的,你应该引用objShell。它应该是这样的:

Set objShell = WScript.CreateObject("WScript.Shell") 
strRegKey = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\Computername" 
strComputerName = objShell.RegRead(strRegKey) 
WScript.Echo strComputerName 

不过,也有越来越多的计算机名称,而不必处理注册表的更可靠的方法。

从WSH(如上面所建议的)

Set WshNetwork = WScript.CreateObject("WScript.Network") 
strComputerName = WshNetwork.ComputerName 
WScript.Echo "Computer Name: " & strComputerName 

从环境变量...

Set wshShell = WScript.CreateObject("WScript.Shell") 
strComputerName = wshShell.ExpandEnvironmentStrings("%COMPUTERNAME%") 
WScript.Echo "Computer Name: " & strComputerName 

从WMI ...

strcomputer = "." 
Set objWMISvc = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 
Set colItems = objWMISvc.ExecQuery("Select * from Win32_ComputerSystem",, 48) 
For Each objItem in colItems 
    strComputerName = objItem.Name 
    WScript.Echo "Computer Name: " & strComputerName 
Next 

从ADSI ...

Set objSysInfo = CreateObject("WinNTSystemInfo") 
strComputerName = objSysInfo.ComputerName 
WScript.Echo "Computer Name: " & strComputerName 

从ADSI(仅适用于域成员)...

Set objSysInfo = CreateObject("ADSystemInfo") 
strComputerName = objSysInfo.ComputerName 
WScript.Echo "Computer Name: " & strComputerName 

...和Windows XP用户的最后一个办法......

Set objPC = CreateObject("Shell.LocalMachine") 
strComputerName = objPC.MachineName 
WScript.Echo "Computer Name: " & strComputerName 
相关问题