SolvedPrivate

VBS Script to Overwrite

Posted on 2013-01-10
21
73 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
The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

 

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 500 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

Do you have a plan for Continuity?

It's inevitable. People leave organizations creating a gap in your service. That's where Percona comes in.

See how Pepper.com relies on Percona to:
-Manage their database
-Guarantee data safety and protection
-Provide database expertise that is available for any situation

Question has a verified solution.

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

The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
Popular third-party chat platforms like Slack, Discord, and Telegram are just a few of the many new productivity applications that are being hijacked by cybercriminals to create command-and-control (C&C) communications infrastructures for their malw…
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.
The viewer will learn how to successfully download and install the SARDU utility on Windows 7, without downloading adware.

690 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