SolvedPrivate

VBS Script to Overwrite

Posted on 2013-01-10
21
58 Views
Last Modified: 2016-02-25
I would like for this script below to overright any existing file it creates. It is a startup script and creates multiple file based on "Date Modified" I want to get rid of this so every file is most recent and a set number of files can be expected. I would also like to add the ability to install Sophos antivirus if it is not found.

RobSampson:
http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_27983948.html



On Error Resume Next

Set objNetwork = CreateObject("WScript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strOutputFile = "\\server\share\" & objNetwork.UserDomain & "_" & objNetwork.ComputerName & ".txt"

Const adVarChar = 200
Const MaxCharacters = 255
      
Set rstAppList = CreateObject("ADOR.Recordset")
rstAppList.Fields.Append "AppName", adVarChar, MaxCharacters
rstAppList.Fields.Append "Version", adVarChar, MaxCharacters
rstAppList.Open

Const strComputer = "."
Const HKLM        = &H80000002

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

strArchitecture = GetOSArchitecture(objWMIService)
strUsername = GetCurrentUsername(objWMIService)
strIPAddress = GetIPAddress(objWMIService)

If strArchitecture = 32 Then
      strKeyPath  = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
Else
      strKeyPath  = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
End If

Dim oReg, arrSubKeys, strProduct, strDisplayName, strVersion

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

Set objOutput = objFSO.CreateTextFile(strOutputFile, True)
objOutput.WriteLine "Username: " & strUsername
objOutput.WriteLine "IP Address: " & strIPAddress

arrProducts = Array("Sophos", "GFI", "Safend", "MBSA")

' Enumerate the subkeys of the Uninstall key
oReg.EnumKey HKLM, strKeyPath, arrSubKeys
For Each strProduct In arrSubKeys
      ' Get the product's display name
      oReg.GetStringValue HKLM, strKeyPath & "\" & strProduct, "DisplayName", strDisplayName
      ' Process only products whose name contain 'Sophos'
      For Each strSearch In arrProducts
            If InStr(1, strDisplayName, strSearch, vbTextCompare) > 0 Then
                  ' Get the product's display version
                  oReg.GetStringValue HKLM, strKeyPath & "\" & strProduct, "DisplayVersion", strVersion
                rstAppList.AddNew
                rstAppList("AppName") = strDisplayName
                rstAppList("Version") = strVersion
                rstAppList.Update
            End If
      Next
Next

rstAppList.Sort = "AppName"

rstAppList.MoveFirst
Do Until rstAppList.EOF
      objOutput.WriteLine rstAppList("AppName") & vbTab & rstAppList("Version")
    rstAppList.MoveNext
Loop

rstAppList.Close

objOutput.Close

Function GetOSArchitecture(objRemote)
      ' TITLE: GetOSArchitecture
      ' DESCRIPTION: This function will use a WMI query to determine the system
      '      architecture of the target computer
      ' INPUT:
      '      objRemote must be an object that is bound to the WMI service on the target machine
      '      Make a call such as Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
      '      and pass objWMI to this function
      ' OUTPUT:
      '      A string value being 32 or 64
      Set colOS = objRemote.ExecQuery("SELECT OSArchitecture FROM Win32_OperatingSystem",, 48)
    For Each objOS In colOS
        intAddressWidth = objOS.OSArchitecture
    Next
    If intAddressWidth = "32-bit" Then intAddressWidth = 32
    If intAddressWidth = "64-bit" Then intAddressWidth = 64
    GetOSArchitecture = intAddressWidth
End Function

Function GetCurrentUsername(objRemote)
      Set colComputer = objWMIService.ExecQuery("Select UserName from Win32_ComputerSystem",, 48)
      strLoggedInUser = ""
      For Each objComputer In colComputer
            strLoggedInUser = objComputer.UserName
      Next
      GetCurrentUsername = strLoggedInUser
End Function

Function GetIPAddress(objRemote)
      Set colComputerIP = objWMIService.ExecQuery("Select IPAddress from Win32_NetworkAdapterConfiguration")
      strIPDetails = ""
      For Each IPConfig In colComputerIP
            If Not IsNull(IPConfig.IPAddress) Then
              For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)
                    If IPConfig.IPAddress(intIPCount) <> "0.0.0.0" And InStr(IPConfig.IPAddress(intIPCount), ":") = 0 Then
                              strIPDetails = strIPDetails & IPConfig.IPAddress(intIPCount) & vbTab
                        End If
                  Next
            End If
      Next
      GetIPAddress = strIPDetails
End Function
0
Comment
Question by:SecAdminDan
  • 11
  • 10
21 Comments
 
LVL 21

Expert Comment

by:mcsween
Comment Utility
It looks like this script will already overwrite any existing files with the same name in the directory.

The true on the end of this line tells it to overwrite if the file exists.
Set objOutput = objFSO.CreateTextFile(strOutputFile, True)

Open in new window


It looks like the file will be called DOMAINNAME_COMPUTERNAME.txt
strOutputFile = "\\server\share\" & objNetwork.UserDomain & "_" & objNetwork.ComputerName & ".txt"

Open in new window

0
 

Author Comment

by:SecAdminDan
Comment Utility
Ok If i run this is creates a file, then if I run it again on the same system it creates the same file with a different time stamp.

Could we add the sophos ability?

Dan
0
 
LVL 21

Expert Comment

by:mcsween
Comment Utility
I don't see how it would be able to create 2 files in the same folder with the same name.  Windows won't allow this...
0
 

Author Comment

by:SecAdminDan
Comment Utility
I am running it through a test OU. I will examine it closely.

Could we add the sophos ability?

32bit - “C:\Program Files (x86)\Sophos\Sophos Anti-Virus\SavService.exe" < /l*v c:\AVStatus.txt
64bit - “C:\Program Files\Sophos\Sophos Anti-Virus\SavService.exe” /l*v < c:\AVStatus.txt
\\security\SophosUpdate\CIDs\S000\SAVSCFXP\setup.exe -s \ -user "domain\username" -pwd "password" -mng yes - >c:\Sophos ( instll successful or failure)

So after the script check the registry for Sphos if these paths dont exist Install Sophos

Possible?

Dan
0
 
LVL 21

Expert Comment

by:mcsween
Comment Utility
Dim wshell
Set wshell = CreateObject("WScript.Shell")
If objFSO.FolderExists("C:\Program Files (x86)\") = True Then
	If objFSO.FileExists("C:\Program Files (x86)\Sophos\Sophos Anti-Virus\SavService.exe") = False Then
		wshell.Run "put setup string for sophos here"
	End If
End If
If objFSO.FolderExists("C:\Program Files\") = True Then
	If objFSO.FileExists("C:\Program Files\Sophos\Sophos Anti-Virus\SavService.exe") = False Then
		wshell.Run "put setup string for sophos here"
	End If
End If

Open in new window

0
 

Author Comment

by:SecAdminDan
Comment Utility
Can you put it all together for me? Not that savvy with the scripting.

Thanks,

Dan
0
 
LVL 21

Expert Comment

by:mcsween
Comment Utility
Just tack my code on to the end of yours.
0
 
LVL 21

Expert Comment

by:mcsween
Comment Utility
On Error Resume Next

Set objNetwork = CreateObject("WScript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strOutputFile = "\\server\share\" & objNetwork.UserDomain & "_" & objNetwork.ComputerName & ".txt"

Const adVarChar = 200
Const MaxCharacters = 255
      
Set rstAppList = CreateObject("ADOR.Recordset")
rstAppList.Fields.Append "AppName", adVarChar, MaxCharacters
rstAppList.Fields.Append "Version", adVarChar, MaxCharacters
rstAppList.Open

Const strComputer = "."
Const HKLM        = &H80000002

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

strArchitecture = GetOSArchitecture(objWMIService)
strUsername = GetCurrentUsername(objWMIService)
strIPAddress = GetIPAddress(objWMIService)

If strArchitecture = 32 Then
      strKeyPath  = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
Else
      strKeyPath  = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
End If

Dim oReg, arrSubKeys, strProduct, strDisplayName, strVersion

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

Set objOutput = objFSO.CreateTextFile(strOutputFile, True)
objOutput.WriteLine "Username: " & strUsername
objOutput.WriteLine "IP Address: " & strIPAddress

arrProducts = Array("Sophos", "GFI", "Safend", "MBSA")

' Enumerate the subkeys of the Uninstall key
oReg.EnumKey HKLM, strKeyPath, arrSubKeys
For Each strProduct In arrSubKeys
      ' Get the product's display name
      oReg.GetStringValue HKLM, strKeyPath & "\" & strProduct, "DisplayName", strDisplayName
      ' Process only products whose name contain 'Sophos'
      For Each strSearch In arrProducts
            If InStr(1, strDisplayName, strSearch, vbTextCompare) > 0 Then
                  ' Get the product's display version
                  oReg.GetStringValue HKLM, strKeyPath & "\" & strProduct, "DisplayVersion", strVersion
                rstAppList.AddNew
                rstAppList("AppName") = strDisplayName
                rstAppList("Version") = strVersion
                rstAppList.Update
            End If
      Next
Next

rstAppList.Sort = "AppName"

rstAppList.MoveFirst
Do Until rstAppList.EOF
      objOutput.WriteLine rstAppList("AppName") & vbTab & rstAppList("Version")
    rstAppList.MoveNext
Loop

rstAppList.Close

objOutput.Close

Dim wshell
Set wshell = CreateObject("WScript.Shell")
If objFSO.FolderExists("C:\Program Files (x86)\") = True Then
	If objFSO.FileExists("C:\Program Files (x86)\Sophos\Sophos Anti-Virus\SavService.exe") = False Then
		wshell.Run "put setup string for sophos here"
	End If
End If
If objFSO.FolderExists("C:\Program Files\") = True Then
	If objFSO.FileExists("C:\Program Files\Sophos\Sophos Anti-Virus\SavService.exe") = False Then
		wshell.Run "put setup string for sophos here"
	End If
End If

Function GetOSArchitecture(objRemote)
      ' TITLE: GetOSArchitecture
      ' DESCRIPTION: This function will use a WMI query to determine the system
      '      architecture of the target computer
      ' INPUT:
      '      objRemote must be an object that is bound to the WMI service on the target machine
      '      Make a call such as Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
      '      and pass objWMI to this function
      ' OUTPUT:
      '      A string value being 32 or 64
      Set colOS = objRemote.ExecQuery("SELECT OSArchitecture FROM Win32_OperatingSystem",, 48) 
    For Each objOS In colOS 
        intAddressWidth = objOS.OSArchitecture
    Next
    If intAddressWidth = "32-bit" Then intAddressWidth = 32
    If intAddressWidth = "64-bit" Then intAddressWidth = 64
    GetOSArchitecture = intAddressWidth
End Function

Function GetCurrentUsername(objRemote)
      Set colComputer = objWMIService.ExecQuery("Select UserName from Win32_ComputerSystem",, 48)
      strLoggedInUser = ""
      For Each objComputer In colComputer
            strLoggedInUser = objComputer.UserName
      Next
      GetCurrentUsername = strLoggedInUser
End Function

Function GetIPAddress(objRemote)
      Set colComputerIP = objWMIService.ExecQuery("Select IPAddress from Win32_NetworkAdapterConfiguration")
      strIPDetails = ""
      For Each IPConfig In colComputerIP
            If Not IsNull(IPConfig.IPAddress) Then 
              For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)
                    If IPConfig.IPAddress(intIPCount) <> "0.0.0.0" And InStr(IPConfig.IPAddress(intIPCount), ":") = 0 Then
                              strIPDetails = strIPDetails & IPConfig.IPAddress(intIPCount) & vbTab
                        End If
                  Next
            End If
      Next
      GetIPAddress = strIPDetails
End Function

Open in new window

0
 

Author Comment

by:SecAdminDan
Comment Utility
Testing now.
0
 
LVL 21

Expert Comment

by:mcsween
Comment Utility
Dont forget to modify the two lines that read
wshell.Run "put setup string for sophos here"

Open in new window

0
Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

 

Author Comment

by:SecAdminDan
Comment Utility
yep!
0
 

Author Comment

by:SecAdminDan
Comment Utility
Works great! Exactly what I need! Can we please add support for Safend installations as well?

I would like to check:

32 bit: C:\Program Files\Safend\Data Protection Agent
64 bit: c:\\Program Files (x86)\Safend\Data Protection Agent
Install from here: \\server\Safend Client 3.4\DataProtectionAgent.en-US.msi

But ignore if is found skip it and no install
\Program Files\Safend\Safend Protector Client
\Program Files (x86)\Safend\Safend Protector Client

I am trying to weed out the old install (the skip part) and install new client.

Make sense?
0
 
LVL 21

Expert Comment

by:mcsween
Comment Utility
My script is just checking to see if program files (x86) folder is there and checking for the program file there if it does; otherwise it checks c:\program files for the file.  All you have to do is modify the lines that look like this:
If objFSO.FileExists("C:\Program Files\Sophos\Sophos Anti-Virus\SavService.exe") = False Then

Open in new window

0
 

Author Comment

by:SecAdminDan
Comment Utility
So i would double up this: Like so....

If objFSO.FolderExists("C:\Program Files (x86)\") = True Then
      If objFSO.FileExists("C:\Program Files (x86)\Sophos\Sophos Anti-Virus\SavService.exe") = False Then
            wshell.Run "put setup string for sophos here"
      End If
End If
If objFSO.FolderExists("C:\Program Files\") = True Then
      If objFSO.FileExists("C:\Program Files\Sophos\Sophos Anti-Virus\SavService.exe") = False Then
            wshell.Run "put setup string for sophos here"
      End If



If objFSO.FolderExists("C:\Program Files (x86)\") = True Then
      If objFSO.FileExists("C:\Program Files (x86)\safend\Data Protection Agent\Dataprotectionagent.exe") = False Then
            wshell.Run "put setup string for safend here"
      End If
End If
If objFSO.FolderExists("C:\Program Files\") = True Then
      If objFSO.FileExists("C:\Program Files\safend\Data Protection Agent\Dataprotectionagent.exe") = False Then
            wshell.Run "put setup string for safend here"
      End If



How can I make sure it doesnt try to install over the old client. I have to remove these manually, no other way.

So the script runs, and does its duties. Looking for Sophos if no then install. Looking for two diffent versions of Safend (by path) I want the script to find the
\Program Files\Safend\Safend Protector Client
\Program Files (x86)\Safend\Safend Protector Client
and ignore if present. But if nothing (no path) is found install Safend.
0
 

Author Comment

by:SecAdminDan
Comment Utility
line 75 Char 80 Error: Expected end of statement

Please help
0
 

Author Comment

by:SecAdminDan
Comment Utility
when running the script with the Sophos additions
0
 
LVL 21

Expert Comment

by:mcsween
Comment Utility
line 75 Char 80 Error: Expected end of statement
Please post line 75
0
 

Author Comment

by:SecAdminDan
Comment Utility
wshell.Run "put setup string for sophos here"
0
 
LVL 21

Expert Comment

by:mcsween
Comment Utility
You have to replace "put setup string for sophos here" with the actual command line to install sophos silently.  It should start with cmd /c then the path to setup.exe then the command line switches.  Something like below only with your custom settings.

wshell.run "cmd /c \\someserver\someshare\sophos\setup.exe -mng yes -scf -patch http://yourmanagementserver.local -crt R -updp \\sophossever\updateshare\CID -s"

Open in new window

More info on Sophos command line switches here: http://www.sophos.com/en-us/support/knowledgebase/12570.aspx
0
 

Author Comment

by:SecAdminDan
Comment Utility
This is my exact line sorry about that:

wshell.Run "\\security\SophosUpdate\CIDs\S000\SAVSCFXP\setup.exe -s \ -user "domain\username" -pwd "xxxxxxxx" -mng yes - >c:\Sophoslog.txt"

It looks like I am missing the cmd /c and defining nointeractive -ni.
0
 
LVL 21

Accepted Solution

by:
mcsween earned 500 total points
Comment Utility
Passing double quotes to the command line can be a bit tricky in VBScript.

wshell.run "cmd /c \\security\SophosUpdate\CIDs\S000\SAVSCFXP\setup.exe -s -user " & """" & "domain\username" & """" & " -pwd " & """" & "xxxxxxxx" & """" & " -mng yes  > c:\Sophoslog.txt"

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

How can you create a game plan that lets you focus on special projects instead of running from cubicle to cubicle every day and feeling like you’ve accomplished nothing? Try these strategies for prioritizing your tasks, offloading what you can, and …
Our Group Policy work started with Small Business Server in 2000. Microsoft gave us an excellent OU and GPO model in subsequent SBS editions that utilized WMI filters, OU linking, and VBS scripts. These are some of experiences plus our spending a lo…
Windows 8 comes with a dramatically different user interface known as Metro. Notably missing from the new interface is a Start button and Start Menu. Many users do not like it, much preferring the interface of earlier versions — Windows 7, Windows X…
This Micro Tutorial will teach you how to change your appearance and customize your Windows 7 interface to your unique preference. This will be demonstrated using Windows 7 operating system.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now