Showing posts with label developer scripts. Show all posts
Showing posts with label developer scripts. Show all posts

Monday, November 14, 2011

HowTo: Pretend you are working (While Text Browsing)

Commandline Web Browser (Just like lynx) using VbScript and IE API.

About the code: The code below will use the Internet Explorer API to load the top 20 stories from google news and choosing one of the article will load the document html of the target URL for you to be able to read news from your DOS command line. Best way to look like you are still working on a code while actually reading news without opening any web browsers :p

Requirements: IE 6++

Code Snippet:

Sub Loadnews()
Dim arrTestArray()
Dim urlSelect
intSize = 0
Dim rInterval:rInterval=60
Dim sTime:sTime = Now
Set ie = CreateObject("InternetExplorer.Application")
with ie
.visible = 0
.navigate "http://news.google.com/"
WScript.StdOut.Write vbcrlf & vbtab & "Loading Top Stories for @ " & Now
while .busy
WScript.StdOut.Write "."
WScript.Sleep 1000
wend
WScript.Echo vbcrlf & vbtab & "elapsed : " & datediff("s",sTime,Now) & " secs"
WScript.Echo vbtab & "next refresh: " & dateadd("s",rInterval,Now) & " secs" & vbcrlf
dim ctr:ctr=1
Set newsTitle = .Document.getElementsByTagName("a")
For each xTag in newsTitle
If instr(xTag.InnerHTML,"titletext") >0 then
WScript.Echo vbcrlf & vbtab & ctr & ". " & xTag.InnerText & _
"..." & vbcrlf & vbTab & "[" & xTag & "]"
ctr = ctr + 1
ReDim Preserve arrTestArray(intSize)
arrTestArray(intSize) = xTag
intSize = intSize + 1
If ctr >20 Then Exit For
End If
Next
end with
ie.quit
Set ie = nothing
Dim sleepctr:sleepctr=1
WScript.StdOut.Write vbcrlf & vbtab & "Choose an article #: "

urlSelect = WScript.StdIn.ReadLine
Set ie = CreateObject("InternetExplorer.Application")
Dim tgt:tgt=arrTestArray(urlSelect-1)
with ie
.navigate tgt
WScript.StdOut.Write vbcrlf & vbtab & "Loading [URL]..." & arrTestArray(urlSelect-1)
while .busy
WScript.StdOut.Write "."
WScript.Sleep 1000
wend
WScript.Echo .Document.Body.InnerText
end with
WScript.StdOut.Write vbcrlf & vbtab & "Press any key to continue..."
jcontinue = WScript.StdIn.ReadLine

End Sub


Screen grab:



If at first you fail, call it version 1.0

Thursday, February 14, 2008

Outlook: Move Items to Folder (with GUI folder list and not inputbox)

I was searching for a Macro online for Outlook mail items moved to different folders.

Have seen few codes that performs the same but with this code I used the GUI folder listing instead of prompting for an inputbox to avoid errors as most users are not aware of the Folder paths.

I submitted the code to OutlookCodeDotCom: Moving mail items to specified folder

It has 30++ downloads so far... not bad!

  1. Sub MoveMailToFolders()
  2. Dim objNS As Outlook.NameSpace
  3. Dim MyFolder As Outlook.MAPIFolder
  4. Dim objItem As Outlook.MailItem
  5. Dim ctr As Integer
  6. On Error Resume Next
  7. ctr = 0
  8. Set objNS = Application.GetNamespace("MAPI")
  9. Set MyFolder = objNS.PickFolder
  10. MsgBox "The selected mail item(s) will be moved to: " & vbCrLf & vbCrLf & _
  11. "Folder Path: " & MyFolder.FolderPath & vbCrLf & _
  12. "Folder Name: " & MyFolder.Name _
  13. , vbOKOnly + vbInformation, "Outlook Help"
  14. For Each objItem In Application.ActiveExplorer.Selection
  15. If MyFolder.DefaultItemType = olMailItem Then
  16. If objItem.Class = olMail Then
  17. ctr = ctr + 1
  18. objItem.Move MyFolder
  19. End If
  20. End If
  21. Next
  22. MsgBox "Moved: " & ctr & " mail item(s) to: " & MyFolder.Name, vbInformation, "Outlook Help"
  23. Set objNS = Nothing
  24. Set MyFolder = Nothing
  25. End Sub


Then using the Customize option on the toolbar, you can create a button for the Macro and assign a shortcut key to it!


If at first you fail, call it version 1.0

Wednesday, January 30, 2008

Latest Project: Server Monitoring Using WMI

It was a while since my last post. Year ender is quite busy and the new year was as much.

I've been working on a latest project for our team. I set up a monitoring server running WMI scripts against remote servers in intervals of 2 or 30mins (depending on the frequency of data required).

Below are few simple snippets I used in to collect remote data and pump it in an html template and send it via email to the team (if ever performance thresholds were exceeded).

Code Snippets:

  1. Sub DisplayErrorInfo
  2. WScript.Echo "Error: : " & Err
  3. WScript.Echo "Error (hex) : &H" & Hex(Err)
  4. WScript.Echo "Source : " & Err.Source
  5. WScript.Echo "Description : " & Err.Description
  6. Err.Clear
  7. End Sub

#1 Bytes Converter Snippet (
One of my favorite snippet, pretty handy!)

  1. Function SetBytes(Bytes,fKB)
  2. If fKB=True then Bytes = Bytes * 1024
  3. If Bytes >= 1073741824 Then
  4. SetBytes = FormatNumber((Bytes / 1024 / 1024 / 1024),2,,-1,-1) & " GB"
  5. ElseIf Bytes >= 1048576 Then
  6. SetBytes = FormatNumber((Bytes / 1024 / 1024),2,,-1,-1) & " MB"
  7. ElseIf Bytes >= 1024 Then
  8. SetBytes = FormatNumber((Bytes / 1024),2,,-1,-1) & " KB"
  9. ElseIf Bytes <>
  10. SetBytes = Bytes & " Bytes"
  11. End If
  12. End Function

#2 Get Available Memory on the server

  1. strComputer = "."
  2. Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
  3. Set colItems = objWMIService.ExecQuery _
  4. ("Select * From Win32_PerfRawData_PerfOS_Memory")
  5. For Each objItem in colItems
  6. intValue = objItem.AvailableBytes
  7. Wscript.Echo "Available memory = " & SetBytes(intValue,false)
  8. Exit For
  9. Next

Note: This requires cooking. If you you have no idea how that works then just use AvailableMBytes instead.

#3 Get CPU Usage (%)

  1. Function GetCPUProcUsg(svr)
  2. c = 0
  3. strComputer = "."
  4. Set objWMIService = GetObject("winmgmts:\\" _
  5. & strComputer & "\root\cimv2:Win32_PerfRawData_PerfOS_Processor.Name='_Total'")
  6. If Err = 0 Then
  7. While (True)
  8. N1 = objWMIService.PercentProcessorTime
  9. D1 = objWMIService.TimeStamp_Sys100NS
  10. Wscript.Sleep(1000)
  11. Set objWMIService2 = GetObject("winmgmts:\\" _
  12. & strComputer & "\root\cimv2:Win32_PerfRawData_PerfOS_Processor.Name='_Total'")
  13. N2 = objWMIService2.PercentProcessorTime
  14. D2 = objWMIService2.TimeStamp_Sys100NS
  15. PercentProcessorTime = (1 - ((N2 - N1)/(D2-D1)))*100
  16. Wscript.Echo "Processor Usage: " & Round(PercentProcessorTime,2) & "%"
  17. GetCPUProcUsg = Round(PercentProcessorTime,2) & "%"
  18. Wend
  19. Else
  20. DisplayErrorInfo
  21. End If
  22. Set objWMIService = nothing
  23. Set objWMIService2 = nothing
  24. End Function

#4 Get Available Disk Space
  1. strComputer = "."
  2. strUser =
  3. strPass =
  4. Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
  5. Set oWMI = objSWbemLocator.ConnectServer(strComputer, "root\cimv2", strUser, strPass)
  6. Set colDisks = oWMI.InstancesOf("win32_PerfRawData_PerfDisk_LogicalDisk.Name")
  7. For Each objDisk in colDisks
  8. intBaseValue = objDisk.PercentFreeSpace_Base
  9. dblActualFreeSpace = (100 * objDisk.PercentFreeSpace) / intBaseValue
  10. Wscript.Echo objDisk.Name & Int(dblActualFreeSpace)
  11. Next


If at first you fail, call it version 1.0

Thursday, September 13, 2007

HowTo: Enum Citrix Server License using LMSTAT

Our PS4 server seems to fail to execute the license information scripts from Citrix.Com (Dependency on SDK).

So instead of relying on it, I decided to develop a script using LMSTAT and a short vb script to parse the output file and write it to a .CSV file for better viewing (Data Filtering and such...)

First I piped the result of lmstat -a to a text file then I used the script below to parse the contents then write it to a .CSV file

Code Snippet:

Parse the source file (lmstat output file): srcfile

  1. Sub GetData(srcfile)
  2. Set f = fso.GetFile(srcfile)
  3. Set ts = f.OpenAsTextStream(ForReading, TristateUseDefault)
  4. Do While ts.AtEndOfStream <> True
  5. readResults = Trim(UCase(ts.ReadLine))
  6. If InStr(readResults, "/27000") Then
  7. mps = split(readResults, Chr(32))
  8. msg = mps(1) & "," & mps(3) &amp; "," & mps(4) &amp;amp; "," & mps(5) & mps(6) & mps(8) &amp;amp; " " & mps(9) &amp;amp; " " & mps(10)
  9. WriteToCSV msg, license_out
  10. End If
  11. Loop
  12. End Sub

Write to CSV function: oCsv(Output File), msg(parsed ReadLine results)


  1. Function WriteToCSV(oCsv,msg)
  2. If Not fso.FileExists(oCsv) Then fso.CreateTextFile(oCsv)
  3. Set f = fso.GetFile(oCsv)
  4. Set ts = f.OpenAsTextStream(ForAppending, TristateUseDefault)
  5. ts.Write msg & vbCrlf
  6. msg = ""
  7. ts.Close
  8. End Function
If at first you fail, call it version 1.0

Wednesday, September 12, 2007

Event Log

Event Log Manipulations:

1. Reading the Event Log
2. Clearing the Event Log
3. Creating backup of the Event Log

Code Snippet #1:

  1. strComputer = "."
  2. Set objWMIService = GetObject("winmgmts:" _
  3. & "{impersonationLevel=impersonate}!\\" _
  4. & strComputer & "\root\cimv2")
  5. Set colLoggedEvents = objWMIService.ExecQuery _
  6. ("Select * from Win32_NTLogEvent " _
  7. & "Where Logfile = 'System'")
  8. For Each objEvent in colLoggedEvents
  9. Wscript.Echo "Category: " &amp; objEvent.Category & VBNewLine _
  10. &amp;amp; "Computer Name: " & objEvent.ComputerName & VBNewLine _
  11. & "Event Code: " & objEvent.EventCode & VBNewLine _
  12. & "Message: " & objEvent.Message & VBNewLine _
  13. & "Record Number: " & objEvent.RecordNumber & VBNewLine _
  14. & "Source Name: " & objEvent.SourceName & VBNewLine _
  15. & "Time Written: " & objEvent.TimeWritten & VBNewLine _
  16. &amp;amp; "Event Type: " & objEvent.Type & VBNewLine _
  17. & "User: " & objEvent.User
  18. Next


Code Snippet #2:

  1. strComputer = "."
  2. Set objWMIService = GetObject("winmgmts:" _
  3. & "{impersonationLevel=impersonate,(Backup)}!\\" & _
  4. strComputer & "\root\cimv2")
  5. Set colLogFiles = objWMIService.ExecQuery _
  6. ("Select * from Win32_NTEventLogFile " _
  7. & "Where LogFileName='Application'")
  8. For Each objLogfile in colLogFiles
  9. objLogFile.ClearEventLog()
  10. WScript.Echo "Cleared application event log file"
  11. Next

Code Snippet #3:


  1. strComputer = "."
  2. Set objWMIService = GetObject("winmgmts:" _
  3. & "{impersonationLevel=impersonate,(Backup)}!\\" & _
  4. strComputer & "\root\cimv2")
  5. Set colLogFiles = objWMIService.ExecQuery _
  6. ("Select * from Win32_NTEventLogFile " _
  7. & "Where LogFileName='Application'")
  8. For Each objLogfile in colLogFiles
  9. errBackupLog = objLogFile.BackupEventLog( _
  10. "c:\scripts\application.evt")
  11. WScript.Echo "File saved as c:\scripts\applications.evt"
  12. Next
If at first you fail, call it version 1.0

Friday, July 13, 2007

MFCOM: Farm Session Count

Another day of Citrix Administration, a simple MFCOM script to view Active Farm Sessions.

Code Snippet:

  1. Const cMetaFrameWinFarmObject = 1
  2. Const MFSessionStateActive = 1
  3. Set theFarm = CreateObject("MetaFrameCOM.MetaFrameFarm")
  4. theFarm.Initialize(cMetaFrameWinFarmObject)
  5. intSessionCount = 0
  6. intActiveCount = 0
  7. For Each oSession In theFarm.Sessions
  8. intSessionCount = intSessionCount + 1
  9. If (oSession.SessionState = MFSessionStateActive) and (oSession.SessionName <> "Console") Then
  10. intActiveCount = intActiveCount + 1
  11. WScript.Echo vbcrlf & "*****************************"
  12. WScript.Echo "User Name: " & oSession.UserName
  13. WScript.Echo "IP Address: " & oSession.ClientAddress
  14. WScript.Echo "Server: " & oSession.ServerName
  15. WScript.Echo "Application: " & oSession.AppName
  16. WScript.Echo "Logon Time: " & oSession.ConnectedTime
  17. End If
  18. Next
  19. WScript.Echo "Total Session Count = " & intSessionCount & vbcrlf & _
  20. "Active Session Count = " & intActiveCount


If at first you fail, call it version 1.0

Monday, July 09, 2007

Merlin the great!

Imagine how amazed your users will be when they login to the domain and Merlin greets them...

You can call Merlin using Agent Control and make do the moves while you perform you login scripts in the background...

You can load information about the logged on user either using ADSI scripts or just by reading on the environment variable table...

Take note of the length of the messages or actions you throw at Merlin, you might need to make use of the Sleep method, otherwise the sentences or the animation will overlap...

Code Snippet:


  1. strAgentName = "Merlin"
  2. strAgentPath = "Msagent\Chars\" & strAgentName &amp;amp; ".acs"
  3. Set objAgent = CreateObject("Agent.Control.2")
  4. objAgent.Connected = True
  5. objAgent.Characters.Load strAgentName, strAgentPath
  6. Set merlin_d_great = objAgent.Characters.Character(strAgentName)
  7. With merlin_d_great
  8. .Show
  9. Set objRequest = .MoveTo(500,400)
  10. Set objRequest = .Play("Announce")
  11. Set objRequest = .Play("Explain")
  12. Set objRequest = .Speak("Hi ")
  13. Set objRequest = .Play("Read")
  14. wscript.sleep 2000
  15. Set objRequest = .Speak("Today is " & Now() & "...")
  16. Set objRequest = .Play("ReadContinued")
  17. wscript.sleep 2000
  18. Set objRequest = .Speak("and the time is " &amp; Time() & "...")
  19. wscript.sleep 2000
  20. Set objRequest = .Play("ReadReturn")
  21. wscript.sleep 2000
  22. Set objRequest = .MoveTo(750, 450)
  23. Set objRequest = .Play("Pleased")
  24. wscript.sleep 5000
  25. Set objRequest = .Speak("I will be back shortly...")
  26. wscript.sleep 5000
  27. Set objRequest = .Play("Wave")
  28. wscript.sleep 5000
  29. .Hide
  30. End With

Have a blast with Merlin, and oh... you can use other characters aswell...

If at first you fail, call it version 1.0

Thursday, June 28, 2007

HowTo: Add cmd.exe to right click context menu

If you want the command prompt to be available whenever you right click on objects on your desktop or explorer, you can opt to create the keys in the registry:

  • HKEY_CLASSES_ROOT\Folder\shell\MenuText\Command

Change the (Default) value to cmd.exe /k cd "%1"

Or you can script it!

Code Snippet:
  1. Const HKEY_CLASSES_ROOT = &H80000000
  2. Const HKEY_CURRENT_USER = &H80000001
  3. Dim WSHShell, objWMIService, strComputer, lcValue1
  4. strComputer = "."
  5. Set objWMIService = GetObject("winmgmts:\\" & strComputer &amp;amp; "\root\cimv2")
  6. Set objWSHShell = WScript.CreateObject("WScript.Shell")
  7. Set objRegObj = WScript.CreateObject("RegObj.Registry")
  8. objWSHShell.Popup "This will enable CMD with explorer options for the Current User"
  9. objWSHShell.RegWrite "HKCR\Folder\Shell\MenuText\Command\", "cmd.exe /k cd " & chr(34) & "%1" & chr(34)
  10. objWSHShell.RegWrite "HKCR\Folder\Shell\MenuText\", "Launch CMD"
  11. tmp = objWSHShell.RegRead("HKCR\Folder\Shell\MenuText\")
  12. objWSHShell.Popup ("Current Value: " + tmp)

If at first you fail, call it version 1.0

HowTo: Enable disabled services

If you want to automate startups on services that might be disabled by GPO, you can use Win32_Service class and change properties like the startup (Automatic\Manual\Disabled) or start\stop the service.

In my case, I prefer to use themes on my XP machine at work but our GPO disables them so our machines look like NT desktops... it sucks ain't it?

So to overcome this, I placed the script in my startup to enable the Themes and start the service.

Code Snippet:

  1. strComputer = "."
  2. Set objWMIService = GetObject("winmgmts:" _
  3. & "{impersonationLevel=impersonate}!\\" & _
  4. strComputer & "\root\cimv2")
  5. Set colServiceList = objWMIService.ExecQuery _
  6. ("Select * from Win32_Service where Name = 'Themes'")
  7. For Each objService in colServiceList
  8. 'Wscript.Echo objService.Name
  9. errReturnCode = objService.Change( , , , , "Automatic")
  10. If objService.State <> "Running" Then
  11. objService.StartService()
  12. Else
  13. objService.StopService()
  14. Wscript.Echo "Stopping..."
  15. Wscript.Sleep 5000
  16. objService.StartService()
  17. Wscript.Echo "Applying Themes"
  18. Wscript.Sleep 5000
  19. End If
  20. Next
Change line #6 value to any services that you want to enable (my case it's Name = 'Themes').

I prefer to use Cscript when executing any vbs scripts to avoid having to click on message prompts whenever you Echo.

If at first you fail, call it version 1.0

Bytes Converter Function

A simple function that converts Bytes to GB, MB or KB.

Code Snippet:

  1. Function SetBytes(Bytes,fKB)
  2. if fKB=True then Bytes = Bytes * 1024
  3. If Bytes >= 1073741824 Then
  4. SetBytes = FormatNumber((Bytes / 1024 / 1024 / 1024),2,,-1,-1) & " GB"
  5. ElseIf Bytes >= 1048576 Then
  6. SetBytes = FormatNumber((Bytes / 1024 / 1024),2,,-1,-1) & " MB"
  7. ElseIf Bytes >= 1024 Then
  8. SetBytes = FormatNumber((Bytes / 1024),2,,-1,-1) & " KB"
  9. ElseIf Bytes < 1024 Then
  10. SetBytes = Bytes & " Bytes"
  11. End If
  12. End Function

Usage: SetBytes(Size,true\false)

If at first you fail, call it version 1.0

Tuesday, June 26, 2007

Perl SMTP

IIS6 requires an Application Pool (like Sharepoint or Exchange) other than Default Application Pool for your Web or Virtual Directory for .Net mail sending via your webpage or else CDONTS library will throw Access Denied errors In Yer Face!

Well thanks to Perl's MIME-Lite and Net-SMTP you are likely to bypass this.

Code Snippet:

  1. use MIME::Lite;
  2. use Net::SMTP;
  3. # This debug flag will print debugging code to your browser,
  4. # depending on its value
  5. # Set this to 1 to send debug code to your browser.
  6. # Set it to 0 to turn it off.
  7. my $DEBUG = 1;
  8. if($DEBUG)
  9. {
  10. $| = 1;
  11. open(STDERR, ">&STDOUT");
  12. }
  13. # Set this variable to your smtp server name
  14. # my $ServerName = "YourSMTPServer";
  15. # Creat a new SMTP object
  16. #$smtp = Net::SMTP->new($ServerName, Debug => 1);
  17. # If you can't connect, don't proceed with the rest of the script
  18. #die "Couldn't connect to server" unless $smtp;
  19. ### Adjust Sender & Recepient email address
  20. my $from_address = '';
  21. my $to_address = '';
  22. my $cc_address = '';
  23. my $mime_type = 'multipart/mixed';
  24. ### Adjust subject and body message
  25. my $subject = '';
  26. my $message_body = "";
  27. ### Adjust the file to attach
  28. my $filename1 = '';
  29. my $recommended_filename1 = '';
  30. ### Creat the initial text of the message
  31. my $mime_msg = MIME::Lite->new(
  32. From => $from_address,
  33. To => $to_address,
  34. Cc => $cc_address,
  35. Subject => $subject,
  36. Type => $mime_type,
  37. )
  38. or die "Error creating MIME body: $!\n";
  39. ### Add the text message
  40. $mime_msg->attach(
  41. Type => 'TEXT',
  42. Data => $message_body
  43. ) or die "Error adding the text message part: $!\n";
  44. ### Attach the attachmnet file
  45. $mime_msg->attach(
  46. Type => 'application/txt',
  47. Path => $filename1,
  48. Filename => $recommended_filename1,
  49. Disposition => 'attachment',
  50. )
  51. or die "Error attaching test file: $!\n";
  52. my $message_body = $mime_msg->body_as_string();
  53. ### Set this variable to your smtp server name
  54. my $ServerName = "";
  55. ### Creat a new SMTP object
  56. $smtp = Net::SMTP->new($ServerName, Debug => 1);
  57. ### If you can't connect, don't proceed with the rest of the script
  58. die "Couldn't connect to server" unless $smtp;
  59. MIME::Lite->send('smtp', $ServerName, Timeout=>60);
  60. $mime_msg->send;
  61. ### Close the connection
  62. $smtp->quit();

If at first you fail, call it version 1.0

WMI Ping (Win32_PingStatus)

The code below is an example in how to use Win32_PingStatus class in WMI to check a remote machine's status on the network.

Code Snippet:

  1. Function PingHost(sTarget)
  2. Set cPingResults = GetObject("winmgmts:{impersonationLevel=impersonate}//" & _
  3. sHost & "/root/cimv2"). ExecQuery("SELECT * FROM Win32_PingStatus " & _
  4. "WHERE Address = '" + sTarget + "'")
  5. For Each oPingResult In cPingResults
  6. If oPingResult.StatusCode = 0 Then
  7. If LCase(sTarget) = oPingResult.ProtocolAddress Then
  8. WScript.Echo sTarget & " is responding"
  9. Else
  10. WScript.Echo sTarget & "(" & oPingResult.ProtocolAddress &amp; ") is responding"
  11. End If
  12. Wscript.Echo "Bytes = " & vbTab & oPingResult.BufferSize & _
  13. vbTab & "Time (ms) = " & vbTab & oPingResult.ResponseTime & _
  14. vbTab & "TTL (s) = " & vbTab & oPingResult.ResponseTimeToLive & _
  15. vbTab & "Hostname = " & vbTab & oPingResult.ProtocolAddressResolved
  16. Else
  17. WScript.Echo sTarget & " is not responding"
  18. WScript.Echo "Status code is " & oPingResult.StatusCode
  19. WScript.Echo "*********************************"
  20. End If
  21. Next
  22. End Function

If at first you fail, call it version 1.0

Monday, June 18, 2007

ADSI Kixtart UDF for Citrix login

Having a mixed mode environment gave us a lot of hassle when logging in to NT and querying group membership in AD... Specially in our case, we have nested OU's...

Ifmember.exe is useful for this problem but it does cause a slight delay in the login process and the users are complaining on the slow login session, some couldn't wait and cancels the connection... catastrophic experience ends up as a global complain... hmmm... some people are just impatient...

So to be able to execute an ADSI query through kix login script the function below can be inserted anywhere in the login script to perform InGroup query... or this can fully replace the built in InGroup function in kixtart.


Code Snippet:

  1. Function fnInGroupAD($sGroup,Optional $bComputer)
  2. Dim $objSys,$objTarget,$aMemberOf,$sMemberOf
  3. $objSys = CreateObject("ADSystemInfo")
  4. $objTarget = GetObject("LDAP://"+Iif($bComputer,$objSys.ComputerName,$objSys.UserName))
  5. $aMemberOf = $objTarget.GetEx("memberOf")
  6. For Each $sMemberOf in $aMemberOf
  7. If InStr($sMemberOf,"CN="+$sGroup+",")
  8. $fnInGroupAD = Not 0
  9. Exit
  10. EndIf
  11. Next
  12. $fnInGroupAD = NOT 1
  13. EndFunction

If at first you fail, call it version 1.0

Saturday, June 16, 2007

Windows Management Instrumentation Command-line (WMIC) tool

I previously posted an article regarding wbemtest that can be utilized in performing wmi query.

I recently visited M$oft and found an article on wmi command-line.

It was a good read and I was pleased to know that it provides you a simple command-line interface to Windows Management Instrumentation (WMI).

If you’ve never used WMIC, open a command prompt and type: WMIC

You should get a brief installation message followed by a WMIC prompt. You can type exit to return to the command prompt. WMIC has an interactive mode like NSLOOKUP or you can access it directly from the command line.

For example, run "wmic os get caption,csdversion", then you should get something like this:

Caption CSDVersion
Microsoft Windows XP Professional Service Pack 2


Type WMIC /? to view more info.

Note:
Use the /RECORD global switch to redirect WMIC output to a file.


If at first you fail, call it version 1.0

Friday, June 15, 2007

Keyword search trick

Searching your Blogs made easy...

A two function javascript that allows your visitors to query the web with any keywords from your page.

The first function checks if the item you double clicked on the document is a text then it passes it to the second function that appends the text value to your specified query string.

You can opt for the result to be displayed on the same page by using:

document.getElementById("<$id$>").innerHtml = ""

Or Pop up a new window:

window.open("<$variables$>")

Or redirect the page:

this.document.location=("" + "")

Code Snippet:

  1. function searchmySite() {
  2. if (navigator.appName!='Microsoft Internet Explorer') {
  3. var mykeywords = document.getSelection();
  4. omg(mykeywords);
  5. }
  6. else {
  7. var mykeywords = document.selection.createRange();
  8. if(document.selection.type == 'Text' && mykeywords .text>'') {
  9. document.selection.empty();
  10. omg(mykeywords.text);}
  11. }
  12. function omg(mykeywords ) {
  13. var searchStr = "<Put your search string here>"
  14. while (mykeywords.substr(mykeywords.length-1,1)==' ')
  15. mykeywords=mykeywords.substr(0,mykeywords.length-1)
  16. while (mykeywords.substr(0,1)==' ')
  17. mykeywords=mykeywords.substr(1)
  18. if (mykeywords) document.location=(searchStr + mykeywords);
  19. }
  20. }
  21. document.ondblclick=searchmySite


If at first you fail, call it version 1.0

Monday, June 11, 2007

Viral detection on multiple page loads

Aside from having too much page loads detected as being viral, too much query from a single point of origin is also detected as viral... now this is the time that when the search results will prompt you for message that this query format is detected as virus and will ask you to key in the confirmation code to confirm that it was a valid search query.

Anyway, since ie will just crash your machine when performing too much page load and queries, I have written another scriptlet that utilizes MSXML2.ServerXMLHTTP.4.0 instead, so no api calls are made to unreliable but wonderfully obedient ie.

Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP.4.0")

'::::: Set your proxy here, comment it if not required


xmlhttp.setProxy 2,"10.1.1.1:8080"

'::::: Open the url using http Get

xmlhttp.open "GET", purl, false

You may use the following as part of your query URL:

InURL:Index.Of?mp3 InText:Index.Of?mp3 InTitle:Index.Of?mp3 InURL:Top Keywords InText:Top Keywords InTitle:Top Keywords InURL:scripts InText:scripts InTitle:scripts InURL:niche InText:niche InTitle:niche InURL:adsense InText:adsense InTitle:adsense InURL:income InText:income InTitle:income InURL:3gp InText:3gp InTitle:3gp InURL:hotel InText:hotel InTitle:hotel InURL:travel InText:travel InTitle:travel InURL:medicine InText:medicine InTitle:medicine InURL:new InText:new InTitle:new InURL:best InText:best InTitle:best InURL:rare InText:rare InTitle:rare InURL:free InText:free InTitle:free InURL:finance InText:finance InTitle:finance InURL:movie InText:movie InTitle:movie InURL:download InText:download InTitle:download InURL:source InText:source InTitle:source InURL:game InText:game InTitle:game InURL:music InText:music InTitle:music InURL:audio InText:audio InTitle:audio InURL:film InText:film InTitle:film InURL:digital InText:digital InTitle:digital InURL:flight InText:flight InTitle:flight InURL:school


':::::: Make sure you define your Browser Agent or else queries will not be allowed and will prompt you for blocks of code that you might need to submit to rectify the malformed query.

xmlhttp.setRequestHeader "User-Agent","Microsoft Internet Explorer"


xmlhttp.send()


':::::: You can do anything with the search results, follow the links, blah
WScript.Echo xmlhttp.responseText

set xmlhttp = nothing


If at first you fail, call it version 1.0

Why Click it, If you can script it?

While 10,000 ecpm can earn you $0.40, one wonders how much it takes to actually earn...

A sequel to my previous post on my recent fascination on ecpm, page loads doesn't mean much if either the page loads are in millisecond and no links in the pages are clicked or the search option was utilized...

Adding an extra function allows the page loads to have a little extra sense as not only page loads will be peformed, but hey... even the search option is populated with a query string (maybe from an array, etc...)... and an added trick to perform the click to actually perform the query...

To fill up the input for the search utility:
.Document.All.tags("INPUT")("q").Value = searchKey

To Click the search button:
Set sButt = .Document.getElementsByTagName("INPUT")
For Each Butt in
sButt
If LCase(Butt.getAttribute("value")) = "search" Then
Butt.Click
Exit For
End If
Next

If this makes sense and actually is acceptable, why not click on all the links in the result page to add up to your ecpm queries...

Set xLinx = .Document.getElementsByTagName("a")
For Each Linx In xLinx
Linx.Click
Next

Note: Make sure that your site setting is to load the results in the same page, rather than popping up new windows... or else you will flood your screen with tons of ie windows... hahaha... (this, even if .visible=0)

A terminate process will help in getting rid of all the unwanted window popups:

Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("SELECT * FROM Win32_Process WHERE Name = 'Iexplore.exe'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next

Note: Do this after each page finishes loading after the click.

A draw back is that all your cookies and such are tracked, hence after numerous reloads and queries it might be detected as a viral activity, solution... clear your tracks...

First, get you cache path from your registry:
CachePath = WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Cache\Paths\Directory")

Then parse through the folders to delete all cache:
Set rootFolder = fso.GetFolder(CachePath)
Set subFolders = rootFolder.SubFolders
For Each folder in subFolders
fso.DeleteFolder(folder)
Next

You may reuse the same to delete the remaining files in the rootfolder. Just replace .SubFolders to .Files.

There you go...

As easy as it looks like and as cool as it may seem, this will not guarantee that you will actually earn anything based on pageloads and queries... ecpm is not as easily attainable although your site is now generating billions of pageloads\month...

And knowing how M$oft Internet Explorer sucks bigtime, you know that it will crash alot if you execute this like 10,000 times????

Anyway, I use Opera and Firefox 50/50... I only use IE to test my scripts to see how long it will take to crash it...

Good luck!

If your first attempt fails, call it version 1.0

Tuesday, June 05, 2007

1,000 eCPM can earn you only $0.01

Just a script that does nothing but loads a page repeatedly...
Hmmm... might be useful or not useful...
Can It be used to accumulate eCPM?

Totally up to you...

psURL = "Your desired url..."
psURL2 = "Second desired url..."
Dim x
Dim IE

x=0
Set IE = CreateObject("InternetExplorer.Application")

With IE
.menubar=0

.toolbar=0
.statusBar=0
.navigate psURL
.visible=0
.resizable=1
Do while .busy
Loop

Do While x < "desired amout of page loads"
WScript.Echo Now & " - Count Load: " & x
.navigate2 psURL
WScript.Echo Now & " - Loaded: " & psURL
Do while .busy
Loop

x =x + 1
WScript.Echo Now & " - 15sec sleep..."
WScript.Sleep(15000)
.navigate2 psURL2
WScript.Echo Now & " - Loaded: " & psURL2
Loop
End With




Thursday, May 24, 2007

SMTP using .NET Classes (Powershell)

A great Powershell code that you can use as a template for SMTP mail with authentication.

Easily extendible for Web development.


Scriptlet:
###############################################
$mail = new-object System.Net.Mail.MailMessage

#set sender email address
$mail.From = new-object System.Net.Mail.MailAddress("mymail@mydomain.com");

#set the recepient email address
$mail.To.Add("touser@domain.com");

#set the email subject
$mail.Subject = "";

#set the content

$mail.Body = "";

#send the message
$smtp = new-object System.Net.Mail.SmtpClient("mydomain.com");

#set the username and password properites on the SmtpClient for authentication
$smtp.Credentials = new-object System.Net.NetworkCredential("username", "password");

#send it
$smtp.Send(mail);


#Voila!
###############################################


Monday, May 21, 2007

Powershell Lynx Project

Those were the days of Lynx when you used to browse the web as text thru the console...

My previous blogs were about scripting with Yahoo api search services. Well, since blogging at work is not really encouraged, I have decided to create my powershell version of Lynx. Since I'm scripting most of the time due to adHoc script requests, my boss won't even realize that I'm actually blogging... hehehe...

For starters, a scriptlet that navigates IE:

$ie = New-Object -com InternetExplorer.Application
$ie.Visible=$true
$ie.MenuBar=$false
$ie.ToolBar=$false
$ie.StatusBar=$false
$ie.Navigate("http://26thgstreet.blogspot.com")


Visibility of IE can be set to false later after I finalized the function to get the HTMLDocument.Innertext and write it to the console.

I will aso have to create a function to accept console arguments to be posted to the HTMLDocument so that I can update my blogs...

Stay tuned for the script updates.