?
SolvedPrivate

VBS Script to Overwrite

Posted on 2013-01-10
21
Medium Priority
?
78 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 10
21 Comments
 
LVL 22

Expert Comment

by:mcsween
ID: 38763011
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
ID: 38763028
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 22

Expert Comment

by:mcsween
ID: 38763074
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
Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

 

Author Comment

by:SecAdminDan
ID: 38763102
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 22

Expert Comment

by:mcsween
ID: 38763184
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
ID: 38763273
Can you put it all together for me? Not that savvy with the scripting.

Thanks,

Dan
0
 
LVL 22

Expert Comment

by:mcsween
ID: 38763663
Just tack my code on to the end of yours.
0
 
LVL 22

Expert Comment

by:mcsween
ID: 38763669
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
ID: 38763711
Testing now.
0
 
LVL 22

Expert Comment

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

Open in new window

0
 

Author Comment

by:SecAdminDan
ID: 38763772
yep!
0
 

Author Comment

by:SecAdminDan
ID: 38763936
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 22

Expert Comment

by:mcsween
ID: 38763990
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
ID: 38764024
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
ID: 38764454
line 75 Char 80 Error: Expected end of statement

Please help
0
 

Author Comment

by:SecAdminDan
ID: 38764480
when running the script with the Sophos additions
0
 
LVL 22

Expert Comment

by:mcsween
ID: 38765576
line 75 Char 80 Error: Expected end of statement
Please post line 75
0
 

Author Comment

by:SecAdminDan
ID: 38767647
wshell.Run "put setup string for sophos here"
0
 
LVL 22

Expert Comment

by:mcsween
ID: 38767703
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
ID: 38767745
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 22

Accepted Solution

by:
mcsween earned 2000 total points
ID: 38767832
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Recovering from what the press called "the largest-ever cyber-attack", IT departments worldwide are discussing ways to defend against this in the future. In this process, many people are looking for immediate actions while, instead, they need to tho…
If you are IT support and need to work after hours to resolve customer issues then here are a few tips on how to handle after hours support
This Micro Tutorial will give you a basic overview of Windows Live Photo Gallery and show you various editing filters and touches to photos you can apply. This will be demonstrated using Windows Live Photo Gallery on Windows 7 operating system.
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…
Suggested Courses
Course of the Month7 days, 19 hours left to enroll

765 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