Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Vb Script, to copy particular folder with subdirectories from multiple servers to a common location with unique server names as their respective folders

Posted on 2008-06-15
Medium Priority
Last Modified: 2013-12-09
i have to copy PKI folder from Remote servers, i hav admin access, so when do \\servername i can copy the contents of VPHOME folder.  For ur easy understanding, i can tell u, PKI is a certification file of Symantec Antivirus Servers, each server is having a share named VPHOME, inside VPHOME share, u may find, Grc.dat file, and a folder name PKI, inside PKI u have subdirectories and files.

d:                                                        "The backup files of remote server should be in D drive of the master server, im running the code from"
cd NewPKI                                            "Folder to backup the PKI contents"
cd ServerGroupName                        "ServerName to be replaced everytime it runs"
md ServerName                                    "Need to create a directory in the name of the server it replaces"
cd ServerName                                            "Changing the directory to the respective servername folder for backup of PKI folder"
copy \\ServerName\VPHOME\grc.dat        " in the server share, u have VPHOME as share, from which i hav to backup GRC.DAT file alone"
Xcopy \\ServerName\VPHOME\pki /E /Y            " Inside PKI folder, u may have 4 subdirectories, several files of some 10 to 20 Kb files"

In the above code, the ServerName need to be replaced with the name of the servers in the list of CSV / Txt  file.

in the CSV/txt file, u may have the server names like this.

S.No.        ServerName        ServerGroupName

1                JSBXXX                ASIA
2.             HSBDYU                ASIA
3.            FFSSLF                ASIA
4.            DFLSSF                ASIA

After we run a script, the folder map will b like this

going further, the servergroupname also changes, like consider it as location based. such as America. We have to create seperate folder for America as     d:\NewPKI\America\....., the servernames will b different in that location.

P.S. I have gone thru this http://www.experts-exchange.com/Programming/Languages/Scripting/Shell/Batch/Q_22612350.html?sfQueryTermInfo=1+copi+file+from+remot+script+server thread, but it only concentrates on Log files, so i dont know how to convert them for my PKI folders in VB script.

pls help me; My mail id shankjai@yahoo.com
cd NewPKI                                            "Folder to backup the PKI contents"
cd ServerGroupName                        "ServerName to be replaced everytime it runs"
md ServerName                                    "Need to create a directory in the name of the server it replaces"
cd ServerName                                            "Changing the directory to the respective servername folder for backup of PKI folder"
copy \\ServerName\VPHOME\grc.dat        " in the server share, u have VPHOME as share, from which i hav to backup GRC.DAT file alone"
Xcopy \\ServerName\VPHOME\pki /E /Y            " Inside PKI folder, u may have 4 subdirectories, several files of some 10 to 20 Kb files"

Open in new window

Question by:shankjai
  • 5
  • 2
LVL 25

Expert Comment

by:Ron Malmstead
ID: 21930369
I don't see why this has to be vb script... any particular reason you don't want to use xcopy ?

example ...
xcopy "\\JSBXXX\vphome\*.*" "d:\NewPKI\asia\JSBXXX\vphome\*.*" /D /E /I /R /Y

also, have you considered creating a single batch file to be run as a scheduled task from all servers ?..as opposed to maintaining a script when you have to add and remove servers...

first you set a global environment variable on every server...using this code as a startup script...
This creates a permanent system variable you can use to identify the subnet a server is on, and use it as a variable.

example batch script to run on any remote server..

IF %NETID% == 172.16.9 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\ASIA\%computername%\NewPKI\*.*" /D /E /I /R /Y
IF %NETID% == 172.16.10 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\AMERICA\%computername%\NewPKI\*.*" /D /E /I /R /Y
IF %NETID% == 172.16.11 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\MEXICO\%computername%\NewPKI\*.*" /D /E /I /R /Y

let me know what you think...
LVL 25

Expert Comment

by:Ron Malmstead
ID: 21930379

IF %NETID% == 172.16.9 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\ASIA\%computername%\NewPKI\*.*" /D /E /I /R /Y
IF %NETID% == 172.16.10 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\AMERICA\%computername%\NewPKI\*.*" /D /E /I /R /Y
IF %NETID% == 172.16.11 xcopy "\\%computername%\VPhome\*.*" "\\pkiserver\vphome\MEXICO\%computername%\NewPKI\*.*" /D /E /I /R /Y

Open in new window


Author Comment

ID: 21954044
Option Explicit

Dim strFile, objSh , errorFile, objErr1
Dim  strSrc1, strSrc2, strDest, bolFlag

'Enter the Server name into the Computers.txt file, one entry per line
strFile = "SymantecPSList.txt"

Dim objFSO, objTS, strComputer, objOuts, objFolder, objErr, objFile, i,strLine, objPing, objStatus,colComputer, oComputer
Dim iDR, sName

'specify filename and folder path for file/folder to be copied

strSrc2 = "\vphome\grc.dat"

'specify target destination
strDest="\\mainserver\Final\New Folder\ "

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSh = CreateObject("WScript.Shell")

'Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("SymantecPSList.txt", ForReading)
Const ForReading = 1
Const ForAppending = 8
Dim arrFileLines()
i = 0
Do Until objFile.AtEndOfStream
    Redim Preserve arrFileLines(i)
    arrFileLines(i) = objFile.ReadLine
    i = i + 1
'     Set objFSO = CreateObject("Scripting.FileSystemObject")
'     Set objSh = CreateObject("WScript.Shell")
    If objFSO.FileExists("output.txt") Then
       Set objFile = objFSO.CreateTextFile("output.txt")
    End If
    Set objFile = Nothing

''Checks whether Server list is available
If objFSO.FileExists(strFile) Then
    Set objFile = objFSO.OpenTextFile("output.txt", ForAppending)
    objFile.WriteLine("Ping Results of the Servers in the server List as on  " & now())
' For Each strLine in arrFileLines
'    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}")._
'        ExecQuery("select * from Win32_PingStatus where address = '"_
'            & strLine & "'")
'    For Each objStatus in objPing
'        If IsNull(objStatus.StatusCode) or objStatus.StatusCode<>0 Then
'            objFile.WriteLine("Server: " & strLine & " is not reachable" & vbTab & objStatus.ProtocolAddress)
'        Else
'            objFile.WriteLine("Server: " & strLine & " is reachable *********************"& vbTab & objStatus.ProtocolAddress)
'For Each strLine in arrFileLines
'WScript.Echo ResolveIP("strLine")
'Function ResolveIP(strComputer)
''     On Error Resume Next
'    Dim wmiQuery, objWMIService, objPing, objStatus
'    wmiQuery = "Select * From Win32_PingStatus Where " & _
'    "Address = '" & strComputer & "'"
'    Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
'    Set objPing = objWMIService.ExecQuery(wmiQuery)
'    For Each objStatus in objPing
'        If IsNull(objStatus.StatusCode) Or objStatus.Statuscode<>0 Then
'            ResolveIP = "Computer is Unreachable!"
'        Else
'            ResolveIP = objStatus.ProtocolAddress
'        End If
'    Next
'End Function
For Each strLine in arrFileLines
If Reachable("strLine") Then
    WScript.Echo "Computer" & strLine & "is Reachable"
    WScript.Echo "Computer is Unreachable!"
End If

Function Reachable(strComputer)
'     On Error Resume Next

    Dim wmiQuery, objWMIService, objPing, objStatus
    wmiQuery = "Select * From Win32_PingStatus Where " & _
    "Address = '" & strComputer & "'"
    Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    Set objPing = objWMIService.ExecQuery(wmiQuery)
    For Each objStatus in objPing
        If IsNull(objStatus.StatusCode) Or objStatus.Statuscode<>0 Then
            Reachable = False 'if computer is unreacable, return false
            Reachable = True 'if computer is reachable, return true
        End If
End Function

'Set colComputer = GetObject("winmgmts:\\" & strLine & "\root\cimv2").ExecQuery("Select DomainRole, Domain from Win32_ComputerSystem")
'For Each oComputer in colComputer
'iDR = oComputer.DomainRole
'sName = oComputer.Domain
'If iDR = 0 Or iDR = 2 Then
'objFile.WriteLine "Computer is in workgroup " & sName
'objFile.WriteLine "Computer is in domain " & sName
'End If
        End If
End If
' objFile.Close

Set objFile = Nothing

WScript.Echo "****************************************************************************"
WScript.Echo "PKI Folder  Backup in progress, Please wait till the program says 'COMPLETE'"
WScript.Echo "****************************************************************************"
WScript.Echo ""
    Set objTS = objFSO.OpenTextFile(strFile)
    Set objOuts = objFSO.CreateTextFile("PKIbackupServerList.txt")
    Set objErr = objFSO.CreateTextFile("ErrorList.txt")            
    objOuts.WriteLine("List of Server Names whose PKI backup was done successfully on  " & now())
    objErr.WriteLine("List of Server Names whose PKI backup was not done as on  " & now())
Do Until objTS.AtEndOfStream
        strComputer = objTS.ReadLine

'Folder created with the respective server names    
'        If objFSO.FolderExists("\\mainserver\Final\New Folder\" & strComputer) Then

Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}")._
        ExecQuery("select * from Win32_PingStatus where address = '"_
            & strComputer & "'")
 For Each objStatus in objPing
    If IsNull(objStatus.StatusCode) or objStatus.StatusCode<>0 Then
            objErr.WriteLine("Server: " & strComputer & " is not reachable" & vbTab & objStatus.ProtocolAddress)
            objOuts.WriteLine("Server: " & strComputer & " is reachable *********************"& vbTab & objStatus.ProtocolAddress)
                     'End If
                    If objFSO.FolderExists("D:\NewPki" & strComputer) Then
                            WScript.Echo "Folder " & strComputer & " already exists, Skipping the server"
                            '    objErr.WriteLine("Server: " & strComputer & " is reachable *********************" & vbTab & objStatus.ProtocolAddress)
                         'Server list which are skipped.
                             objErr.WriteLine ("Server Name: " & strComputer & " Folder already exists hence skipped PKI backup")
                             objErr.WriteLine("Server: " & strComputer & " is reachable *********************"& vbTab & objStatus.ProtocolAddress)
                        Set objFolder    = objFSO.CreateFolder(strComputer)
                            'PKI folders are copied along with GRC.dat file in the created server folders    
                        '            objSh.Run "Xcopy.exe \\" & strComputer & "\Share\Test " & " " & "\\mainserver\Final\New Folder\" & strComputer & " /e /y"
                        '            objSh.Run "Xcopy.exe \\" & strComputer & "\test2\sam.cab" & " " & "\\mainserver\Final\New Folder\" & strComputer & "  /y"
'                                    objSh.Run "Xcopy.exe " & strSrc1 & " " & strDest & strComputer & " /e /y"
'                                    objSh.Run "Xcopy.exe " & strSrc2 & " " & strDest & strComputer & "  /y"
                        ' '             objSh.Run "Xcopy.exe C:\test C:\Backup /E /Y"
                                objSh.Run "Xcopy.exe \\" & strComputer & strSrc1 & " " & strDest & "\" & strComputer & " /e /y"
                                objSh.Run "Xcopy.exe \\" & strComputer & strSrc2 & " " & strDest & "\" & strComputer & "  /y"
                        '            objSh.Run "Xcopy.exe \\mainserver\test" & " " &  "\\mainserver\Final\New Folder"  & " /e /y"
                        '         WScript.Echo "Tried the above link for " & strComputer
                        WScript.Echo "Folder Created in the Name of :" & strComputer
                                    objOuts.WriteLine ("PKI Backup done for the Server Name: " & strComputer)
                    End If
    End If




'    End If


WScript.Echo "output of Backup servers will be in PKIbackupServerList.txt file"
WScript.Echo "output of skipped servers will be in ErrorList.txt file"

WScript.Echo "Complete :o)"

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.


Author Comment

ID: 21954099
The above code i fixed and run it in my server, its working. but the query state in the above code "'Set colComputer = GetObject("winmgmts:\\" & strLine & "\root\cimv2").ExecQuery("Select DomainRole, Domain from Win32_ComputerSystem")" throws error while run in windows 2003 environment. hence i commented the Ping status codes.

any idea how to check, whether the server is reachable, if reachable output the IP address and hostname of the server which are done with PKI backup.

P.S. For your question about the schedule backup on servers. The network is huge n the servers are large. any change in the schedule task has to go through proper procedure. this will take a month or two to proceed. I dont want the management to involve in approval / query. thats y i would like to run a vbscript with the list of server names in my network. Moreover, a copy of PKI folder for each server is enough, no need to take the backup again and again as scheduled.
LVL 25

Accepted Solution

Ron Malmstead earned 200 total points
ID: 22013135
while the above code is robust...obviously shankjai put alot of work into it... the problem with vb is that it doesn't wait for a command to complete before running the next line of code.  Also, if the return code is 0 vb assumes everything is peaches..The command executed, but it doesn't mean it succeeded.  

Essentially the above code is using VB, to run command line arguments ( xcopy ! ), ....which is why I think you would be better off using a simple batch file and just "do the deed" without complicating it by querying WMI and having to constantly debug a large vb script everytime you need to make a change or add/remove a server or directory or whatever...

You'll notice with WMI and vb, you'll get varying results from server to server as well.

You can run the batch file (xcopy) from your own machine as long as you have admin rights...  putting it as a scheduled task on each server was just a suggestion.

To check if a server is online...and that you have admin rights..  is simple.  Just look for the presence of a file...any file in the administrative share. C$..and also keep a log of whether or not copying succeeded.


IF NOT EXIST == \\servername1\c$\windows\system32\explorer.exe GOTO 2
xcopy \\servername1\pki\*.* \\servername2\PKI\USA\servername1\*.* /D /E /I /R /Y
ECHO servername1 not online %date% %time% >> \\servername2\pki\logfile.txt
IF NOT EXIST == \\servername3\c$\windows\system32\explorer.exe GOTO 4
xcopy \\servername1\pki\*.* \\servername2\PKI\Asia\servername1\*.* /D /E /I /R /Y
ECHO servername3 not online %date% %time% >> \\servername2\pki\logfile.txt
the above example servername2 is the repository server..

VB is good for alot of things.. but the simple copying of files from one location to another...is not one of them.  You can write a batch file to do the same thing in a fraction of the time.
LVL 25

Expert Comment

by:Ron Malmstead
ID: 22013172
I guess if you have the code working...and you just want to see if a machine is online. Use the code below.  Of course sub strComputer for strHost


'* Function IsPingable(strHost)
'*	Returns True or False based on the output from ping.exe	
Function IsPingable(strHost)
	Set objShell = WScript.CreateObject("WScript.Shell")
	Set objExecObject = objShell.Exec("cmd /c ping.exe -n 3 -w 1000 " &amp; strHost)
	Do While Not objExecObject.StdOut.AtEndOfStream
		strText = objExecObject.StdOut.ReadLine()
		If Instr(strText, "Reply") > 0 Then
	        		'Wscript.Echo "Reply received."
	        		IsPingable = True
			Exit Do
		End If
	If (IsPingable &lt;> True) Then
		IsPingable = False
	End If
End Function

Open in new window

LVL 25

Expert Comment

by:Ron Malmstead
ID: 22013175

Featured Post

The Lifecycle Approach to Managing Security Policy

Managing application connectivity and security policies can be achieved more effectively when following a framework that automates repeatable processes and ensures that the right activities are performed in the right order.

Question has a verified solution.

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

Considering today’s continual security threats, which affect Information technology networks and systems worldwide, it is very important to practice basic security awareness. A normal system user can secure himself or herself by following these simp…
2017 was a scary year for cyber security.  Hear what our security experts say that hackers have in store for us in 2018.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses

578 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