2010-08-23 55 views
10

在行「If(IsNull(value))then」下面是我的代碼是否正確?我想檢查註冊表項是否存在,如果不存在,則顯示一個網頁。vbscript and checking for null

Option Explicit 
On error resume next 
Dim SysVarReg, Value 
Set SysVarReg = WScript.CreateObject("WScript.Shell") 
value = SysVarReg.RegRead ("HKCU\Software\test\FirstLogonComplete") 

If (IsNull(value)) then 

    Set WshShell = WScript.CreateObject("WScript.Shell") 
    WshShell.Run "c:\Program Files\Internet Explorer\iexplore.exe https://intranet/start.htm" 

    Dim SysVarReg2, Value2 
    Value2 = "TRUE" 
    Set SysVarReg2 = WScript.CreateObject("WScript.Shell") 
    SysVarReg2.RegWrite "HKCU\Software\test\FirstLogonComplete", Value2 

else 
    wscript.echo "Already logged on" 
end if 

回答

5

如果RegRead引發錯誤,則value未初始化;未初始化的變量的值爲Empty,而不是Null。 因此,你應該Dim聲明之後加入該行

value = Null 

。否則,IsNull將始終返回False

+0

這裏的關鍵(沒有雙關語意)是RegRead [拋出一個錯誤(HTTP ://msdn.microsoft.com/en-us/library/x05fawxd%28v=vs.84%29.aspx)如果該鍵不存在,並且OP已打開「On Error Resume Next」。或者,可以使用'IsEmpty(value)'而不是'IsNull(value)'。 – 2013-01-08 05:24:10

2

你的意思是'空'或'沒有'?

在VBScript中,Nothing表示沒有值(或空指針)。 Null用於表示來自數據庫的NULL值。

有關更多信息,請參閱this link

另外,請參閱this example對於如何在一個註冊表項存在檢測:

Const HKLM = &H80000002 
Set oReg =GetObject("Winmgmts:root\default:StdRegProv") 

sKeyPath = "Software\Microsoft\Windows\CurrentVersion" 
If RegValueExists(HKLM, sKeyPath, sValue) Then 
    WScript.Echo "Value exists" 
Else 
    WScript.Echo "Value does not exist" 
End If 

Function RegValueExists(sHive, sRegKey, sRegValue) 
    Dim aValueNames, aValueTypes 
    RegValueExists = False 
    If oReg.EnumValues(sHive, sKeyPath, aValueNames, aValueTypes) = 0 Then 
    If IsArray(aValueNames) Then 
     For i = 0 To UBound(aValueNames) 
     If LCase(aValueNames(i)) = LCase(sRegValue) Then 
      RegValueExists = True 
     End If 
     Next 
    End If 
    End If 
End Function 
0

這是我解決業務問題。他們想讓USB只讀,這樣數據就不會在拇指驅動器上流連忘返。在ping和連接到WMI之後,我必須確定密鑰是否已經存在並且值已設置。在幾千臺電腦上。

keyExists = fnReadKeyValue() 

'====================================== 
'====================================== 


Function fnReadKeyValue() 
    ' ' EXAMPLE VALUES 
    ' const HKEY_LOCAL_MACHINE = &H80000002 
    ' strComputer = "." 
    ' strKeyPath = "SYSTEM\CurrentControlSet\Control\StorageDevicePolicies" 
    ' strEntryName = "WriteProtect" 

    Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ 
     strComputer & "\root\default:StdRegProv") 

    objReg.GetDWordValue HKEY_LOCAL_MACHINE, strKeyPath, strEntryName, strValue 
    if IsNull(strValue) then 
     objLogFile.WriteLine "That registry value doesn't exist." 
     fnReadKeyValue = "FAIL" 
    else 
     fnReadKeyValue = strValue 
    end if 

End Function 
4

在VBScript中 - 其中所有變量都是變量 - 變量可以是兩個特殊值之一:EMPTY或NULL。 EMPTY被定義爲具有未初始化值的變量,而NULL是不包含有效數據的變量。

如果你想測試變量,即「價值」是否爲null或空,然後使用下面的if語句:

If IsNull(value) Or IsEmpty(value) Then 
    '...do something 
End If