I have two files weblogic.jar and weblogic.policy in C:\Weblogic\wlserver\server\lib. With the first method, the script finds them and displays the name of the file:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Weblogic\wlserver\server\lib")
Set colFiles = objFolder.Files
For Each objFile in colFiles
If(StrComp(objFile.Name, "weblogic.jar", 1) = 0 OR StrComp(objFile.Name, "weblogic.policy", 1) = 0) Then
Wscript.Echo objFile.Name, objFile.Size
End If
Next
When I try to use WMI with CIM_DataFile, the script doesn't find any file in the same folder (but finds some in other folders):
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colFiles = objWMIService.ExecQuery ("Select Name from CIM_DataFile where FileName = 'weblogic'",, 48)
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
I am on Windows Server 2012 R2, I run the script as administrator and the folder C:\Weblogic needs admin privileges.
Is it a WMI privilege problem?
Someone already have this problem? What is the solution?
EDIT:
Thanks for your answer.
Sadly, that doesn't work. I get the same result.
I run the 2 method on the same script. I try to create test files on my desktop named weblogic.jar, weblogic.policy, ... and WMI doesn't find them !
Maybe WMI no longer works properly on this server ?
This is my script:
If Not WScript.Arguments.Named.Exists("elevate") Then
Wscript.Echo "Run"
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile="C:\test.txt"
Set objFileLog = objFSO.CreateTextFile(outFile,True)
objFileLog.Write "Scripting.FileSystemObject :" & vbCrLf
Set objFolder = objFSO.GetFolder("C:\Weblogic\wlserver\server\lib")
Set colFiles = objFolder.Files
For Each objFile in colFiles
If(StrComp(objFile.Name, "weblogic.jar", 1) = 0 OR StrComp(objFile.Name, "weblogic.policy", 1) = 0) Then
Wscript.Echo objFile.Name, objFile.Size
objFileLog.Write " " & objFile.Path & " " & objFile.Size & vbCrLf
End If
Next
objFileLog.Write "winmgmts :" & vbCrLf
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colFiles = objWMIService.ExecQuery ("Select Name from CIM_DataFile where FileName = 'weblogic'",, 48)
For Each objFile in colFiles
Wscript.Echo objFile.Name
objFileLog.Write " " & objFile.Name & vbCrLf
Next
objFileLog.Close
And the result is:
Scripting.FileSystemObject :
C:\Weblogic\wlserver\server\lib\weblogic.jar 5541
C:\Weblogic\wlserver\server\lib\weblogic.policy 30888
winmgmts :
c:\oracle\...\templates\wlserver\server\lib\weblogic.policy
c:\oracle\...\wlserver\server\lib\weblogic.policy
c:\oracle\...\sample\config\wls\web-inf\weblogic.xml
I don't get weblogic files with WMI in folders :
"C:\Weblogic\wlserver\server\lib\"
"C:...\Desktop\"
Try something like this to run the script with admin privileges :
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
'Your code goes here
Related
I am looking for a VB script or batch file to read & Execute multiple URLs from an CSV file containing the URL Data in column B & The mentioned URL directly contains on the downloadable file which need to store at location or directory named on behalf of content stored in Column A.
Column A & Column B could be vice versa.
I was trying same thing with batch file but unable to read CSV file automatically instead able to create simple code as show below but would be no success for daily usage as automatic as always required manual intervention, please help accordingly, also check in Python solution code is available but do not want to use it as required Python installation as do not want to do so too.
#echo Off
TITLE Test File Download and Storage
Pause
CD\
d:
cd Test
dir Tes_poc1 [i.e. From column A]
curl http://www.abcd,com/file1.pdf > file1.pdf [URL Just for example, can't share actual one due to security limitations]
cd Test
dir Tes_poc2 "i.e. From column A"
curl http://www.abcd,com/file2.pdf > file2.pdf [URL Just for example, can't share actual one due to security limitations]
Edit :
Also tried following VBscript able to download file and create folder but unable to move downloaded file to respective folder:
dim objFileSys, objReadFile
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const csFSpec = "1.txt"
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim goWS : Set goWS = CreateObject("WScript.Shell")
Dim tsIn : Set tsIn = goFS.OpenTextFile(csFSpec)
Do Until tsIn.AtEndOfStream
Dim sLine : sLine = tsIn.ReadLine
goWS.Run """chrome.exe"" """ & sLine & """", 1, True
Loop
tsIn.Close
Set objFileSys = CreateObject("Scripting.FileSystemObject")
Set objReadFile = objFileSys.OpenTextFile("D:\Test\2.txt", ForReading)
Do until objReadFile.AtEndOfStream = True
objFileSys.CreateFolder(objReadFile.ReadLine)
Loop
objReadFile.Close
Set objReadFile = Nothing
Set objFileSys = Nothing
Where 1.txt contains list of urls and 2.txt contains list of respective URL folder name to be create
here are few Example URL's you can use as sample.
http://www.iiswc.org/iiswc2009/sample.doc
https://www.scc.kit.edu/downloads/jrg-mb/Abstract_template.doc
https://www.k-state.edu/grad/etdr/template/mastersinstructions.doc
https://www.cdc.gov/polio/stop/doc/stop-cv-format.doc
Suppose you have the contents of the.csv file like this one in the same folder of your batch file : Test.csv
Tes_poc1,http://www.pdf995.com/samples/pdf.pdf
Tes_poc2,https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png
You can do something like this to download files with Certutil command line :
#echo off
Mode 60,3 & Color A
Title Download files with Certutil command by Hackoo 2018
Set "File=%~dp0Test.csv"
Set "DownloadFolder=%~dp0Test"
if not exist "%DownloadFolder%" MD "%DownloadFolder%"
CD /D "%DownloadFolder%"
#for /F "tokens=1-2 delims=," %%i in ('Type "%File%"') do (
If not exist "%DownloadFolder%\%%i\" MD "%DownloadFolder%\%%i\"
cls & echo( & echo Downloading "%%~nxj"
Call :Download %%j %DownloadFolder%\%%i\%%~nxj
)
Start "" Explorer "%DownloadFolder%" & Exit
::--------------------------------------------
:Download <Url> <File>
certutil.exe -urlcache -split -f %1 %2 >nul
exit /b
::-------------------------------------------
You can give a try for this vbscript with a progressbar in bonus !
Usage : Drag and Drop a text file that contains url per row over this script to be downloaded
Or
Usage in command line : Cscript //nologo "ThisVbsFile" "Path\TextFile.txt"
Option Explicit
Const Copyright =" (C) by Hackoo 2018"
Dim Title,InputFile,objFSO,objStream,dic,URL,FileName,PathScript
Dim BaseName,Save2File,Folder,k,WaitingMsg,ws,Temp,oExec,HH
Title = "Download From File"
If WSH.Arguments.Count = 0 Then
MsgBox "Usage : Drag and Drop a text file that contains url per row over " &_
"this script "& DblQuote(WSH.Scriptname) & " to be downloaded "& vbCrlf &_
"OR " & vbCrlf &_
"Usage in command line : "& vbCrlf &_
"Cscript //nologo "& DblQuote(WSH.Scriptname) & " " & DblQuote("Path\TextFile.txt"),_
vbExclamation,Title & Copyright
Wscript.Quit(1)
End If
InputFile = Wscript.Arguments(0)
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objStream = objFSO.OpenTextFile (InputFile, 1)
set dic = CreateObject("Scripting.Dictionary")
Set ws = CreateObject("WScript.Shell")
Temp = ws.ExpandEnvironmentStrings("%Temp%")
Do while not objStream.AtEndOfStream
URL = objStream.ReadLine
If URL <> "" Then
FileName = GetFileNamefromDirectLink(URL)
PathScript = objFSO.GetParentFolderName(wscript.ScriptFullName) 'Path of this Vbscript
BaseName = GetFilenameWithoutExtension(FileName)
Folder = PathScript & "\" & BaseName
If Not objFSO.FolderExists(Folder) Then
objFSO.CreateFolder(Folder)
End If
dic.Add URL,Folder & "\" & FileName
End If
Loop
For Each URL in dic
Save2File = dic(URL)
WaitingMsg = "Please wait ... The download of : <font color=Yellow>"& DblQuote(Save2File) & "</font> is in progress ..."
Call CreateProgressBar(Title,WaitingMsg)'Creation of Waiting Bar
Call LaunchProgressBar() 'Launch of the Waiting Bar
Call Download(URL,Save2File)
pause(1)
Call CloseProgressBar()
Next
Set HH = CreateObject("Internet.HHCtrl")
HH.TextPopup " Download is finished ! ", "Tahoma,32", 10,10,10,500
Pause(3)
Wscript.Quit(0)
'------------------------------------------------
Sub Download(URL,Save2File)
Dim File,Line,BS,ws
On Error Resume Next
Set File = CreateObject("WinHttp.WinHttpRequest.5.1")
File.Open "GET",URL, False
File.Send()
If err.number <> 0 then
Line = Line & vbcrlf & "Error Getting File"
Line = Line & vbcrlf & "Error " & err.number & "(0x" & hex(err.number) & ") " & vbcrlf &_
err.description
Line = Line & vbcrlf & "Source " & err.source
MsgBox Line,vbCritical,"Error getting file"
Err.clear
wscript.quit
End If
If File.Status = 200 Then ' File exists and it is ready to be downloaded
Set BS = CreateObject("ADODB.Stream")
Set ws = CreateObject("wscript.Shell")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile Save2File, 2
ElseIf File.Status = 404 Then
MsgBox "File Not found : " & File.Status,vbCritical,"Error File Not Found"
Else
MsgBox "Unknown Error : " & File.Status,vbCritical,"Error getting file"
End If
End Sub
'------------------------------------------------
Function GetFileNamefromDirectLink(URL)
Dim ArrFile,FileName
ArrFile = Split(URL,"/")
FileName = ArrFile(UBound(ArrFile))
GetFileNamefromDirectLink = FileName
End Function
'------------------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'------------------------------------------------
Function GetFilenameWithoutExtension(FileName)
Dim Result, i
Result = FileName
i = InStrRev(FileName, ".")
If ( i > 0 ) Then
Result = Mid(FileName, 1, i - 1)
End If
GetFilenameWithoutExtension = Result
End Function
'------------------------------------------------
Sub CreateProgressBar(Title,WaitingMsg)
Dim ws,fso,f,f2,ts,ts2,Ligne,i,fread,LireTout,NbLigneTotal,Temp,PathOutPutHTML,fhta,oExec
Set ws = CreateObject("wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Temp = WS.ExpandEnvironmentStrings("%Temp%")
PathOutPutHTML = Temp & "\Barre.hta"
Set fhta = fso.OpenTextFile(PathOutPutHTML,2,True)
fhta.WriteLine "<HTML>"
fhta.WriteLine "<HEAD>"
fhta.WriteLine "<Title> " & Title & Copyright & "</Title>"
fhta.WriteLine "<HTA:APPLICATION"
fhta.WriteLine "ICON = ""magnify.exe"" "
fhta.WriteLine "BORDER=""THIN"" "
fhta.WriteLine "INNERBORDER=""NO"" "
fhta.WriteLine "MAXIMIZEBUTTON=""NO"" "
fhta.WriteLine "MINIMIZEBUTTON=""NO"" "
fhta.WriteLine "SCROLL=""NO"" "
fhta.WriteLine "SYSMENU=""NO"" "
fhta.WriteLine "SELECTION=""NO"" "
fhta.WriteLine "SINGLEINSTANCE=""YES"">"
fhta.WriteLine "</HEAD>"
fhta.WriteLine "<BODY text=""white""><CENTER>"
fhta.WriteLine "<marquee DIRECTION=""LEFT"" SCROLLAMOUNT=""3"" BEHAVIOR=ALTERNATE><font face=""Comic sans MS"">" & WaitingMsg &"</font></marquee>"
fhta.WriteLine "<img src=""data:image/gif;base64,R0lGODlhgAAPAPIAAP////INPvvI0/q1xPVLb/INPgAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAgAAPAAAD5wiyC/6sPRfFpPGqfKv2HTeBowiZGLORq1lJqfuW7Gud9YzLud3zQNVOGCO2jDZaEHZk+nRFJ7R5i1apSuQ0OZT+nleuNetdhrfob1kLXrvPariZLGfPuz66Hr8f8/9+gVh4YoOChYhpd4eKdgwDkJEDE5KRlJWTD5iZDpuXlZ+SoZaamKOQp5wAm56loK6isKSdprKotqqttK+7sb2zq6y8wcO6xL7HwMbLtb+3zrnNycKp1bjW0NjT0cXSzMLK3uLd5Mjf5uPo5eDa5+Hrz9vt6e/qosO/GvjJ+sj5F/sC+uMHcCCoBAAh+QQJCgAAACwAAAAAgAAPAAAD/wi0C/4ixgeloM5erDHonOWBFFlJoxiiTFtqWwa/Jhx/86nKdc7vuJ6mxaABbUaUTvljBo++pxO5nFQFxMY1aW12pV+q9yYGk6NlW5bAPQuh7yl6Hg/TLeu2fssf7/19Zn9meYFpd3J1bnCMiY0RhYCSgoaIdoqDhxoFnJ0FFAOhogOgo6GlpqijqqKspw+mrw6xpLCxrrWzsZ6duL62qcCrwq3EsgC0v7rBy8PNorycysi3xrnUzNjO2sXPx8nW07TRn+Hm3tfg6OLV6+fc37vR7Nnq8Ont9/T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DpuXlZ+SoZaamKOQp5wAm56loK6isKSdprKotqqttK+7sb2zq6y8wcO6xL7HwMbLtb+3zrnNycKp1bjW0NjT0cXSzMLK3uLd5Mjf5uPo5eDa5+Hrz9vt6e/qosO/GvjJ+sj5F/sC+uMHcCCoBAA7AAAAAAAAAAAA"" />"
fhta.WriteLine "</CENTER></BODY></HTML>"
fhta.WriteLine "<SCRIPT LANGUAGE=""VBScript""> "
fhta.WriteLine "Set ws = CreateObject(""wscript.Shell"")"
fhta.WriteLine "Temp = WS.ExpandEnvironmentStrings(""%Temp%"")"
fhta.WriteLine "Sub window_onload()"
fhta.WriteLine " CenterWindow 575,100"
fhta.WriteLine " Self.document.bgColor = ""DarkOrange"" "
fhta.WriteLine " End Sub"
fhta.WriteLine " Sub CenterWindow(x,y)"
fhta.WriteLine " Dim iLeft,itop"
fhta.WriteLine " window.resizeTo x,y"
fhta.WriteLine " iLeft = window.screen.availWidth/2 - x/2"
fhta.WriteLine " itop = window.screen.availHeight/2 - y/2"
fhta.WriteLine " window.moveTo ileft,itop"
fhta.WriteLine "End Sub"
fhta.WriteLine "</script>"
fhta.close
End Sub
'------------------------------------------------
Sub LaunchProgressBar()
Set oExec = Ws.Exec("mshta.exe " & Temp & "\Barre.hta")
End Sub
'------------------------------------------------
Sub CloseProgressBar()
oExec.Terminate
End Sub
'------------------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'------------------------------------------------
Sub Pause(Secs)
Wscript.Sleep(Secs * 1000)
End Sub
'------------------------------------------------
I am trying to write a windows batch script that will run all the time and when a usb flash drive will be inserted it will copy files from usb to computer.
I've found a lot of script that do different parts of it but none of them works as I want.
Can sombody help me ?
I posted before a vbscript here to do what you want just take a look and try it !
Vbscript to copy files with specific extension from usb when plugged in
Edit on 19/07/2016 #10:42 :
I improved this vbsript to run as admin, and to let executing just one insctance of this script.
AutoSave_USB_SDCARD.vbs to copy into My Documents folder
Option Explicit
' Run as Admin
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
' To let executing just one insctance of this script
If AppPrevInstance() Then
MsgBox "There is an existing proceeding !" & VbCrLF &_
CommandLineLike(WScript.ScriptName),VbExclamation,"There is an existing proceeding !"
WScript.Quit
Else
Do
Call AutoSave_USB_SDCARD()
Pause(30)
Loop
End If
'**************************************************************************
Function AppPrevInstance()
With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE "_
& CommandLineLike(WScript.ScriptFullName) & _
" AND CommandLine LIKE '%WScript%' OR CommandLine LIKE '%cscript%'")
AppPrevInstance = (.Count > 1)
End With
End With
End Function
'**************************************************************************
Function CommandLineLike(ProcessPath)
ProcessPath = Replace(ProcessPath, "\", "\\")
CommandLineLike = "'%" & ProcessPath & "%'"
End Function
'*************************AutoSave_USB_SDCARD()****************************
Sub AutoSave_USB_SDCARD()
Dim Ws,WshNetwork,NomMachine,MyDoc,strComputer,objWMIService,objDisk,colDisks
Dim fso,Drive,NumSerie,volume,cible,Amovible,Dossier,chemin,Command,Result
Set Ws = CreateObject("WScript.Shell")
Set WshNetwork = CreateObject("WScript.Network")
NomMachine = WshNetwork.ComputerName
MyDoc = Ws.SpecialFolders("Mydocuments")
cible = MyDoc & "\"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
("SELECT * FROM Win32_LogicalDisk")
For Each objDisk in colDisks
If objDisk.DriveType = 2 Then
Set fso = CreateObject("Scripting.FileSystemObject")
For Each Drive In fso.Drives
If Drive.IsReady Then
If Drive.DriveType = 1 Then
NumSerie=fso.Drives(Drive + "\").SerialNumber
Amovible=fso.Drives(Drive + "\")
Numserie=ABS(INT(Numserie))
volume=fso.Drives(Drive + "\").VolumeName
Dossier=NomMachine & "_" & volume &"_"& NumSerie
chemin=cible & Dossier
Command = "cmd /c Xcopy.exe " & Amovible &" "& chemin &" /I /D /Y /S /J /C"
Result = Ws.Run(Command,0,True)
end if
End If
Next
End If
Next
End Sub
'**************************End of AutoSave_USB_SDCARD()*******************
Sub Pause(Sec)
Wscript.Sleep(Sec*1000)
End Sub
'************************************************************************
This waits for the volumes to change, then copies the USB to c:\test. Lots of message boxes so you can see what's happening. Remove them for production.
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set evtDevice = objWMIService.ExecNotificationQuery ("SELECT * FROM Win32_VolumeChangeEvent")
Wscript.Echo "Waiting for events ..."
Do
Set objReceivedEvent = evtDevice.NextEvent
'report an event
Wscript.Echo " Win32_Device Changed event occurred" & VBNewLine
If objReceivedEvent.EventType = 1 Then
Wscript.Echo "Type = Config Changed"
ElseIf objReceivedEvent.EventType = 2 Then
Wscript.Echo "Type = Device Arrived"
Set colItems = objWMIService.ExecQuery("Select * From Win32_Volume")
For Each objItem in colItems
Wscript.Echo objitem.DriveType
If objitem.DriveType = 2 then
Wscript.Echo objItem.DriveType & " " & objItem.Name & " " & objItem.driveletter
Wscript.Echo "Starting Copying"
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set SrcFldr=objShell.NameSpace(objitem.driveletter)
Set DestFldr=objShell.NameSpace("c:\test\")
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Wscript.Echo "Finished Copying"
End If
Next
ElseIf objReceivedEvent.EventType = 3 Then
Wscript.Echo "Type = Device Left"
ElseIf objReceivedEvent.EventType = 4 Then
Wscript.Echo "Type = Computer Docked"
End If
Loop
Try this:
#echo off
set backupcmd=xcopy /s /c /d /e /h /i /r /y /
%backupcmd% "%USERPROFILE%\Pictures" "%drive%\all\My pics"
%backupcmd% "%USERPROFILE%\Favorites" "%drive%\all\Favorites"
%backupcmd% "%USERPROFILE%\Videos" "%drive%\all\Vids"
%backupcmd% "%USERPROFILE%\Documents" "%drive%\all\Docs"
%backupcmd% "%USERPROFILE%\OneDrive" "%drive%\all\Onedrive"
%backupcmd% "%USERPROFILE%\Desktop" "%drive%\all\Desktop"
%backupcmd% "%USERPROFILE%\Network" "%drive%\all\Other devices"
I needed to copy all of my photos from my old laptop to my new laptop. This is a quick and dirty script that I put together (based on other scripts on this site) to copy files from one network location to another. I wanted the process to be able to recover in case of a network copy error because the total time to copy all of my photos was 40 hours.
sourceRoot and targetRoot is the beginning part of the file path to replace between locations. lastFileLog is a file used to keep track of the last file that was copied. This is needed to recover from a partial copy. Windows seems to allocate the full file size even when the file fails to copy. So I just keep track of the last file to copy it again on failure. objStartFolder is the starting path on the source network location.
'initialize paths
objStartFolder = "\\owner-pc\d\pics"
lastFileLog = "c:\Files\misc\archive.log"
sourceRoot = "\\owner-pc\d"
targetRoot = "c:\Files"
Set objFSO = CreateObject("Scripting.FileSystemObject")
'read log
Set objFile = objFSO.OpenTextFile(lastFileLog)
Do Until objFile.AtEndOfStream
replacefile= objFile.ReadLine
Wscript.Echo "This file will be replaced: " & replacefile
Loop
objFile.Close
'copy files
Set objFolder = objFSO.GetFolder(objStartFolder)
ShowSubfolders objFSO.GetFolder(objStartFolder)
'clear log
Set objFileLog = objFSO.CreateTextFile(lastFileLog,True)
objFileLog.Write ""
objFileLog.Close
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Wscript.Echo Subfolder.Path
if not(objFSO.FolderExists(replace(Subfolder.Path,sourceRoot,targetRoot))) then
objFSO.CreateFolder(replace(Subfolder.Path,sourceRoot,targetRoot))
end if
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
if not(objFSO.FileExists(replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot))) then
Wscript.Echo Subfolder.Path & "\" & objFile.Name
Set objFileLog = objFSO.CreateTextFile(lastFileLog,True)
objFileLog.Write Subfolder.Path & "\" & objFile.Name
objFileLog.Close
objFSO.CopyFile Subfolder.Path & "\" & objFile.Name, replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot)
elseif replacefile = Subfolder.Path & "\" & objFile.Name then
Wscript.Echo "Replacing ... " & Subfolder.Path & "\" & objFile.Name
objFSO.CopyFile Subfolder.Path & "\" & objFile.Name, replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot),true
else
Wscript.Echo "Skip ... " & Subfolder.Path & "\" & objFile.Name
end if
Next
ShowSubFolders Subfolder
Next
end sub
For Folder: Try This.
Option Explicit
Dim obj,Itemcoll1,a,b
Set obj=CreateObject("Shell.Application")
Function SelectFold1(Desc)
Set SelectFold1=obj.BrowseForFolder(0,Desc,0,"C:\Users\Mohammed Sajjad\Desktop\")
End Function
Set Itemcoll1=SelectFold1("Copy: ").Items
SelectFold1("Paste: ").CopyHere Itemcoll1 'Use MoveHere if you want to move
MsgBox "Completed"
For File:
Option Explicit
Dim objApp : Set objApp = CreateObject("Shell.Application")
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objSHL : Set objSHL = CreateObject("WScript.Shell")
'Browse for Folder
'----------------------------------------------------------
Function SelectFold()
Dim objFolder
Set objFolder = objApp.BrowseForFolder(0,"Select a Folder",0,0)
If objFolder Is Nothing Then
MsgBox "Canceled"
WScript.Quit
Else
SelectFold = objFolder.Self.Path & "\"
End If
End Function
'----------------------------------------------------------
'Browse for file
'----------------------------------------------------------
Function SelectFile()
Dim tempFolder : Set tempFolder = objFSO.GetSpecialFolder(2)
Dim tempFile : tempFile = objFSO.GetTempName() & ".hta"
Dim path : path = "HKCU\Volatile Environment\MsgResp"
With tempFolder.CreateTextFile(tempFile)
.Write "<input type=file name=f>" & _
"<script>f.click();(new ActiveXObject('WScript.Shell'))" & _
".RegWrite('HKCU\\Volatile Environment\\MsgResp', f.value);" & _
"close();</script>"
.Close
End With
objSHL.Run tempFolder & "\" & tempFile, 0, True
If objSHL.RegRead(path) = "" Then
objSHL.RegDelete path
objFSO.DeleteFile tempFolder & "\" & tempFile
WScript.Quit
End If
SelectFile = objSHL.RegRead(path)
objSHL.RegDelete path
objFSO.DeleteFile tempFolder & "\" & tempFile
End Function
'----------------------------------------------------------
objFSO.CopyFile SelectFile, SelectFold
In Windows 7, I've got a VBScript that creates an email in Outlook with a link to the file when you right-click in Windows Explorer. The script is run by creating a shortcut to it and adding it to %userprofile%\SendTo (which shows up in the Send to when you right-click the file). The goal is to be able to send a link to the file and the folder that contains it, rather than sending it as an attachment. It works fine except it always give a link directly to the file. How do I modify it so it also provides a link to the folder in the second line?
Const olMailItem = 0
Const olFolderInbox = 6
If WScript.Arguments.Count = 0 Then
WScript.Quit
End If
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_Process Where Name = 'outlook.exe'")
If colItems.Count = 0 Then
Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objFolder = objNamespace.GetDefaultFolder(olFolderInbox)
objFolder.Display
End If
strFile = WScript.Arguments.Item(0)
Set objOutlook = CreateObject("Outlook.Application")
Set objItem = objOutlook.CreateItem(olMailItem)
objItem.Subject = "Here is a link to a file..."
objItem.HTMLBody = "Link to the file: " & strFile & "<BR>Link to the folder: " & strFile & ""
objItem.Display
Might be a simple answer, but I haven't been able to figure it out. Any help would be appreciated!
The FileSystemObject object and it's GetParentFolderName method could help. Note that for any of methods used (in next script) hold: a method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.
option explicit
Dim strFile, FSO, oFile
If WScript.Arguments.Count > 0 Then
strFile = WScript.Arguments.Item(0)
Else
strFile = "D:\Remote\bat\COCL\bu bu bu\somefile.ext"
End If
Set FSO = CreateObject("Scripting.FileSystemObject")
Wscript.Echo "FSO 'path' methods" & vbNewLine & "---------------------" _
& vbNewLine & "GetAbsolutePathName: " & FSO.GetAbsolutePathName( strFile) _
& vbNewLine & "GetParentFolderName: " & FSO.GetParentFolderName( strFile) _
& vbNewLine & "GetDriveName: " & FSO.GetDriveName( strFile) _
& vbNewLine & "GetBaseName: " & FSO.GetBaseName( strFile) _
& vbNewLine & "GetExtensionName: " & FSO.GetExtensionName( strFile) _
& vbNewLine & "GetFileName: " & FSO.GetFileName( strFile)
Set FSO = Nothing
Wscript.Quit
Here is my bat file
REG DELETE "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate" /v SusClientId /f
REG DELETE "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate" /v SusClientIdValidation /f
C:\Windows\System32\wuauclt.exe /resetauthorization /detectnow
C:\Windows\System32\wuauclt.exe /reportnow
The bat file doesn't work unless it's run inside an "Administrator Command Prompt"
My question is how can I use a VBScript wrapper to run the bat file as an Admin?
I was trying to run this bat file with SCCM but it didn't work. We used a support incident ticket with Microsoft to find out that we need a VBScript wrapper to launch the bat file as an Admin.
Use the runas verb
HelpMsg = vbcrlf & " ShVerb" & vbcrlf & vbcrlf & " David Candy 2014" & vbcrlf & vbcrlf & " Lists or runs an explorer verb (right click menu) on a file or folder" & vbcrlf & vbcrlf & " ShVerb <filename> [verb]" & vbcrlf & vbcrlf & " Used without a verb it lists the verbs available for the file or folder" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The program lists most verbs but only ones above the first separator" & vbcrlf & " of the menu work when used this way" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The Properties verb can be used. However the program has to keep running" & vbcrlf & " to hold the properties dialog open. It keeps running by displaying" & vbcrlf & " a message box."
Set objShell = CreateObject("Shell.Application")
Set Ag = WScript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
If Ag.count = 0 then
wscript.echo " ShVerb - No file specified"
wscript.echo HelpMsg
wscript.quit
Else If Ag.count = 1 then
If LCase(Replace(Ag(0),"-", "/")) = "/h" or Replace(Ag(0),"-", "/") = "/?" then
wscript.echo HelpMsg
wscript.quit
End If
ElseIf Ag.count > 2 then
wscript.echo vbcrlf & " ShVerb - To many parameters" & vbcrlf & " Use quotes around filenames and verbs containing spaces" & vbcrlf
wscript.echo HelpMsg
wscript.quit
End If
If fso.DriveExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetFileName(Ag(0)))
' Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Set objFolderItem = objFolder.self
msgbox ag(0)
ElseIf fso.FolderExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
ElseIf fso.fileExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Else
wscript.echo " ShVerb - " & Ag(0) & " not found"
wscript.echo HelpMsg
wscript.quit
End If
Set objVerbs = objFolderItem.Verbs
'If only one argument list verbs for that item
If Ag.count = 1 then
For Each cmd in objFolderItem.Verbs
If len(cmd) <> 0 then CmdList = CmdList & vbcrlf & replace(cmd.name, "&", "")
Next
wscript.echo mid(CmdList, 2)
'If two arguments do verbs for that item
ElseIf Ag.count = 2 then
For Each cmd in objFolderItem.Verbs
If lcase(replace(cmd, "&", "")) = LCase(Ag(1)) then
wscript.echo Cmd.doit
Exit For
End If
Next
'Properties is special cased. Script has to stay running for Properties dialog to show.
If Lcase(Ag(1)) = "properties" then
WSHShell.AppActivate(ObjFolderItem.Name & " Properties")
msgbox "This message box has to stay open to keep the " & ObjFolderItem.Name & " Properties dialog open."
End If
End If
End If