Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Examples of Window Scripting uses in VFP

Windows Scripting

Examples of Window Scripting uses in VFP

by  Mike Gagnon  Posted    (Edited  )
Here are a few examples of the different uses of Window Scripting.
This requires a Windows Scripting version 5.6 or more.
http://msdn.microsoft.com/library/default.asp?url=/downloads/list/webdev.asp.

How to get basic computer information
Code:
WshNetwork = CreateObject('WScript.Network')
lcMessage='Domain = ' + WshNetwork.UserDomain + CHR(13)
lcMessage=lcMessage+ 'Computer Name =' + WshNetwork.ComputerName+CHR(13)
lcMessage=lcMessage+ 'User Name = ' + WshNetwork.UserName
MESSAGEBOX(lcMessage)

How to get more information about your CD-ROM(s)
Code:
LOCAL strComputer
Local lcString
strComputer = '.'
lcString = '
objWMIService = Getobject('winmgmts:'+ 'impersonationLevel=impersonate}!\\' + strComputer + '\root\cimv2')
colItems = objWMIService.ExecQuery('Select * from Win32_CDROMDrive')
For Each objItem In colItems
	lcString = lcString + 'Description: '+objItem.Description+Chr(13)
	lcString = lcString + 'Name: '+objItem.Name+Chr(13)
	lcString = lcString + 'Manufacturer:' +objItem.manufacturer+Chr(13)
	lcString = lcString + 'Media type: '+objItem.mediaType+Chr(13)
	lcString = lcString + 'PNP Device ID:' + objItem.PNPDeviceID +Chr(13)
Next
Messagebox(lcString)

How to map a Network Drive
Code:
oNet = CreateObject('WScript.Network')    
oNet.MapNetworkDrive('I:','\\myserver\myFiles',.T.,'mike','password')

How to remove a Network connection
Code:
WshNetwork = CreateObject('WScript.Network')
WshNetwork.RemoveNetworkDrive('E')

How to add a printer connection
Code:
oNet = createobject('WScript.Network')
oNet.AddWindowsPrinterConnection('\\ServerName\PrinterName')

How to set a Windows default printer
Code:
oNet = CreateObject('WScript.Network')    
oNet.SetDefaultPrinter('\\ServerName\PrinterName')

How to check for available space on a given disk drive.
Code:
objFSO = CreateObject('Scripting.FileSystemObject')
objDrive = objFSO.GetDrive('C:')
MESSAGEBOX('Available space: ' + chr(13)+TRANSFORM(objDrive.AvailableSpace,'999,999,999,999,999'+' kb' ))

How to copy a file
Code:
FSO = CreateObject('Scripting.FileSystemObject')
FSO.CopyFile('c:\COMPlusLog.txt','c:\x\')

How to create a folder
Code:
fso = createobject('Scripting.FileSystemObject')
fldr = fso.CreateFolder('C:\MyTest')

How to delete a folder
Code:
fso =createobject('Scripting.FileSystemObject')
fldr = fso.DeleteFolder('C:\MyTest')

How to determine if a folder exists.
Code:
fso =createobject('Scripting.FileSystemObject')
? fso.FolderExists('C:\MyTest')

How to create a file
Code:
fso = CreateObject('Scripting.FileSystemObject')
f1 = fso.CreateTextFile('c:\testfile.txt', .T.)

How to create a file and write to it.
Code:
fso = CreateObject('Scripting.FileSystemObject')
tf = fso.CreateTextFile('c:\testfile.txt', .t.)
tf.WriteLine('Testing 1, 2, 3.') 
tf.WriteBlankLines(3) && Skip three lines
tf.Write ('This is a test.') 
tf.Close
MODIFY FILE 'c:\testfile.txt'

How to create a desktop icon (with path)
Code:
oShell = CreateObject('WScript.Shell')
DesktopPath = oShell.SpecialFolders('Desktop')
oURL = oShell.CreateShortcut(DesktopPath + '\MSDN Scripting.URL')
oURL = oShell.CreateShortcut(DesktopPath + '\MSDN Scripting.URL')
oURL.TargetPath = 'HTTP://MSDN.Microsoft.com/scripting/'
oURL.Save

How to create an entry in the Windows' registry
Code:
oSh = CreateObject('WScript.Shell')
key =  'HKEY_CURRENT_USER\'
oSh.RegWrite( key + 'WSHTest\','testkeydefault')
oSh.RegWrite(key + 'WSHTest\string1', 'testkeystring1')
oSh.RegWrite( key + 'WSHTest\string2', 'testkeystring2', 'REG_SZ')
oSh.RegWrite( key + 'WSHTest\string3', 'testkeystring3', 'REG_EXPAND_SZ')
oSh.RegWrite( key + 'WSHTest\int', 123, 'REG_DWORD')

How to remove a Registry Key
Code:
oSh = CreateObject('WScript.Shell')
oSh.RegDelete('HKCU\\Software\\ACME\\FortuneTeller\\MindReader')
oSh.RegDelete('HKCU\\Software\\ACME\\FortuneTeller\\')
oSh.RegDelete ('HKCU\\Software\\ACME\\')

A replacement to the default VFP messagebox
Code:
WshShell = Createobject('WScript.Shell')
BtnCode = WshShell.Popup('Do you feel alright?', 7, 'Answer This Question:', 4 + 32)
Do Case
Case BtnCode=6
	WSHSHELL.Popup('Glad to hear you feel alright.')
Case BtnCode=7
	WSHSHELL.Popup('Hope you're feeling better soon.')
Endcase

Create a desktop shortcut
Code:
Shell = CreateObject('WScript.Shell')
DesktopPath = Shell.SpecialFolders('Desktop')
link = Shell.CreateShortcut(DesktopPath+'\test.lnk')
link.Arguments = '1 2 3'
link.Description = 'test shortcut'
link.HotKey = 'CTRL+ALT+SHIFT+X'
link.IconLocation = 'app.exe,1'
link.TargetPath = 'c:\blah\app.exe'
link.WindowStyle = 3
link.WorkingDirectory = 'c:\blah'
link.Save()

Use a Window XP fileOpen dialog (Only on Windows XP) that allows multiple selection.
Code:
oDlg= Createobject('userAccounts.commonDialog')
oDlg.flags= '&h1a04'
oDlg.Filter= 'All Files|*.*|'+ 'Text and Batch Files|*.txt;*.bat'
oDlg.filterIndex= 2
oDlg.initialDir='C:\'
qSln= oDlg.showOpen
If qSln
	Messagebox(oDlg.fileName)
Else
	Messagebox('Dialog cancelled.')
Endif

Demonstrates a method for converting the Universal Time Coordinate (UTC) values used by WMI to standard date-time values. This example returns the datetime in the installation of the Operating system.
Code:
strComputer = '.'
objWMIService = Getobject('winmgmts:\\' + strComputer + '\root\cimv2')
objOS = objWMIService.ExecQuery('Select * from Win32_OperatingSystem')
For Each strOS In objOS
	dtmInstallDate = strOS.InstallDate
	MESSAGEBOX(TRANSFORM(WMIDateStringToDate(dtmInstallDate)))
Next
Function WMIDateStringToDate(dtmInstallDate)
PRIVATE ldRetVal
RETURN CTOT(SUBSTR(dtmInstallDate, 5, 2) + '/' + SUBSTR(dtmInstallDate, 7, 2) + '/' + Left(dtmInstallDate, 4) + ' ' +;
 SUBSTR(dtmInstallDate, 9, 2) + ':' + SUBSTR(dtmInstallDate, 11, 2) + ':' + SUBSTR(dtmInstallDate,13, 2))
ENDFUNC

Retrieving the local system time including day-of-the week,quarter, week-of-the-month
Code:
strComputer = '.'
lcStr='
objWMIService = Getobject('winmgmts:\\' + strComputer + '\root\cimv2')
colItems = objWMIService.ExecQuery('Select * from Win32_LocalTime')
Set Step On
For Each objItem In colItems
	lcStr=lcStr+'Year: ' + Transform(objItem.Year)+Chr(13)
	lcStr=lcStr+'Month: ' + Transform(objItem.Month)+Chr(13)
	lcStr=lcStr+'Day: ' + Transform(objItem.Day)+Chr(13)
	lcStr=lcStr+'Hour: ' + Transform(objItem.Hour)+Chr(13)
	lcStr=lcStr+'Minute: ' + Transform(objItem.Minute)+Chr(13)
	lcStr=lcStr+'Second: ' +Transform( objItem.Second)+Chr(13)
	lcStr=lcStr+'Day Of the Week: ' + Transform(objItem.Dayofweek)+Chr(13)
	lcStr=lcStr+ 'Week In the Month: ' +Transf( objItem.WeekInMonth)+Chr(13)
	lcStr=lcStr+'Quarter: ' +Transform( objItem.Quarter)
Next
Messagebox(lcStr)

Run a schedule task now, rather than wait for the scheduled time.
Code:
ssfCONTROLS = 3  && Control Panel's Schedule Tasks folder
sJobName = 'fta'  && Name of the task to run
sRunVerb = 'R&un'  && Executing command
sEndVerb = '&End Task'  && Cancelling command
shellApp = Createobject('shell.application')
oControlPanel = shellApp.Namespace(ssfCONTROLS) && Schedule Tasks folder
oST = '
For Each folderitem In oControlPanel.items  && Loop though the items in the Control Panel items
	If folderitem.Name  = 'Scheduled Tasks'
		oST = folderitem.getfolder() && Found it
		Exit
	Endif
Next
If Vartype(oST) != 'O'
	Messagebox('Couldn't find 'TS' folder')
Endif
oJob = '
For Each folderitem In oST.items  && Loop through the different scheduled tasks until we fiind it.
	If   Lower(folderitem.Name)  = Lower(sJobName) 
		oJob = folderitem  && Found it
		Exit
	Endif
Next
If Vartype(oJob) !='O'
	Messagebox( 'Couldn't find ' + sJobName + ' item')
Else
	bEnabled = .T.
	oRunVerb = '
	oEndVerb = '
	s = 'Verbs: ' + Chr(13)
	For Each Verb In oJob.verbs  && Loop through the different commands in the scheduled task until we find right one.
		s = s + Chr(13) + Verb.Name
		If Verb.Name = sRunVerb
			oRunVerb = Verb
			bEnabled = .F.
		Endif
		If Verb.Name = sEndVerb
			oEndVerb = Verb
		Endif
	Next
	If bEnabled
		oJob.InvokeVerb(oEndVerb)  && Cancel the task
	Else
		Wait Window Nowait 'executing job'
		oJob.InvokeVerb(sRunVerb)  && Run the task!
	Endif
Endif

Funtion to enumerate running processes.
Code:
FUNCTION enumerateProcess
lcComputer = '.'
loWMIService = Getobject('winmgmts:' ;
    + '{impersonationLevel=impersonate}!\\' + lcComputer + '\root\cimv2')
colProcessList = loWMIService.ExecQuery ;
    ('Select * from Win32_Process')
Create Cursor Process (Name c(20),Id i,Thread i,pagefile i,pagefault i,workingset c(20))
Index On Name Tag Name
For Each loProcess In colProcessList
    Insert Into Process (Name,Id,Thread,pagefile,pagefault,workingset);
        VALUES (loProcess.Name,loProcess.ProcessID,loProcess.ThreadCount,loProcess.PageFileUsage,;
        loProcess.pagefaults,loProcess.WorkingSetSize)
Next
BROWSE normal
Function to terminate all instances of a running process.
Code:
FUNCTION terminateProcess(lcProcess)
lcComputer = '.'
loWMIService = Getobject('winmgmts:' ;
    + '{impersonationLevel=impersonate}!\\' + lcComputer + '\root\cimv2')
colProcessList = loWMIService.ExecQuery ;
    ('Select * from Win32_Process')
For Each loProcess In colProcessList
   IF UPPER(loProcess.name) = lcProcess
     loProcess.terminate()
   endif
Next

How to force the Addprinter applet from the control Panel
Code:
oShell = CreateObject("WScript.Shell")
oShell.Run("rundll32.exe shell32.dll,SHHelpShortcuts_RunDLL AddPrinter")

How to access the Control Panel applets
Code:
oShell = CreateObject('WScript.Shell')
oShell.Run('Control.exe Sysdm.cpl,,0') [color green]&& System Propeties general Tab.[/color]
oShell.Run('Control.exe Sysdm.cpl,,1')[color green] && System Properties - Computer name tab.[/color]
oShell.Run('Control.exe Sysdm.cpl,,2') [color green]&& System properties - Hardware tab.[/color]
oShell.Run('Control.exe Sysdm.cpl,,3') [color green]&& System properties - Advanced tab.[/color]
oShell.Run('Control.exe Sysdm.cpl,,4') [color green]&& System properties - System Restore tab (ME and XP).[/color]
oShell.Run('Control.exe Sysdm.cpl,,5') [color green]&& System properties - Automatic Updates tab.[/color]
oShell.Run('Control.exe Sysdm.cpl,,6') [color green]&& System properties - Remote tab.[/color]

The parameters apply to the different applets. The last parameter refers to the tab that has the focus.

Code:
oShell.Run('Control.exe Access.cpl,,1') [color green] && Accessibilty Options applet focused on tab 1[/color]
oShell.Run('Control.exe AppWiz.cpl,,1') [color green] && Add/Remove Programs applet focused on tab 1[/color]
oShell.Run('Control.exe Desk.cpl,,1') [color green] && Display Properties applet focused on tab 1[/color]

The rest of the Applets works in the same principle.
InetCpl.cpl Internet Options
Intl.cpl Country
Joy.cpl Joystick
mlcfg32.cpl Mail account setup
Main.cpl Mouse, keyboard, printers and fonts
MmSys.cpl Multimedia and sounds
Modem.cpl Modem
OdbcCp32.cpl ODBC data source
Password.cpl Password
Ports.cpl Ports
PowerCfg.cpl Power Management
PrefsCpl.cpl Real Player G2
Ras.cpl Remote Access
SrvMgr.cpl Server
SysDm.cpl System
Telephon.cpl Telephony
Themes.cpl Desktop themes
TimeDate.cpl Date/Time
TweakUI.cpl TweakUI
Ups.cpl Spare power supply


Mike Gagnon
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top