I got this script working as an app in Finder but I would like to get an alert when the archive is done. Any idea how I can do this?
tell application "Finder"
set theItems to selection
repeat with _a from 1 to (count of theItems)
set theItem to (item _a of theItems) as alias
set itemPath to quoted form of POSIX path of theItem
set fileName to name of theItem
set theFolder to POSIX path of (container of theItem as alias)
set zipFile to quoted form of (theFolder & fileName & ".tgz")
do shell script "tar czvf " & zipFile & " " & itemPath
end repeat
end tell
many thanks
Erik
Related
I've been trying for a little while to swap out one of the parts in a POSIX Path with a variable but I've had no success. This is the script I'm trying to develop:
tell application "Finder"
duplicate POSIX file "/Users/**Variable**/Documents/img.jpg" to POSIX file "/Users/**Variable**/Desktop/" with replacing
end tell
The parts in the path are the places where I want the variable to be present. How can I do this?
You break the string with ampersands & and the variable.
Also, it's good practice to convert posix paths to Mac standard colon: paths prior to scripting Finder. Finder's duplicate function has been buggy since 10.9 in these ways.
I have broken out some of the coercions so you can see what's going on.
-- define file and user names
set fileName to "img.jpg"
set user1 to "Mitc"
set user2 to "Mitc"
-- create posix path strings
set path1 to "/Users/" & user1 & "/Documents/" & fileName
set path2 to "/Users/" & user2 & "/Desktop/"
-- convert posix paths into colon paths
set ref1 to (POSIX file path1) as string
set ref2 to (POSIX file path2) as string
-- display dialog ref1 & return & ref2 -- to test
tell application "Finder" to duplicate alias ref1 to alias ref2 with replacing
you have to use the " & to tell the script to stop reading the directory and add the variable so here is the result:
tell application "Finder"
duplicate POSIX file "/Users/" & variable & "/Documents/img.jpg" to POSIX file "/Users/" & variable & "/Desktop/" with replacing
end tell
(make sure you use the "set" command to make the variable, EG.)
set variable to "text"
Hope this helped!
I need to join any files (2GB) without read their content. I have tried to use CopyFile method but it doesn't work.
My code is that:
Public Function UnificarCRIs(ByVal path, ByVal FICRIEC, ByVal sessio, ByVal CIBAA)
Dim objFile, objCurrentFolder, filesys, origenFitxers
Dim FileName, WshShell
On error resume next
Set filesys = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objCurrentFolder = filesys.getFolder(path)
origenFitxers = " "
For Each objFile In objCurrentFolder.Files
FileName = objFile
If (right(FileName, 4) = ".cri") Then
origenFitxers = FileName
'Wscript.Echo FileName
If filesys.FileExists(path & FICRIEC & sessio) Then
'Wscript.Echo "If"
Wscript.Echo path & FICRIEC & sessio & "+" & FileName
filesys.CopyFile path & FICRIEC & sessio & "+" & FileName, path & FICRIEC & sessio
'WshShell.Run ("copy " & path & FICRIEC & sessio & "+" & FileName & " " & path & FICRIEC & sessio & "_tmp")
'filesys.DeleteFile path & FICRIEC & sessio
'filesys.MoveFile path & FICRIEC & sessio & "_tmp", path & FICRIEC & sessio
Else
Wscript.Echo "Else"
WshShell.Run ("copy " & FileName & " " & path & FICRIEC & sessio)
'filesys.CopyFile FileName,path & FICRIEC & sessio
End If
End If
Next
End Function
Are there some way to join two files using Vbscript?
Thanks
To join two files, 'someone' has to to read (and write) the contents of both files. This 'someone' could be copy [/B] f1 + f2 f3. So use your loop to build the correct file specs and WshShell.Run/.Exec the suitabe commands.
Depends which COM objects you have access to and where the code is running.
1) If you have access to the Shell, then use the copy command of the DOS prompt. This example shows the excecution of the Dir command but it's the same technique.
Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")
' Note the True value means wait to complete...
' And the 0 value means do not display any window...
oShell.run "cmd /K CD C:\ & Dir", 0, True
Set oShell = Nothing
And maybe also take a look here http://ss64.com/vb/shellexecute.html. Don't know if that method will help.
2) If you have no shell then if you can make COM objects then make one with C++ or Delphi or VB6 etc. Then use that COM object to execute the DOS command to do the merging.
3) Otherwise you will have to read the data from the file. If it is text files then that is easy because there are simple commands to do that with in the Vbs. If it is binary data then that requires more work to get at the binary data and use the "LenB" and "AscB" style functions to access the raw bytes of the Unicode. But you really do not want to do that.
Any upload handling script for ASP should show you the technique for working with raw bytes from the strings.
You can combine VBScript with Windows Copy command to join files.
You can see the document on appending binary files using Copy here
https://support.microsoft.com/en-us/kb/71161
Here's the example of the technique:
JoinFiles "c:\test\", "c:\test\mergedfile.cri"
Function JoinFiles (inPath, outPath)
Dim objShell, objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = WScript.CreateObject("WScript.Shell")
Dim strFilenames, objFile, intFilecount, intExitCode
strFilenames = ""
intFilecount = 0
intExitCode = 0
' If the input folder exists, proceed to listing the files
If objFSO.FolderExists (inPath) Then
' List the files in the folder and join the files which has cri extension
For Each objFile In objFSO.GetFolder(inPath).Files
If LCase (objFSO.GetExtensionName (objFile.Path)) = "cri" Then
intFilecount = intFilecount+1
strFilenames = strFilenames & """" & objFile.Path & """ + "
End If
Next
' If there're more than one file, proceed to join the file
If (intFilecount > 1) Then
' join the files. Remove the last 3 characters from strFilenames (" + ").
intExitCode = objShell.Run ("%COMSPEC% /C COPY /B " & Left (strFilenames, Len (strFilenames)-3) _
& " """ & outPath & """ /Y", 0, True)
Else
' Not enough file to join
End If
Else
' Can't find folder, exit.
End If
End Function
I am going to create a self extracting archive but I have got a problem connecting with the default path of the extraction. I would like to extract my files in the same path as the self-extraction archive program. Unfortunately, the files are extracting in another path (C:\Users\computer\AppData\Temp\IXP000.TMP). Is it possible to set the path?
I can't find any direct way to do this with IExpress, but there is a trick we can apply.
But first I'll point out that this is really easy with something like 7-Zip's 7zCon.sfx module (if all you need to do is have the archive extract to the current directory, no questions asked). So you might just want to try something other than IExpress.
Anyhow, the problem with IExpress is that, at the time our install program runs, we're no longer in the directory of the original archive; the current directory is now something like %temp%\IXP000.TMP. So we need to find the directory of our parent process – kind of a pain. Once that's known, we can just xcopy the contents of the archive over to the destination folder.
In VBScript, it would look something like this:
Option Explicit
Dim objShell, objWMI
Dim objCmd, intMyPid, intMyParentPid, objMyParent
Set objShell = CreateObject("WScript.Shell")
Set objWMI = GetObject("winmgmts:root\cimv2")
Set objCmd = objShell.Exec("cmd.exe")
intMyPid = objWMI.Get("Win32_Process.Handle='" & objCmd.ProcessID & "'").ParentProcessId
objCmd.Terminate
intMyParentPid = objWMI.Get("Win32_Process.Handle='" & intMyPid & "'").ParentProcessId
Set objMyParent = objWMI.Get("Win32_Process.Handle='" & intMyParentPid & "'")
objShell.Run "xcopy /y * " & """" & Left(objMyParent.ExecutablePath, _
InStrRev(objMyParent.ExecutablePath, ".exe", -1, vbTextCompare) -1) &_
"\""", 0, True
Your install program would then be, eg: wscript extractToOriginalLocation.vbs //B.
(Inspired somewhat by the answer to this question.)
You could always use a cmd script and echo lines of code into files in specific directories
My iPad app gives users the ability to watch a few hundred videos. Currently the iPad app points them to an MP4 file. However, I would like to point them to a QuickTime Reference Movie instead. (This allows the app to send a lower-bitrate version of the video if the user is connected via 3G vs. wifi.)
Right now, I create the various versions, plus the reference file, in QuickTime by going to File -> Export to Web. However, this process (1) only lets me do one file at a time, and (2) generates lots of useless stuff like HTML and JavaScript.
How can I automate the process? Does anyone know of existing scripts / tools to do this work? I'm sure other devs have had to do it before.
I wrote (and cobbled together from other stuff on the web) this AppleScript to do the job:
--property exportFolder : (path to documents folder as Unicode text) & "Your Folder:"
property QTExportPath : (path to movies folder from user domain)
property completedFolderName : "completion" -- this folder must already exist
property referenceFiles : {}
property encodeCount : 0
on run
choose folder with prompt "Choose folder with video files:" -- with multiple selections allowed
open (result)
end run
on open droppedItems
tell application "Finder"
set allFiles to every file of entire contents of droppedItems as alias list
end tell
-- Error checking
repeat with testFile in allFiles
set myChars to characters of basename(testFile)
if count_matches(myChars, ".") > 1 then
display dialog "ERROR: The file " & basename(testFile) & " has too many periods."
return
end if
end repeat
-- Made it past error checking, let's get started
tell application "QuickTime Player"
activate
close every window
end tell
repeat with thisItem in allFiles
tell application "QuickTime Player"
close every window
open thisItem as alias
end tell
activate application "QuickTime Player"
tell application "System Events"
tell process "QuickTime Player"
keystroke "E" using command down
repeat until exists sheet 1 of window 1
delay 0.2
end repeat
click button "Export" of sheet 1 of window 1
end tell
end tell
tell application "Finder"
set fileExt to name extension of thisItem
end tell
set fileBaseName to basename(thisItem)
set lengthWithoutExtension to (count of fileBaseName) - (count of fileExt) - 1
set fileBaseNameWithoutExtension to text 1 thru lengthWithoutExtension of fileBaseName
set end of referenceFiles to fileBaseNameWithoutExtension
repeat until startedExporting(fileBaseNameWithoutExtension)
-- wait for this file to start exporting before beginning another
end repeat
end repeat
repeat until doneExporting(referenceFiles)
-- wait for exporting to finish
end repeat
cleanUpGarbage(referenceFiles)
tell application "QuickTime Player"
activate
close every window
quit
end tell
display alert "finished exporting"
end open
on basename(thePath) -- Returns basename of alias
set thePOSIXPath to the POSIX path of thePath
if thePOSIXPath ends with "/" then
set nameIndex to -2
else
set nameIndex to -1
end if
set ASTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to "/"
set thePOSIXPath to text item nameIndex of thePOSIXPath
set AppleScript's text item delimiters to ASTID
return thePOSIXPath
end basename
on startedExporting(fileBaseNameWithoutExtension) -- Checks if QuickTime began exporting a file
set moviesPath to QTExportPath as text
set fileToTest to ((the POSIX path of moviesPath) & fileBaseNameWithoutExtension & "/Resources/" & fileBaseNameWithoutExtension & ".mov")
if FileExists(fileToTest) then
-- do nothing
else
return false
end if
end startedExporting
on doneExporting(referenceFiles) -- Checks if QuickTime is done exporting everything
set moviesPath to QTExportPath as text
repeat with thisItem in referenceFiles
set fileToTest to ((the POSIX path of moviesPath) & thisItem & "/Resources/" & thisItem & ".mov")
if FileExists(fileToTest) then
-- do nothing
else
return false
end if
end repeat
end doneExporting
on FileExists(theFile) -- (String) as Boolean
tell application "System Events"
if exists file theFile then
return true
else
if exists folder theFile then
return true
else
return false
end if
end if
end tell
end FileExists
on cleanUpGarbage(referenceFiles)
set moviesPath to QTExportPath as text
set donePath to (QTExportPath as text) & completedFolderName as text
set POSIXMovies to the POSIX path of moviesPath
set POSIXDone to the POSIX path of donePath
repeat with thisItem in referenceFiles
set directoryToClean to (POSIXMovies & thisItem & "/")
set m4vcommand to "find '" & directoryToClean & "' -type f -iname '*m4v' -exec cp -n {} '" & POSIXDone & "' \\;"
set movcommand to "find '" & directoryToClean & "' -type f -iname '*mov' -exec cp -n {} '" & POSIXDone & "' \\;"
do shell script m4vcommand
do shell script movcommand
set thefolder to POSIX file directoryToClean
tell application "Finder"
delete thefolder
end tell
end repeat
end cleanUpGarbage
on count_matches(this_list, this_item)
set the match_counter to 0
repeat with i from 1 to the count of this_list
if item i of this_list is this_item then ¬
set the match_counter to the match_counter + 1
end repeat
return the match_counter
end count_matches
It assumes:
the folder you're starting from has ONLY movie files, AND you want to convert ALL of them.
you have already set up whatever export settings you want in QuickTime by doing one manual export to web
It will export them one at a time. If you want to convert multiple simultaneously, modify the startedExporting method to only check for a folder instead of the .mov file (the .mov file is the last one to generate.)
I need path to the folder that contains cmd file.
With %0 I can get the file name. But how to get the folder name?
c:\temp\test.cmd >> test.cmd
P.S. My current directory != folder of the script.
For the folder name and drive, you can use:
echo %~dp0
You can get a lot more information using different modifiers:
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only
%~nxI - expands %I to a file name and extension only
%~fsI - expands %I to a full path name with short names only
This is a copy paste from the "for /?" command on the prompt.
Related
Top 10 DOS Batch tips (Yes, DOS Batch...) shows batchparams.bat (link to source as a gist):
C:\Temp>batchparams.bat c:\windows\notepad.exe
%~1 = c:\windows\notepad.exe
%~f1 = c:\WINDOWS\NOTEPAD.EXE
%~d1 = c:
%~p1 = \WINDOWS\
%~n1 = NOTEPAD
%~x1 = .EXE
%~s1 = c:\WINDOWS\NOTEPAD.EXE
%~a1 = --a------
%~t1 = 08/25/2005 01:50 AM
%~z1 = 17920
%~$PATHATH:1 =
%~dp1 = c:\WINDOWS\
%~nx1 = NOTEPAD.EXE
%~dp$PATH:1 = c:\WINDOWS\
%~ftza1 = --a------ 08/25/2005 01:50 AM 17920 c:\WINDOWS\NOTEPAD.EXE
The accepted answer is helpful, but it isn't immediately obvious how to retrieve a filename from a path if you are NOT using passed in values. I was able to work this out from this thread, but in case others aren't so lucky, here is how it is done:
#echo off
setlocal enabledelayedexpansion enableextensions
set myPath=C:\Somewhere\Somewhere\SomeFile.txt
call :file_name_from_path result !myPath!
echo %result%
goto :eof
:file_name_from_path <resultVar> <pathVar>
(
set "%~1=%~nx2"
exit /b
)
:eof
endlocal
Now the :file_name_from_path function can be used anywhere to retrieve the value, not just for passed in arguments. This can be extremely helpful if the arguments can be passed into the file in an indeterminate order or the path isn't passed into the file at all.
In order to assign these to variables, be sure not to add spaces in front or after the equals sign:
set filepath=%~dp1
set filename=%~nx1
Then you should have no issues.
In case anyone wants an alternative method...
If it is the last subdirectory in the path, you can use this one-liner:
cd "c:\directory\subdirectory\filename.exe\..\.." && dir /ad /b /s
This would return the following:
c:\directory\subdirectory
The .... drops back to the previous directory.
/ad shows only directories
/b is a bare format listing
/s includes all subdirectories. This is used to get the full path of the directory to print.
I had same problem in my loop where i wanted to extract zip files in the same directory and then delete the zip file. The problem was that 7z requires the output folder, so i had to obtain the folder path of each file. Here is my solution:
FOR /F "usebackq tokens=1" %%i IN (`DIR /S/B *.zip` ) DO (
7z.exe x %%i -aoa -o%%i\..
)
%%i was a full filename path and %ii\.. simply returns the parent folder.
hope it helps.
In case the accepted answer by Wadih didn't work for you, try echo %CD%
This was put together with some edited example cmd
#Echo off
Echo ********************************************************
Echo * ZIP Folder Backup using 7Zip *
Echo * Usage: Source Folder, Destination Drive Letter *
Echo * Source Folder will be Zipped to Destination\Backups *
Echo ********************************************************
Echo off
set year=%date:~-4,4%
set month=%date:~-10,2%
set day=%date:~-7,2%
set hour=%time:~-11,2%
set hour=%hour: =0%
set min=%time:~-8,2%
SET /P src=Source Folder to Backup:
SET source=%src%\*
call :file_name_from_path nam %src%
SET /P destination=Backup Drive Letter:
set zipfilename=%nam%.%year%.%month%.%day%.%hour%%min%.zip
set dest="%destination%:\Backups\%zipfilename%"
set AppExePath="%ProgramFiles(x86)%\7-Zip\7z.exe"
if not exist %AppExePath% set AppExePath="%ProgramFiles%\7-Zip\7z.exe"
if not exist %AppExePath% goto notInstalled
echo Backing up %source% to %dest%
%AppExePath% a -r -tzip %dest% %source%
echo %source% backed up to %dest% is complete!
TIMEOUT 5
exit;
:file_name_from_path <resultVar> <pathVar>
(
set "%~1=%~nx2"
exit /b
)
:notInstalled
echo Can not find 7-Zip, please install it from:
echo http://7-zip.org/
:end
PAUSE
IMHO the simplest yet most powerful method to get the full path of a file is:
Start Notepad
Copy and Paste the following text:
#echo %1 | clip 3
Save the file as "CopyAsPath.bat"
Now you can either
drag a file over that batch
or
copy it into your SendTo menu folder (%USERPROFILE%\AppData\Roaming\Microsoft\Windows\SendTo)
Whether you follow the option 1 or the option 2, one millisecond later you can either
"press Ctrl-V"
or
use "Right Mouse Click -> Paste"
to paste the full path+filename wherever you want.
Simple, powerful, and without using any external Windows tool.