locked
Test Code Block Colorization RRS feed

  • Question

  • This is an example of VBScript code, using VB.NET selection:

    ' Test colorization of VBScript code.
    Option Explicit
    
    Dim strValue, k, objNetwork, A(), x, y
    Dim objWMI, objDisk
    ReDim Preserve A(3)
    Const ForReading = 1
    
    On Error Resume Next
    If (Err.Number <> 0) Then
        Wscript.Echo "???" _
            & vbCrLf & "xxx"
        Wscript.StdOut.WriteLine "yyy"
    End If
    On Error GoTo 0
    y = Array("1", "2", "3")
    
    Set objNetwork = CreateObject("Wscript.Network")
    Wscript.Echo objNetwork.UserName
    Set objNetwork = Nothing
    Set objWMI = GetObject("winmgmts:")
    Set objDisk = objWMI.Get("Win32_LogicalDisk.DeviceID='c:'")
    k = 0
    Wscript.Sleep 1000
    Do Until k = 1
        k = k + 1
        If (((k = 3) And (k > 0)) Or (Err.Number <> 0)) Then
            Exit Do
        End If
    Loop
    Do While k < 3
        k = k + 1
        If (k > 4) Then Exit Do
    Loop
    Do While Not (k = 0)
        k = 0
    Loop
    For Each x In A
        If (x = "NO") Then
            Exit For
        ElseIf (x = "YES") Then
            Wscript.Quit
        Else
            ' Do nothing.
        End If
        x = Null
    Next
    For x = LBound(A) To UBound(A)
        ' Do nothing.
    Next
    If IsArray(A) Then Wscript.Echo UBound(A)
    If (varType(A) And vbArray) <> False Then
        Wscript.Echo "Yes"
    End If
    While (k < 5)
        k = k + 1
    Wend
    Select Case k
        Case 0
            ' Do nothing.
        Case 1
            ' Do nothing.
        Case Else
            ' Do nothing.
    End Select
    k = 0
    Do
        If (k = 1) Then
            Exit do
        End If
        k = k + 1
    Loop While (k < 2)
    Do
        k = k + 1
    Loop Until (k = 3)
    Execute "k = k + 1"
    k = Eval("3 + 5")
    
    strValue = "default"
    Call MySub("Test 1")
    MySub "Test 2"
    strValue = MyFunction("Test 3")
    Wscript.Echo strValue
    
    Sub MySub(ByVal Value1)
        Call MsgBox("Hello World" & vbCrLf & Value1)
        Exit Sub
    End Sub
    
    Function MyFunction(ByVal Value1)
        MyFunction = Value1
        MsgBox "Hello World" & vbCrLf & Value1
        Exit Function
    End Function
    


    Richard Mueller - MVP Directory Services
    Saturday, October 8, 2011 5:31 PM

All replies

  • Below is the same VBScript program (with slight modifications, adding comments for further testing), but this time I used my new VBScript program to convert the code to HTML with colorization. I then pasted the HTML into the reply using the "Edit HTML Source" button:

     

    ' Test colorization of VBScript code.
    ' Comment with 'keyword' End, "End".
    Option Explicit

    Dim strValue, k, objNetwork, A(), x, y
    Dim objWMI, objDisk
    ReDim Preserve A(3)
    Const ForReading = 1

    On Error Resume Next
    If (Err.Number <> 0) Then
        Wscript.Echo "???" _
            & vbCrLf & "xxx"
        Wscript.StdOut.WriteLine "yyy"
    End If
    On Error GoTo 0
    y = Array("1" , "2" , "3" ) ' Initialize the array.

    Set objNetwork = CreateObject("Wscript.Network")
    Wscript.Echo objNetwork.UserName
    Set objNetwork = Nothing
    Set objWMI = GetObject("winmgmts:")
    Set objDisk = objWMI.Get("Win32_LogicalDisk.DeviceID='c:'")
    k = 0
    Wscript.Sleep 1000
    Do Until k = 1
        k = k + 1
        If (((k = 3) And (k > 0)) Or (Err.Number <> 0)) Then
            Exit Do
        End If
    Loop
    Do While k < 3
        k = k + 1
        If (k > 4) Then Exit Do
    Loop
    Do While Not (k = 0)
        k = 0
    Loop
    For Each x In A
        If (x = "NO" ) Then
            Exit For
        ElseIf (x = "YES" ) Then
            Wscript.Quit
        Else
            ' Do nothing.
        End If
        x = Null
    Next
    For x = LBound(A) To UBound(A)
        ' Do nothing.
    Next
    If IsArray(A) Then Wscript.Echo UBound(A)
    If (varType(A) And vbArray) <> False Then
        Wscript.Echo "Yes"
    End If
    While (k < 5)
        k = k + 1
    Wend
    Select Case k
        Case 0
            ' Do nothing.
        Case 1
            ' Do nothing.
        Case Else
            ' Do nothing.
    End Select
    k = 0
    Do
        If (k = 1) Then
            Exit Do
        End If
        k = k + 1
    Loop While (k < 2)
    Do
        k = k + 1
    Loop Until (k = 3)
    Execute "k = k + 1"
    k = Eval("3 + 5")

    strValue = "default"
    Call MySub("Test 1")
    MySub "Test 2"
    strValue = MyFunction("Test 3")
    Wscript.Echo strValue

    Sub MySub(ByVal Value1)
        Call MsgBox("Hello World" & vbCrLf & Value1)
        Exit Sub
    End Sub

    Function MyFunction(ByVal Value1)
        MyFunction = Value1
        MsgBox "Hello World" & vbCrLf & Value1
        Exit Function
    End Function

    -----

     

    Notice that spacing and indentation are maintained, and a fixed-width font is used.

     


    Richard Mueller - MVP Directory Services
    Sunday, October 9, 2011 11:40 PM
  • Another example from the forums:

     

    Option Explicit

    Dim objRootDSE, strDNSDomain, objTrans, strNetBIOSDomain
    Dim strComputer, strComputerDN, objComputer, strNewDescr

    ' Constants for the NameTranslate object.
    Const ADS_NAME_INITTYPE_GC = 3
    Const ADS_NAME_TYPE_NT4 = 3
    Const ADS_NAME_TYPE_1779 = 1

    ' Determine DNS name of domain from RootDSE.
    Set objRootDSE = GetObject("LDAP://RootDSE")
    strDNSDomain = objRootDSE.Get("defaultNamingContext")

    ' Use the NameTranslate object.
    Set objTrans = CreateObject("NameTranslate")

    ' Initialize NameTranslate by locating the Global Catalog.
    objTrans.Init ADS_NAME_INITTYPE_GC, ""

    ' Use the Set method to specify the DNS domain name.
    objTrans.Set ADS_NAME_TYPE_1779, strDNSDomain

    ' Use the Get method to retrieve the NetBIOS name of the domain.
    strNetBIOSDomain = objTrans.Get(ADS_NAME_TYPE_NT4)

    ' Remove trailing backslash.
    strNetBIOSDomain = Left(strNetBIOSDomain, Len(strNetBIOSDomain) - 1)

    ' Prompt for computer name.
    strComputer = InputBox("Enter NetBIOS name of computer", "My Script Title")

    ' Specify the new computer description (or prompt for or retrieve from elsewhere).
    strNewDescr = "My Computer Description"

    ' Use the Set method to specify the NT format of the object name.
    ' The sAMAccountName of computer objects is the NetBIOS name
    ' with a trailing "$" character. Trap error if object not found in AD.
    On Error Resume Next
    objTrans.Set ADS_NAME_TYPE_NT4, strNetBIOSDomain & "\" & strComputer & "$"
    If (Err.Number <> 0) Then
        On Error GoTo 0
        Wscript.Echo "Computer " & strComputer & " not found in Active Directory"
        Wscript.Quit
    End If
    ' Restore normal error handling.
    On Error GoTo 0

    ' Use the Get method to retrieve the RPC 1779 Distinguished Name.
    strComputerDN = objTrans.Get(ADS_NAME_TYPE_1779)

    ' Bind to the computer object in AD.
    Set objComputer = GetObject("LDAP://" & strComputerDN)

    ' Assign new description.
    objComputer.description = strNewDescr

    ' Save changes.
    objComputer.SetInfo

    -----

     


    Richard Mueller - MVP Directory Services
    Monday, October 10, 2011 4:11 PM
  • Here is a PowerShell script, pasted in the reply using the "Insert Code Block" button, and selecting PowerShell for the language:

     

    # Test colorization of PowerShell code.
    
    Trap {"Error: $_"; Break;}
    Function GetFlags ($lngValue)
    {
        # Function to test bits of userAccountControl attribute.
        # Returns settings that are True in semicolon delimited string.
        $String = ""
        If ($lngValue -band 2) {$String = "$String;User account disabled"}
        If ($lngValue -band 32) {$String = "$String;No password required"}
        $String = $String.Trim(";")
        Return $String
    }
    
    # Search entire domain.
    $D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
    $Domain = [ADSI]"LDAP://$D"
    $Searcher = New-Object System.DirectoryServices.DirectorySearcher
    $Searcher.PageSize = 200
    $Searcher.SearchScope = "subtree"
    
    # Filter on all user objects.
    $Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
    # Attribute values to retrieve.
    $Searcher.PropertiesToLoad.Add("distinguishedName") > $Null
    $Searcher.PropertiesToLoad.Add("userAccountControl") > $Null
    
    # Output header line.
    """Distinguished Name"",""Flags"""
    
    $Results = $Searcher.FindAll()
    ForEach ($Result In $Results)
    {
        $DN = $Result.Properties.Item("distinguishedName")
    
        # Test bits of userAccountControl.
        $lngFlags = $Result.Properties.Item("userAccountControl")
        $Flags = GetFlags $lngFlags.Item(0)
    
        # Display values comma delimited, enclosed in quotes.
        """$DN"",""$Flags"""
    }
    
    If ($x -not $y) {"Yes"}
    Else {'No'}
    $y = [Math]::PI
    $x = "abcdef" -replace "b", "X"
    $z = [String]$y
    $Script:Count = 0
    $w = 'whatever'
    
    


    Richard Mueller - MVP Directory Services
    Monday, October 10, 2011 10:20 PM
  • The same PowerShell script, but using my VBScript program to convert the code into HTML with colorization, then pasted in the reply with the "Edit HTML Source" button:

     

    # Test colorization of PowerShell code.

    Trap {"Error: $_"; Break;}
    Function GetFlags ($lngValue)
    {
        # Function to test bits of userAccountControl attribute.
        # Returns settings that are True in semicolon delimited string.
        $String = ""
        If ($lngValue -band 2) {$String = "$String;User account disabled"}
        If ($lngValue -band 32) {$String = "$String;No password required"}
        $String = $String.Trim(";")
        Return $String
    }

    # Search entire domain.
    $D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
    $Domain = [ADSI]"LDAP://$D"
    $Searcher = New-Object System.DirectoryServices.DirectorySearcher
    $Searcher.PageSize = 200
    $Searcher.SearchScope = "subtree"

    # Filter on all user objects.
    $Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
    # Attribute values to retrieve.
    $Searcher.PropertiesToLoad.Add("distinguishedName") > $Null
    $Searcher.PropertiesToLoad.Add("userAccountControl") > $Null

    # Output header line.
    """Distinguished Name"",""Flags"""

    $Results = $Searcher.FindAll()
    ForEach ($Result In $Results)
    {
        $DN = $Result.Properties.Item("distinguishedName")

        # Test bits of userAccountControl.
        $lngFlags = $Result.Properties.Item("userAccountControl")
        $Flags = GetFlags $lngFlags.Item(0)

        # Display values comma delimited, enclosed in quotes.
        """$DN"",""$Flags"""
    }

    If ($x -not $y) {"Yes"}
    Else {'No'}
    $y = [Math]::PI
    $x = "abcdef" -replace "b", "X"
    $z = [String]$y
    $Script:Count = 0
    $w = 'whatever'

    -----

     This version doesn't handle strings enclosed in single quotes.

     


    Richard Mueller - MVP Directory Services
    Tuesday, October 11, 2011 1:12 AM
  • test
    Tuesday, October 11, 2011 4:02 AM
  • Another PowerShell code snippet, pasted with "Insert Code Block" and selecting PowerShell for the language:

    $filter = "LogFile='Security' and TimeGenerated >= '$date'"
    
    $(C:\Windows\System32\dnscmd.exe $(hostname) /resetforwarders $(forwardersip))
    
    $main = @()
    
    #query session is different than query user, returns different data
    #http://support.microsoft.com/kb/186592
    $return = query user
    $a = $return | %{$_ -split "\s{2,}"} | where {$_ -ne ""}
    
    for($i=0;$i -lt $a.length;$i+=6)
    {
       $session = new-object object
       $session | Add-Member -MemberType "noteproperty" -Name UserName -Value $a[$i+0]
       $session | Add-Member -MemberType "noteproperty" -Name SessionName -Value $a[$i+1]
       $session | Add-Member -MemberType "noteproperty" -Name ID -Value $a[$i+2]
       $session | Add-Member -MemberType "noteproperty" -Name State -Value $a[$i+3]
       $session | Add-Member -MemberType "noteproperty" -Name IdleTime -Value $a[$i+4]
       $session | Add-Member -MemberType "noteproperty" -Name LogonTime -Value $a[$i+5]
       $main += $session
    }
    #$main | format-table
    
    $ComputerName = Get-Content $env:computername
    
    $EmailTo = "youremail@none.com"
    $EmailFrom = "myemail@none.com"
    $EmailSubject = "Your RDP session has been idle."
    $EmailBody = "Your RDP session on $ComputerName has been idle for $main[$i].IdleTime."
    
    for ($i=0;$i -lt $main.length; $i++)
    {
    		#filter out the first line and active sessions (the period)
    		if ($main[$i].IdleTime -ne "IDLE TIME" -and $main[$i].IdleTime -ne "." -and $main[$i].State -ne "Active")
    		{
    			$A = $main[$i].state
    			Write-Host "A is $a"
    			$IdleTime = [TimeSpan]($A -replace "\+",":")
    			Write-Host "Idle time is $IdleTime"
    			"Days " + $IdleTime.Days
    			"Hours " + $IdleTime.Hours
    
    		}
    }
    
    


    Richard Mueller - MVP Directory Services
    Wednesday, October 12, 2011 4:12 PM