How to run a script
Hope someone can answer this ASAP, I'm on deadline.
I have to convert .cwk files to Appleworks6, and found some great scripts by Hiroto in the AW forum.
However, i dont know how to use them!
copy and paste into script editor? Terminal? And then what? Compile? Run? ????
the confusing thing for me is none of them have the word "tell" in them, which all my research has informed me is how an applescript script reads...
Just (* , etc.
Here is the first part of one:
-- save_AW_as_v6.applescript
Convert files of AppleWorks / ClarisWorks prior to version 6 to AppleWorks 6 files.
v0.1
* Tested with AppleWorks 6.2.4 under OS X 10.6.8.
* AppleWorks 6.2.9 may fail to open old ClarisWorks files, in which case use older version such as AppleWorks 6.2.4.
* Specify property in_place in script, which defines the operation mode, as necessary.
* A log file with time-stamp in name is created on desktop.
* Original file name is always preserved.
Name extension ".cwk" is not added in destination file if it is missing in source file.
This is to avoid possible data loss in case there're file names, e.g., abc and abc.cwk in a source directory.
_main()
on _main()
script o
property in_place : false
true : convert files in place, i.e. files are overwritten,
where original source directory is archived in zip file with time-stamp in name in advance;
false : converted files are saved in destination directory which is specified in a dialogue in script
Thanks, for your time with this, Niel. I really don't want to have to convert them all by hand, so if I can get these to work, it would be beyond wonderful. I'm 2 days past when i told the client I'd have them ready...
Here are all 3 scripts. Cwk to AW6, AW6 to Numbers, AW6 to Pages...i imagine I'll have the same trouble with all of them.
Here's Hiroto's original posting:https://discussions.apple.com/thread/5455245?start=45&tstart=0
--save_AW_as_v6.applescript
Convert files of AppleWorks / ClarisWorks prior to version 6 to AppleWorks 6 files.
v0.3
v0.3 -
changed the logging scheme from post-conversion log:
converted x => y
to pre-conversion log:
converting x => y
so that it can help to identify the last file which had caused the applicaton / script to crash.
v0.2 -
added optional function to inherit creation and modification dates of source files
v0.1 -
initial version
* Tested with AppleWorks 6.2.4 under OS X 10.6.8.
* AppleWorks 6.2.9 may fail to open old ClarisWorks files, in which case use older version such as AppleWorks 6.2.4.
* Specify property in_place in script as necessary.
* Specify property inherit_dates in script as necessary.
* A log file with time-stamp in name is created on desktop.
* Original file name is always preserved.
Name extension ".cwk" is not added in destination file if it is missing in source file.
This is to avoid possible data loss in case there're file names, e.g., abc and abc.cwk in a source directory.
_main()
on _main()
script o
property in_place : true
true : convert files in place, i.e. files are overwritten,
where original source directory is archived in zip file with time-stamp in name in advance;
false : converted files are saved under destination directory which is specified in a dialogue in script
property inherit_dates : true
true : destination file inherits creation date and modification date of source file
false : destination file has creation date and modification date at the time of conversion
property logfile : (path to desktop)'s POSIX path & (do shell script "date +'save_AW_as_v6.log_%Y%m%dT%H%M%S.txt'")
property pp : {}
-- accept source directory (and destination direcotry if in_place is false)
set srcd to (choose folder with prompt "Choose source directory where source files reside.")'s POSIX path
if srcd ends with "/" and (count srcd) > 1 then set srcd to srcd's text 1 thru -2
if not in_place then
repeat
set dstd to (choose folder with prompt "Choose destination directory where to save converted files.")'s POSIX path
if dstd ends with "/" and (count dstd) > 1 then set dstd to dstd's text 1 thru -2
if srcd ≠ dstd then exit repeat
display dialog "Source and destination directories cannot be the same!" with icon stop
end repeat
end if
log_printf(logfile, "conversion started in operation mode: in_place = %s, inherit_dates = %s.\\n", {in_place, inherit_dates})
-- retrieve target files
log_printf(logfile, "scanning files under %s\\n", srcd)
set pp to _match(my is_AW_but_v6, scan_AW_files(srcd))
log_printf(logfile, "found %d file(s) to process.\\n", count my pp)
-- process target files
if (count my pp) > 0 then
if in_place then
-- archive the source directory first (zip file name = srcd_YYYY-MM-DDTHH.MM.SS.zip)
set dst to do shell script "src=" & srcd's quoted form & "
dst=\"${src}_$(date +'%FT%H.%M.%S').zip\"
ditto -ck --keepParent --sequesterRsrc \"$src\" \"$dst\"
echo \"$dst\""
log_printf(logfile, "archived source directory in %s\\n", dst)
repeat with p in my pp
set p to p's contents
log_printf(logfile, "converting %s\\n", p)
save_AW_as_v6(p, p, {inherit_dates:inherit_dates})
end repeat
else
set slen to count srcd
repeat with p in my pp
set p to p's contents
set q to dstd & (p's text (slen + 1) thru -1)
log_printf(logfile, "converting %s => %s\\n", {p, q})
save_AW_as_v6(p, q, {inherit_dates:inherit_dates})
end repeat
end if
end if
-- completion notice
log_printf(logfile, "process completed for total of %d file(s).\\n", count my pp)
tell me
activate
display dialog "Done " & (count my pp) & " file(s)." giving up after 5 with icon note
end tell
end script
tell o to run
end _main
on scan_AW_files(d)
string d : POSIX path of source directory where to start scanning
return list : list of POSIX paths of found files
* query condition is (file name extension = "cwk") OR (file creator type = "BOBO")
script o
property pp : {}
property qq : {}
property rr : {}
tell application "System Events"
tell disk item d
set pp to every folder's POSIX path
repeat with p in my pp
set qq to my scan_AW_files(p's contents)
repeat with q in my qq
set end of my rr to q's contents
end repeat
end repeat
set qq to every file's POSIX path whose name extension = "cwk" or creator type = "BOBO"
repeat with q in my qq
set end of my rr to q's contents
end repeat
end tell
end tell
return my rr's contents
end script
tell o to run
end scan_AW_files
on is_AW_but_v6(f)
string f : POSIX path of source file
return boolean : true if f is AW/CW file of version prior to 6, false otherwise
* matching codition is (byte 1 < 0x06) AND (bytes 5..8 = 'BOBO')
set f to f as POSIX file --as alias
--return (read f from 5 for 4)'s id = {66, 79, 66, 79} and (read f for 1)'s id < 6 -- for 10.5 or later only
considering case
return (read f from 5 for 4) = "BOBO" and (ASCII number (read f for 1)) < 6
end considering
end is_AW_but_v6
on save_AW_as_v6(src, dst, {inherit_dates:inherit_dates})
string src : POSIX path of source file, typically file of AW5 or CW4 etc
string dst : POSIX path of destination file
boolean inherit_dates: true for dst to inherit creation and modification dates of src, false otherwise.
* src may equate to dst, in which case src is overwritten
* intermeditate directories in dst will be created as needed if not present
-- get source alias
set srca to src as POSIX file as alias
-- create temp file
set tmp to do shell script "mktemp /tmp/save_AW_as_v6.XXXXXXXX"
set tmpa to tmp as POSIX file as alias
-- convert to AW6 and save in temp file
tell application "AppleWorks 6"
--activate
set k to count documents
open srca
repeat until (count documents) > k
delay 0.2
end repeat
tell document 1
close saving in tmpa
end tell
end tell
-- wait for the temp file is closed
wait_file_close(tmp)
-- set label of temp file to label of source file -- [1]
repeat 3 times -- max retry
try -- [2]
tell application "Finder"
set lbl to item srca's label index
tell item tmpa
update
set its label index to lbl
end tell
end tell
exit repeat -- exit if no error
delay 0.5 -- wait some time before retry
end try
end repeat
-- inherit creation and modication dates from src to tmp
if inherit_dates then inherit_file_dates(src, tmp)
-- move temp file to destination file (destination directory tree is created as necessary)
do shell script "tmp=" & tmp's quoted form & "; dst=" & dst's quoted form & "
d=${dst%/*}; [[ -d \"$d\" ]] || mkdir -p \"$d\"
mv -f \"$tmp\" \"$dst\""
[1] This is required because AW6 does not preserve the original label when saving file.
[2] Finder is such an unreliable beast that it may fail even after the file is indeed closed.
end save_AW_as_v6
on wait_file_close(f)
string f : POSIX path of file
* wait until f is no longer opened by AppleWorks
do shell script "f=" & f's quoted form & "
while [[ $(lsof -Fc \"$f\") =~ 'AppleWorks' ]]; do sleep 0.3; done"
end wait_file_close
on _match(pat, aa)
handler pat : handler to test elements in aa
list aa : source list
return list : list of every element a of list aa whose pat(a) = true
script o
property |::xx| : aa's contents
property |::yy| : {}
property |::f| : pat
repeat with x in my |::xx|
set x to x's contents
if my |::f|(x) then set end of my |::yy| to x
end repeat
return my |::yy|'s contents
end script
tell o to run
end _match
on log_printf(f, fmt, lst)
string f : POSIX path of log file
string fmt : printf format string
list lst : list of values (if lst is one item list {x}, lst may be x)
* %-26s time-stamp in format %F %T%z is added to the beginning of each entry
local args
set args to "'%-26s'" & fmt's quoted form & " \"$(date +'%F %T%z')\" "
repeat with a in {} & lst
set args to args & (a as string)'s quoted form & space
end repeat
do shell script "printf " & args & " >> " & f's quoted form
end log_printf
on inherit_file_dates(src, dst)
string src : POSIX path of source file
string dst : POSIX path of destination file
* If creation date of src is older than or equal to that of dst,
this will set both creation date and modification date of dst to those of src.
* If creation date of src is newer than that of dst,
this will set only modification date of dst to that of src.
do shell script "src=" & src's quoted form & "; dst=" & dst's quoted form & "
ct=$(stat -f '%SB' -t '%Y%m%d%H%M.%S' \"$src\")
mt=$(stat -f '%Sm' -t '%Y%m%d%H%M.%S' \"$src\")
touch -t $ct \"$dst\" # set creation date (<= current creation date)
touch -mt $mt \"$dst\" # set modification date (>= creation date)"
end inherit_file_dates
[CodeBlockStart:17c5a62c-54d3-4061-ac41-37b7e4ed1ce1][excluded]
--save_AW6_SS_as_Numbers2.applescript
Convert AppleWorks v6 SS (spreadsheet) files to iWork'09's Numbers v2 files
v0.2
v0.2 -
changed the logging scheme from post-conversion log:
converted x => y
to pre-conversion log:
converting x => y
so that it can help to identify the last file which had caused the applicaton / script to crash.
v0.1 -
initial version
* Tested with Numbers 2.0.5 under OS X 10.6.8.
* Specify property in_place in script as necessary.
* Specify property inherit_dates in script as necessary.
* A log file with time-stamp in name is created on desktop.
* Original file name is always preserved except that name extension ".numbers" is added
Note that original name extension (.cwk) is NOT removed and thus, e.g., abc.cwk will be converted to abc.cwk.numbers
This is to avoid possible data loss in case there're file names, e.g., abc and abc.cwk in a source directory.
_main()
on _main()
script o
property in_place : true
true : convert files in place, i.e. converted files are saved in original directories,
where original source directory is archived in zip file with time-stamp in name in advance;
false : converted files are saved under destination directory which is specified in a dialogue in script
property inherit_dates : true
true : destination file inherits creation date and modification date of source file
false : destination file has creation date and modification date at the time of conversion
property ext : ".numbers"
property logfile : (path to desktop)'s POSIX path & (do shell script "date +'save_AW6_SS_as_Numbers4.log_%Y%m%dT%H%M%S.txt'")
property pp : {}
-- accept source directory (and destination direcotry if in_place is false)
set srcd to (choose folder with prompt "Choose source directory where source files reside.")'s POSIX path
if srcd ends with "/" and (count srcd) > 1 then set srcd to srcd's text 1 thru -2
if not in_place then
repeat
set dstd to (choose folder with prompt "Choose destination directory where to save converted files.")'s POSIX path
if dstd ends with "/" and (count dstd) > 1 then set dstd to dstd's text 1 thru -2
if srcd ≠ dstd then exit repeat
display dialog "Source and destination directories cannot be the same!" with icon stop
end repeat
end if
log_printf(logfile, "conversion started in operation mode: in_place = %s, inherit_dates = %s.\\n", {in_place, inherit_dates})
-- retrieve target files
log_printf(logfile, "scanning files under %s\\n", srcd)
set pp to _match(my is_AW_v6_SS, scan_AW_files(srcd))
log_printf(logfile, "found %d file(s) to process.\\n", count my pp)
-- process target files
if (count my pp) > 0 then
if in_place then
-- archive the source directory first (zip file name = srcd_YYYY-MM-DDTHH.MM.SS.zip)
set dst to do shell script "src=" & srcd's quoted form & "
dst=\"${src}_$(date +'%FT%H.%M.%S').zip\"
ditto -ck --keepParent --sequesterRsrc \"$src\" \"$dst\"
echo \"$dst\""
log_printf(logfile, "archived source directory in %s\\n", dst)
repeat with p in my pp
set p to p's contents
set q to p & ext
log_printf(logfile, "converting %s => %s\\n", {p, q})
save_AW6SS_as_Numbers2(p, q, {inherit_dates:inherit_dates})
--do shell script "rm -f " & p's quoted form -- delete the source file [1]
end repeat
else
set slen to count srcd
repeat with p in my pp
set p to p's contents
set q to dstd & (p's text (slen + 1) thru -1) & ext
log_printf(logfile, "converting %s => %s\\n", {p, q})
save_AW6SS_as_Numbers2(p, q, {inherit_dates:inherit_dates})
end repeat
end if
end if
-- completion notice
log_printf(logfile, "process completed for total of %d file(s).\\n", count my pp)
tell me
activate
display dialog "Done " & (count my pp) & " file(s)." giving up after 5 with icon note
end tell
[1] NOT recommended because conversion is not necessarily complete.
end script
tell o to run
end _main
on scan_AW_files(d)
string d : POSIX path of source directory where to start scanning
return list : list of POSIX paths of found files
* query condition is (file name extension = "cwk") OR (file creator type = "BOBO")
script o
property pp : {}
property qq : {}
property rr : {}
tell application "System Events"
tell disk item d
set pp to every folder's POSIX path
repeat with p in my pp
set qq to my scan_AW_files(p's contents)
repeat with q in my qq
set end of my rr to q's contents
end repeat
end repeat
--set qq to every file's POSIX path whose name extension = "cwk" or (creator type = "BOBO" and file type = "CWSS")
set qq to every file's POSIX path whose name extension = "cwk" or creator type = "BOBO"
repeat with q in my qq
set end of my rr to q's contents
end repeat
end tell
end tell
return my rr's contents
end script
tell o to run
end scan_AW_files
on is_AW_v6_SS(f)
string f : POSIX path of source file
return boolean : true if f is AW version 6 WP file, false otherwise
byte[1] = version
byte[5..8] = BOBO
byte[279] (when byte[1] = 0x06) =
0 => draw
1 => word processing
2 => spreadsheet
3 => database
4 => paint
5 => presentation
* byte index is 1-based
set f to f as POSIX file
(* -- 10.5 or later only
return (read f from 5 for 4)'s id = {66, 79, 66, 79} and ¬
(read f for 1)'s id = 6 and ¬
(read f from 279 for 1)'s id = 1
considering case
return (read f from 5 for 4) = "BOBO" and ¬
(ASCII number (read f for 1)) = 6 and ¬
(ASCII number (read f from 279 for 1)) = 2
end considering
end is_AW_v6_SS
on save_AW6SS_as_Numbers2(src, dst, {inherit_dates:inherit_dates})
string src : POSIX path of source file
string dst : POSIX path of destination file
boolean inherit_dates: true for dst to inherit creation and modification dates of src, false otherwise.
* src may equate to dst, in which case src is overwritten
* intermeditate directories in dst will be created as needed if not present
-- get source and destination file
set srcf to src as POSIX file
set dstf to dst as POSIX file
-- open srca in Pages v4 and save it in dstf
tell application "Numbers"
--activate
set k to count documents
open srcf
repeat until (count documents) > k
delay 0.2
end repeat
tell document 1
close saving in dstf
end tell
end tell
-- wait for dst to come into existence
wait_file_exist(dst)
-- set label of destination file to label of source file -- [1]
repeat 3 times -- max retry
try -- [2]
tell application "Finder"
set lbl to item (srcf as alias)'s label index
tell item (dstf as alias)
update
set its label index to lbl
end tell
end tell
exit repeat -- exit if no error
delay 0.5 -- wait some time before retry
end try
end repeat
-- inherit creation and modication dates from src to tmp
if inherit_dates then inherit_file_dates(src, dst)
[1] This is required because Pages does not preserve the original label when saving file.
[2] Finder is such an unreliable beast that it may fail even after the file indeed has come into existence.
end save_AW6SS_as_Numbers2
on wait_file_exist(f)
string f : POSIX path of file
* wait until f comes into existence
do shell script "f=" & f's quoted form & "
until [[ -e \"$f\" ]]; do sleep 0.3; done"
end wait_file_exist
on _match(pat, aa)
handler pat : handler to test elements in aa
list aa : source list
return list : list of every element a of list aa whose pat(a) = true
script o
property |::xx| : aa's contents
property |::yy| : {}
property |::f| : pat
repeat with x in my |::xx|
set x to x's contents
if my |::f|(x) then set end of my |::yy| to x
end repeat
return my |::yy|'s contents
end script
tell o to run
end _match
on log_printf(f, fmt, lst)
string f : POSIX path of log file
string fmt : printf format string
list lst : list of values (if lst is one item list {x}, lst may be x)
* %-26s time-stamp in format %F %T%z is added to the beginning of each entry
local args
set args to "'%-26s'" & fmt's quoted form & " \"$(date +'%F %T%z')\" "
repeat with a in {} & lst
set args to args & (a as string)'s quoted form & space
end repeat
do shell script "printf " & args & " >> " & f's quoted form
end log_printf
on inherit_file_dates(src, dst)
string src : POSIX path of source file
string dst : POSIX path of destination file
* If creation date of src is older than or equal to that of dst,
this will set both creation date and modification date of dst to those of src.
* If creation date of src is newer than that of dst,
this will set only modification date of dst to that of src.
do shell script "src=" & src's quoted form & "; dst=" & dst's quoted form & "
ct=$(stat -f '%SB' -t '%Y%m%d%H%M.%S' \"$src\")
mt=$(stat -f '%Sm' -t '%Y%m%d%H%M.%S' \"$src\")
touch -t $ct \"$dst\" # set creation date (<= current creation date)
touch -mt $mt \"$dst\" # set modification date (>= creation date)"
end inherit_file_dates
[CodeBlockEnd:17c5a62c-54d3-4061-ac41-37b7e4ed1ce1]
[CodeBlockStart:e2c458b8-4771-44db-8dab-e6447418de9f][excluded]
--save_AW6_WP_as_Pages4.applescript
Convert AppleWorks v6 WP (word processing) files to iWork'09's Pages v4 files
v0.2
v0.2 -
changed the logging scheme from post-conversion log:
converted x => y
to pre-conversion log:
converting x => y
so that it can help to identify the last file which had caused the applicaton / script to crash.
v0.1 -
initial version
* Tested with Pages 4.0.5 under OS X 10.6.8.
* Specify property in_place in script as necessary.
* Specify property inherit_dates in script as necessary.
* A log file with time-stamp in name is created on desktop.
* Original file name is always preserved except that name extension ".pages" is added
Note that original name extension (.cwk) is NOT removed and thus, e.g., abc.cwk will be converted to abc.cwk.pages
This is to avoid possible data loss in case there're file names, e.g., abc and abc.cwk in a source directory.
_main()
on _main()
script o
property in_place : true
true : convert files in place, i.e. converted files are saved in original directories,
where original source directory is archived in zip file with time-stamp in name in advance;
false : converted files are saved under destination directory which is specified in a dialogue in script
property inherit_dates : true
true : destination file inherits creation date and modification date of source file
false : destination file has creation date and modification date at the time of conversion
property ext : ".pages"
property logfile : (path to desktop)'s POSIX path & (do shell script "date +'save_AW6_WP_as_Pages4.log_%Y%m%dT%H%M%S.txt'")
property pp : {}
-- accept source directory (and destination direcotry if in_place is false)
set srcd to (choose folder with prompt "Choose source directory where source files reside.")'s POSIX path
if srcd ends with "/" and (count srcd) > 1 then set srcd to srcd's text 1 thru -2
if not in_place then
repeat
set dstd to (choose folder with prompt "Choose destination directory where to save converted files.")'s POSIX path
if dstd ends with "/" and (count dstd) > 1 then set dstd to dstd's text 1 thru -2
if srcd ≠ dstd then exit repeat
display dialog "Source and destination directories cannot be the same!" with icon stop
end repeat
end if
log_printf(logfile, "conversion started in operation mode: in_place = %s, inherit_dates = %s.\\n", {in_place, inherit_dates})
-- retrieve target files
log_printf(logfile, "scanning files under %s\\n", srcd)
set pp to _match(my is_AW_v6_WP, scan_AW_files(srcd))
log_printf(logfile, "found %d file(s) to process.\\n", count my pp)
-- process target files
if (count my pp) > 0 then
if in_place then
-- archive the source directory first (zip file name = srcd_YYYY-MM-DDTHH.MM.SS.zip)
set dst to do shell script "src=" & srcd's quoted form & "
dst=\"${src}_$(date +'%FT%H.%M.%S').zip\"
ditto -ck --keepParent --sequesterRsrc \"$src\" \"$dst\"
echo \"$dst\""
log_printf(logfile, "archived source directory in %s\\n", dst)
repeat with p in my pp
set p to p's contents
set q to p & ext
log_printf(logfile, "converting %s => %s\\n", {p, q})
save_AW6WP_as_Pages4(p, q, {inherit_dates:inherit_dates})
--do shell script "rm -f " & p's quoted form -- delete the source file [1]
end repeat
else
set slen to count srcd
repeat with p in my pp
set p to p's contents
set q to dstd & (p's text (slen + 1) thru -1) & ext
log_printf(logfile, "converting %s => %s\\n", {p, q})
save_AW6WP_as_Pages4(p, q, {inherit_dates:inherit_dates})
end repeat
end if
end if
-- completion notice
log_printf(logfile, "process completed for total of %d file(s).\\n", count my pp)
tell me
activate
display dialog "Done " & (count my pp) & " file(s)." giving up after 5 with icon note
end tell
[1] NOT recommended because conversion is not necessarily complete.
end script
tell o to run
end _main
on scan_AW_files(d)
string d : POSIX path of source directory where to start scanning
return list : list of POSIX paths of found files
* query condition is (file name extension = "cwk") OR (file creator type = "BOBO")
script o
property pp : {}
property qq : {}
property rr : {}
tell application "System Events"
tell disk item d
set pp to every folder's POSIX path
repeat with p in my pp
set qq to my scan_AW_files(p's contents)
repeat with q in my qq
set end of my rr to q's contents
end repeat
end repeat
--set qq to every file's POSIX path whose name extension = "cwk" or (creator type = "BOBO" and file type = "CWWP")
set qq to every file's POSIX path whose name extension = "cwk" or creator type = "BOBO"
repeat with q in my qq
set end of my rr to q's contents
end repeat
end tell
end tell
return my rr's contents
end script
tell o to run
end scan_AW_files
on is_AW_v6_WP(f)
string f : POSIX path of source file
return boolean : true if f is AW version 6 WP file, false otherwise
byte[1] = version
byte[5..8] = BOBO
byte[279] (when byte[1] = 0x06) =
0 => draw
1 => word processing
2 => spreadsheet
3 => database
4 => paint
5 => presentation
* byte index is 1-based
set f to f as POSIX file
(* -- 10.5 or later only
return (read f from 5 for 4)'s id = {66, 79, 66, 79} and ¬
(read f for 1)'s id = 6 and ¬
(read f from 279 for 1)'s id = 1
considering case
return (read f from 5 for 4) = "BOBO" and ¬
(ASCII number (read f for 1)) = 6 and ¬
(ASCII number (read f from 279 for 1)) = 1
end considering
end is_AW_v6_WP
on save_AW6WP_as_Pages4(src, dst, {inherit_dates:inherit_dates})
string src : POSIX path of source file
string dst : POSIX path of destination file
boolean inherit_dates: true for dst to inherit creation and modification dates of src, false otherwise.
* src may equate to dst, in which case src is overwritten
* intermeditate directories in dst will be created as needed if not present
-- get source and destination file
set srcf to src as POSIX file
set dstf to dst as POSIX file
-- open srca in Pages v4 and save it in dstf
tell application "Pages"
--activate
set k to count documents
open srcf
repeat until (count documents) > k
delay 0.2
end repeat
tell document 1
close saving in dstf
end tell
end tell
-- wait for dst to come into existence
wait_file_exist(dst)
-- set label of destination file to label of source file -- [1]
repeat 3 times -- max retry
try -- [2]
tell application "Finder"
set lbl to item (srcf as alias)'s label index
tell item (dstf as alias)
update
set its label index to lbl
end tell
end tell
exit repeat -- exit if no error
delay 0.5 -- wait some time before retry
end try
end repeat
-- inherit creation and modication dates from src to tmp
if inherit_dates then inherit_file_dates(src, dst)
[1] This is required because Pages does not preserve the original label when saving file.
[2] Finder is such an unreliable beast that it may fail even after the file indeed has come into existence.
end save_AW6WP_as_Pages4
on wait_file_exist(f)
string f : POSIX path of file
* wait until f comes into existence
do shell script "f=" & f's quoted form & "
until [[ -e \"$f\" ]]; do sleep 0.3; done"
end wait_file_exist
on _match(pat, aa)
handler pat : handler to test elements in aa
list aa : source list
return list : list of every element a of list aa whose pat(a) = true
script o
property |::xx| : aa's contents
property |::yy| : {}
property |::f| : pat
repeat with x in my |::xx|
set x to x's contents
if my |::f|(x) then set end of my |::yy| to x
end repeat
return my |::yy|'s contents
end script
tell o to run
end _match
on log_printf(f, fmt, lst)
string f : POSIX path of log file
string fmt : printf format string
list lst : list of values (if lst is one item list {x}, lst may be x)
* %-26s time-stamp in format %F %T%z is added to the beginning of each entry
local args
set args to "'%-26s'" & fmt's quoted form & " \"$(date +'%F %T%z')\" "
repeat with a in {} & lst
set args to args & (a as string)'s quoted form & space
end repeat
do shell script "printf " & args & " >> " & f's quoted form
end log_printf
on inherit_file_dates(src, dst)
string src : POSIX path of source file
string dst : POSIX path of destination file
* If creation date of src is older than or equal to that of dst,
this will set both creation date and modification date of dst to those of src.
* If creation date of src is newer than that of dst,
this will set only modification date of dst to that of src.
do shell script "src=" & src's quoted form & "; dst=" & dst's quoted form & "
ct=$(stat -f '%SB' -t '%Y%m%d%H%M.%S' \"$src\")
mt=$(stat -f '%Sm' -t '%Y%m%d%H%M.%S' \"$src\")
touch -t $ct \"$dst\" # set creation date (<= current creation date)
touch -mt $mt \"$dst\" # set modification date (>= creation date)"
end inherit_file_dates
Similar Messages
-
How to run a script on Oracle server from isqlplus
Hi I am trying to run a script on my workstation from Oracle server through isqlplus workarea. I entered following command and get the following error. i have enabled isqlplus URL by editing web.xml file already. Can please someone help how to run the script?
@http://myaixserver.com:5560/scripts/Databasestartupstages.sql;
SP2-0920: HTTP error 'page not found (505)' on attempt to open URLSo far, you haven't specified your rdbms version and isqlplus behaved differently on a 9iR1, 9iR2 from the one release on 10gR1/R2. on 9i it was a servlet based on a JServ servlet executor machine, meanwhile on 10g it is a J2EE compliant application deployed on an OC4J container, so configuration is different.
You may want to take a look at these references -->
* Starting iSQL*Plus from a URL
* Creating Reports using iSQL*Plus
~ Madrid -
How to run a script from Calculation Manager
Hi All,
I would like to know how to run a script made by using Calculation Manager. I have converted a simple rule script which has just one statement(HS.EXP "A#Sales = 100") in "Sub Calculate()" by using FMRulesMigrator.exe and then imported, deployed to an application. when I execute "Calculate" from a Data Grid, the rule didn't take effect to application data. If I load the script by using classic rule editor, it works fine.
Is there anything I have to know to run a rule script which is made by using Calculation Manager?
Thanks in advance.
CY.Hi,
Refer the following the link for calling logic from new custom buttons using VBA.
https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/f085dd92-a40c-2c10-dcb1-a7c24476b23a
hpe this ll help.
thnks. -
Applescript: How to run a script once upon logon for multiple users
I'm deploying a NetRestore image to about 150 Macs which will be using Active Directory and I've designed a custom default user for each new user. However, our system requires a specialized certificate that has to be installed on the local login.keychain for each user otherwise network connectivity is impacted.
I've tried to use the security command through Terminal to install the certificate, but no matter what combination of commands, I cannot seem to get that to work properly even with an already-created user. While it will often say it's installed, the cert will not actually show up in the login keychain in Keychain Access. And the network connectivity is still impacted.
So instead, I created a brief AppleScript that just gives the user brief instructions to click "Add" on the prompt for which Keychain to add the cert and then "Always Trust" for the "This cert is not verified" prompt. Then it launches Keychain Access. Originally, I was going to have it actually click the buttons for the user, but I realized trying to get the whole Accessibility apps and assitive devices to work on every new user would be a nightmare.
I created the script on another 10.9 Mac using Automator to make it an actual application. I've used the instructions in OS X: Using AppleScript with Accessibility and Security features in Mavericks to sign it and I'm using root to move it from its network location into the Applications folder. I've adjusted the permissions to allow all Admin users to r/w (along with everyone else). To the root user, it shows as a usable application, but every other user on the Mac sees it as damaged/incomplete.
What I want to do is add it to the default Login Items, so I can run the final AppleScript command to simply remove the login items listing. That way I don't need to worry about it running again, but it's still available for the next user to sign onto the deployed Mac.
I know it's a little convoluted, but this is the final piece to the NetRestore deployment I've been working on for months. Any suggestions on how to make this work (or even a completely different solution) would be greatly appreciated.
Here was the original shell script in case you're curious.
#!/bin/bash
## Prompt for current user admin for use in Certificate Install
while :; do # Loop until valid input is entered or Cancel is pressed.
localpass=$(osascript -e 'Tell application "System Events" to display dialog "Enter your password for Lync Setup:" default answer "" with hidden answer' -e 'text returned of result' 2>/dev/null)
if (( $? )); then exit 1; fi # Abort, if user pressed Cancel.
localpass=$(echo -n "$localpass" | sed 's/^ *//' | sed 's/ *$//') # Trim leading and trailing whitespace.
if [[ -z "$localpass" ]]; then
# The user left the password field blank.
osascript -e 'Tell application "System Events" to display alert "You must enter the local user password; please try again." as warning' >/dev/null
# Continue loop to prompt again.
else
# Valid input: exit loop and continue.
break
fi
done
echo $localpass | sudo security import /'StartupFiles'/bn-virtual.crt ~/Library/Keychain/login.keychain
osascript -e 'tell Application "System Events" to delete every login item whose name is "LyncCert"
And this is the AppleScript itself. (I used the \ to make it easier to read. The first line is actually one complete command)
display dialog "Click OK to start installing Mac Network Certificate." & return & return & \
"In the following prompts, click the 'Add' then 'Always Trust'." & return & return & \
After you have clicked 'Always Trust', quit Keychain Access." default button 1 with title \
"Mac Network Certificate Install"
activate application "Keychain Access"
tell application "Finder" to open POSIX file "/StartupFiles/bn-virtualcar.crt"
tell application "System Events" to delete login item "Lync-AppleScript"
end
Thank you for your help!I have run into this same issue. Are you trying to run the script one time as a new user logs in or everytime a user logs in?
-
How to run multiple scripts in sql*plus?
I would like to run 2 scripts in sql*plus, how do I do this? I tried the following, but it won't run.
create table student_new
AS
select *
from student
insert into student_new
(last_name, first_name
values
(Crop, Jenny)
The above are the two scripts I want to run, what am I doing wrong.
ThanksDo you have a solution to run multiple scripts continuosly, one after the other as one script.
Say I have file1.sql file2.sql, file3.sql.
I want to create a script run.sql, where this will run file1.sql,file2.sql,file3.sql one after other without any one running one after the other like follows:
run.sql should have
begin
@file1.sql
@file2.sql
@file3.sql
dbms_output.put_line(select sysdate from dual);
end;
If I run run.sql all the three scripts should be executed successfully and then display the current time . All these files have update statements(50,000 updates each file).
Very urgetn. Can some one hlpe, please.
Thanks in advance. -
How to run Powershell script (function) through Windows Task Schduler ??
Hello All,
i have Powershell script which is created as a function. I have to give parameters to run the script. And it is working fine. Now i want to run this script through windows task scheduler but it is not working. I dont know how to call powershell function
through task scheduler.
From command line i run it like this:
. c:\script\Get-ServiceStatusReport.ps1
dir function:get-service*
Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
In windows Task scheduler I am giving this: it runs but i dont receive any output :
Program/Script:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Parameter:
-file ". 'Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk'"
Please HELP !!!Thanks for the reply:
The script is already saved as Get-ServiceStatusReport.ps1 .
On powershell it does not run like .\Get-ServiceStatusReport.ps1 (parameter).
But i have to call it as function:
Like this:
Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
As you said:
I tried to run it like this:
Program/Script:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Parameter:
-file "c:\script\Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk'"
But its not working , on scheduler its giving error: (0xFFFD0000)
Please HELP !!!
WHOLE SCRIPT:
function Get-ServiceStatusReport
param(
[String]$ComputerList,[String[]]$includeService,[String]$To,[String]$From,[string]$SMTPMail
$script:list = $ComputerList
$ServiceFileName= "c:\ServiceFileName.htm"
New-Item -ItemType file $ServiceFilename -Force
# Function to write the HTML Header to the file
Function writeHtmlHeader
param($fileName)
$date = ( get-date ).ToString('yyyy/MM/dd')
Add-Content $fileName "<html>"
Add-Content $fileName "<head>"
Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"
Add-Content $fileName '<title>Service Status Report </title>'
add-content $fileName '<STYLE TYPE="text/css">'
add-content $fileName "<!--"
add-content $fileName "td {"
add-content $fileName "font-family: Tahoma;"
add-content $fileName "font-size: 11px;"
add-content $fileName "border-top: 1px solid #999999;"
add-content $fileName "border-right: 1px solid #999999;"
add-content $fileName "border-bottom: 1px solid #999999;"
add-content $fileName "border-left: 1px solid #999999;"
add-content $fileName "padding-top: 0px;"
add-content $fileName "padding-right: 0px;"
add-content $fileName "padding-bottom: 0px;"
add-content $fileName "padding-left: 0px;"
add-content $fileName "}"
add-content $fileName "body {"
add-content $fileName "margin-left: 5px;"
add-content $fileName "margin-top: 5px;"
add-content $fileName "margin-right: 0px;"
add-content $fileName "margin-bottom: 10px;"
add-content $fileName ""
add-content $fileName "table {"
add-content $fileName "border: thin solid #000000;"
add-content $fileName "}"
add-content $fileName "-->"
add-content $fileName "</style>"
Add-Content $fileName "</head>"
Add-Content $fileName "<body>"
add-content $fileName "<table width='100%'>"
add-content $fileName "<tr bgcolor='#CCCCCC'>"
add-content $fileName "<td colspan='4' height='25' align='center'>"
add-content $fileName "<font face='tahoma' color='#003399' size='4'><strong>Service Stauts Report - $date</strong></font>"
add-content $fileName "</td>"
add-content $fileName "</tr>"
add-content $fileName "</table>"
# Function to write the HTML Header to the file
Function writeTableHeader
param($fileName)
Add-Content $fileName "<tr bgcolor=#CCCCCC>"
Add-Content $fileName "<td width='10%' align='center'>ServerName</td>"
Add-Content $fileName "<td width='50%' align='center'>Service Name</td>"
Add-Content $fileName "<td width='10%' align='center'>status</td>"
Add-Content $fileName "</tr>"
Function writeHtmlFooter
param($fileName)
Add-Content $fileName "</body>"
Add-Content $fileName "</html>"
Function writeDiskInfo
param($filename,$Servername,$name,$Status)
if( $status -eq "Stopped")
Add-Content $fileName "<tr>"
Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$servername</td>"
Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$name</td>"
Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$Status</td>"
Add-Content $fileName "</tr>"
else
Add-Content $fileName "<tr>"
Add-Content $fileName "<td >$servername</td>"
Add-Content $fileName "<td >$name</td>"
Add-Content $fileName "<td >$Status</td>"
Add-Content $fileName "</tr>"
writeHtmlHeader $ServiceFileName
Add-Content $ServiceFileName "<table width='100%'><tbody>"
Add-Content $ServiceFileName "<tr bgcolor='#CCCCCC'>"
Add-Content $ServiceFileName "<td width='100%' align='center' colSpan=3><font face='tahoma' color='#003399' size='2'><strong> Service Details</strong></font></td>"
Add-Content $ServiceFileName "</tr>"
writeTableHeader $ServiceFileName
#Change value of the following parameter as needed
$InlcudeArray=@()
#List of programs to exclude
#$InlcudeArray = $inlcudeService
Foreach($ServerName in (Get-Content $script:list))
$service = Get-Service -ComputerName $servername
if ($Service -ne $NULL)
foreach ($item in $service)
#$item.DisplayName
Foreach($include in $includeService)
write-host $inlcude
if(($item.serviceName).Contains($include) -eq $TRUE)
Write-Host $item.MachineName $item.name $item.Status
writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Status
Add-Content $ServiceFileName "</table>"
writeHtmlFooter $ServiceFileName
function Validate-IsEmail ([string]$Email)
return $Email -match "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
Function sendEmail
param($from,$to,$subject,$smtphost,$htmlFileName)
[string]$receipients="$to"
$body = Get-Content $htmlFileName
$body = New-Object System.Net.Mail.MailMessage $from, $receipients, $subject, $body
$body.isBodyhtml = $true
$smtpServer = $MailServer
$smtp = new-object Net.Mail.SmtpClient($smtphost)
$validfrom= Validate-IsEmail $from
if($validfrom -eq $TRUE)
$validTo= Validate-IsEmail $to
if($validTo -eq $TRUE)
$smtp.UseDefaultCredentials = $true;
$smtp.Send($body)
write-output "Email Sent!!"
else
write-output "Invalid entries, Try again!!"
$date = ( get-date ).ToString('yyyy/MM/dd')
sendEmail -from $From -to $to -subject "Service Status - $Date" -smtphost $SMTPMail -htmlfilename $ServiceFilename -
Reg: How to Run a Script File in WebLogic Server 10.3.3
Hi WebLogic Experts,
In our project we are using WebLogic Serve 10.3.3. I need to run one script file. could you please suggest me where should i need to place that script file in WebLogic Server 10.3.3 and How to run & stop that Script file.?
please experts i waiting for your's reply..
Thanks & Regards,
Induja..1. You can put a command line into startWebLogic.sh to start your script file.
2. In your proyect you can create a java class to run the script file.
3. You can create a java class to run the script file an setup it like a startup class into weblogic server.
4. You can create a java class to run the script file an setup it like a job scheduler into weblogic server.
In what time you need run this script file? -
How to Run 2 Scripts simultaneously:PlayQuicktimeMovieWhileSpeechRecognitio
Basicallly i want to make an interactive game using QT movies and Speechrecognition to control what happens, loading different video clips, changing the speed of the movie while it's playing, playing sounds according to what happens.
So i don't know if i need 2 or 3 scripts runing simultaneously.
But anyways, how would you do it?
Do you need to have one parent script? And if so, how would you do it.. how do you run child scripts within the parent script
This is my basic idea , will it work:
PARENT SCRIPT
-Set GameALIVE to true
Repeat while GameALIVE is true
run GAMESPEECHRECOGNITIONScriptTHat just listens for commands
run Script that plays and controls QT Movies based on what the GAMESPEECHRECOGNITION script gets as input
end true
END PARENT SCRIPT
That's my idea but i have no clue how to do itI've been waiting for a dualhead2go DP edition too. Arrived today. Just playing with it.
I'd hand on for the Dualhead2Go, that is if you haven't got it already. It's a really nice bit of kit. I'm currently running an inbuilt display and two samsung T260 with resolutions of 1920 by 1200 each as well as the inbuilt display. I haven't yet tried switching to the lower spec graphics card in my MBP but with this one it is working beautifully. I can't imagine a USB external graphics card being anywhere near as good. -
[solved] How to run a script on logout?
I've just migrated from ubuntu and so far I'm really happy with Arch. GNU/Linux really is easier to 'get' with Arch. I've been able to overcome all problems so far with reading previous posts or searching for it by other means, yet this obviously elementary broblem still defies solution.
- How do I run a script on logout?
What I want to do on logout is to run 'fusermount -u ~/mounted-dir/', where 'mounted-dir' holds media from my account on another host. I have it set up so that /etc/profile runs ~/.login which in turn runs 'sshfs [email protected]:~/media/ ~/mounted-dir/ -o sshfs_sync -o reconnect'.
- Is this a reasonable way of Getting Things Done?
I suspect (as I always do) that there might be a way these things are supposed to be done, this not being it.
Last edited by pooflinger (2007-10-05 10:05:29)pooflinger wrote:
_adam_ wrote:
the problem with .bash_logout is it will run whenever you exit a bash instance.
are you using a desktop environment? do you just want this to happen prior to shutdown? or when you actually log out?
I pretty sure that .bash_logout only runs if $SHELL is /bin/bash when you log out. I want this to happen when I actually log out.
yeah, sorry, i forgot its only executed when a login shell is used. -
Powershell: how to run vbs script with switches.
Background: To remove a specific service, I usually log into a server, go to path c$\Program files\HP... find a specific vbs, and run it using CMD.exe.
Now, I'm new to powershell, so I'm looking into automating this job. When I use CMD, I run cscript path\serviceinstall.vbs
-r.
How do I add cscript switches to powershell?
IF
((test-path -path "servername\C$\Program Files\...") -eq "true")
invoke-command -scriptblock ""servername\C$\Program Files\...\serviceinstall.vbs -r?1. You cannot run VBS as a scriptblock.
2. If youactually were to have read the full help ypu would have seen how to use the command.
3. Given you initial questin and the vague answers you gave there is nothing any could do to help you.
If you do not give accurate information you will not likely get answers that are helpful.
I recommend starting at the beginning and learning PowerShell basics. If you had done that you would know that a script block is not a quoted string with vbscript in it or the path to a file.
When working with any technology it is important to read the instructions carefully. It is also useful to knowhow to do basic research on the technology you are trying to learn.
There are 15 examples in PowerShell V2 for Invoke-Command. Here they are as captured directly from PowerShell V2. (The is no update-help on V2. All help is built in.)
-------------------------- EXAMPLE 1 --------------------------
C:\PS>invoke-command -filepath c:\scripts\test.ps1 -computerName Server01
Disks: C:, D:, E:
Status: Warning, Normal, Normal
Description
This command runs the Test.ps1 script on the Server01 computer.
The command uses the FilePath parameter to specify a script that is located on the local computer. The script runs
on the remote computer and the results are returned to the local computer.
-------------------------- EXAMPLE 2 --------------------------
C:\PS>invoke-command -computername server01 -credential domain01\user01 -scriptblock {get-culture}
Description
This command runs a Get-Culture command on the Server01 remote computer.
It uses the ComputerName parameter to specify the computer name and the Credential parameter to run the command in
the security context of "Domain01\User01," a user with permission to run commands. It uses the ScriptBlock paramete
r to specify the command to be run on the remote computer.
In response, Windows PowerShell displays a dialog box that requests the password and an authentication method for t
he User01 account. It then runs the command on the Server01 computer and returns the result.
-------------------------- EXAMPLE 3 --------------------------
C:\PS>$s = new-pssession -computername server02 -credential domain01\user01
C:\PS> invoke-command -session $s -scriptblock {get-culture}
Description
This example runs the same "Get-Culture" command in a session (a persistent connection) on the Server02 remote comp
uter. Typically, you create a session only when you are running a series of commands on the remote computer.
The first command uses the New-PSSession cmdlet to create a session on the Server02 remote computer. Then, it saves
the session in the $s variable.
The second command uses the Invoke-Command cmdlet to run the Get-Culture command on Server02. It uses the Session p
arameter to specify the session saved in the $s variable.
In response, Windows PowerShell runs the command in the session on the Server02 computer.
-------------------------- EXAMPLE 4 --------------------------
C:\PS>invoke-command -computername Server02 -scriptblock {$p = get-process powershell}
C:\PS> invoke-command -computername Server02 -scriptblock {$p.virtualmemorysize}
C:\PS>
C:\PS> $s = new-pssession -computername Server02
C:\PS> invoke-command -session $s -scriptblock {$p = get-process powershell}
C:\PS> invoke-command -session $s -scriptblock {$p.virtualmemorysize}
17930240
Description
This example compares the effects of using ComputerName and Session parameters of Invoke-Command. It shows how to u
se a session to run a series of commands that share the same data.
The first two commands use the ComputerName parameter of Invoke-Command to run commands on the Server02 remote comp
uter. The first command uses the Get-Process command to get the PowerShell process on the remote computer and to sa
ve it in the $p variable. The second command gets the value of the VirtualMemorySize property of the PowerShell pro
cess.
The first command succeeds. But, the second command fails because when you use the ComputerName parameter, Windows
PowerShell creates a connection just to run the command. Then, it closes the connection when the command is complet
e. The $p variable was created in one connection, but it does not exist in the connection created for the second co
mmand.
The problem is solved by creating a session (a persistent connection) on the remote computer and by running both of
the related commands in the same session.
The third command uses the New-PSSession cmdlet to create a session on the Server02 computer. Then it saves the ses
sion in the $s variable. The fourth and fifth commands repeat the series of commands used in the first set, but in
this case, the Invoke-Command command uses the Session parameter to run both of the commands in the same session.
In this case, because both commands run in the same session, the commands succeed, and the $p value remains active
in the $s session for later use.
-------------------------- EXAMPLE 5 --------------------------
C:\PS>$command = { get-eventlog -log "windows powershell" | where {$_.message -like "*certificate*"} }
C:\PS> invoke-command -computername S1, S2 -scriptblock $command
Description
This example shows how to enter a command that is saved in a local variable.
When the entire command is saved in a local variable, you can specify the variable as the value of the ScriptBlock
parameter. You do not have to use the "param" keyword or the ArgumentList variable to submit the value of the local
variable.
The first command saves a Get-Eventlog command in the $command variable. The command is formatted as a script block
The second command uses the Invoke-Command cmdlet to run the command in $command on the S1 and S2 remote computers.
-------------------------- EXAMPLE 6 --------------------------
C:\PS>invoke-command -computername server01, server02, TST-0143, localhost -configurationname MySession.PowerShell
-scriptblock {get-eventlog "windows powershell"}
Description
This example demonstrates how to use the Invoke-Command cmdlet to run a single command on multiple computers.
The command uses the ComputerName parameter to specify the computers. The computer names are presented in a comma-s
eparated list. The list of computers includes the "localhost" value, which represents the local computer.
The command uses the ConfigurationName parameter to specify an alternate session configuration for Windows PowerShe
ll and the ScriptBlock parameter to specify the command.
In this example, the command in the script block gets the events in the Windows PowerShell event log on each remote
computer.
-------------------------- EXAMPLE 7 --------------------------
C:\PS>$version = invoke-command -computername (get-content machines.txt) -scriptblock {(get-host).version}
Description
This command gets the version of the Windows PowerShell host running on 200 remote computers.
Because only one command is run, it is not necessary to create persistent connections (sessions) to each of the com
puters. Instead, the command uses the ComputerName parameter to indicate the computers.
The command uses the Invoke-Command cmdlet to run a Get-Host command. It uses dot notation to get the Version prope
rty of the Windows PowerShell host.
To specify the computers, it uses the Get-Content cmdlet to get the contents of the Machine.txt file, a file of com
puter names.
These commands run synchronously (one at a time). When the commands complete, the output of the commands from all o
f the computers is saved in the $version variable. The output includes the name of the computer from which the data
originated.
-------------------------- EXAMPLE 8 --------------------------
C:\PS>$s = new-pssession -computername Server01, Server02
C:\PS> invoke-command -session $s -scriptblock {get-eventlog system} -AsJob
Id Name State HasMoreData Location Command
1 Job1 Running True Server01,Server02 get-eventlog system
C:\PS> $j = Get-Job
C:\PS> $j | format-list -property *
HasMoreData : True
StatusMessage :
Location : Server01,Server02
Command : get-eventlog system
JobStateInfo : Running
Finished : System.Threading.ManualResetEvent
InstanceId : e124bb59-8cb2-498b-a0d2-2e07d4e030ca
Id : 1
Name : Job1
ChildJobs : {Job2, Job3}
Output : {}
Error : {}
Progress : {}
Verbose : {}
Debug : {}
Warning : {}
StateChanged :
C:\PS> $results = $j | Receive-Job
Description
These commands run a background job on two remote computers. Because the Invoke-Command command uses the AsJob para
meter, the commands run on the remote computers, but the job actually resides on the local computer and the results
are transmitted to the local computer.
The first command uses the New-PSSession cmdlet to create sessions on the Server01 and Server02 remote computers.
The second command uses the Invoke-Command cmdlet to run a background job in each of the sessions. The command uses
the AsJob parameter to run the command as a background job. This command returns a job object that contains two ch
ild job objects, one for each of the jobs run on the two remote computers.
The third command uses a Get-Job command to save the job object in the $j variable.
The fourth command uses a pipeline operator (|) to send the value of the $j variable to the Format-List cmdlet, whi
ch displays all properties of the job object in a list.
The fifth command gets the results of the jobs. It pipes the job object in $j to the Receive-Job cmdlet and stores
the results in the $results variable.
-------------------------- EXAMPLE 9 --------------------------
C:\PS>$MWFO-LOg = Microsoft-Windows-Forwarding/Operational
C:\PS> invoke-command -computername server01 -scriptblock {param($log, $num) get-eventlog -logname $log -newest $nu
m} -ArgumentList $MWFO-log, 10
Description
This example shows how to include the values of local variables in a command run on a remote computer.
The first command saves the name of the Microsoft-Windows-Forwarding/Operational event log in the $MWFO-Log variabl
e.
The second command uses the Invoke-Command cmdlet to run a Get-EventLog command on the Server01 remote computer tha
t gets the 10 newest events from the Microsoft-Windows-Forwarding/Operational event log on Server01.
This command uses the "param" keyword to create two variables, $log and $num, that are used as placeholders in the
Get-EventLog command. These placeholders have arbitrary names that do not need to match the names of the local vari
ables that supply their values.
The values of the ArgumentList parameter demonstrate the two different ways to specify values in the argument list.
The value of the $log placeholder is the $MFWO-Log variable, which is defined in the first command. The value of t
he $num variable is 10.
Before the command is sent to the remote computer, the variables are replaced with the specified values.
-------------------------- EXAMPLE 10 --------------------------
C:\PS>invoke-command -computername S1, S2 -scriptblock {get-process powershell}
PSComputerName Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
S1 575 15 45100 40988 200 4.68 1392 powershell
S2 777 14 35100 30988 150 3.68 67 powershell
C:\PS> invoke-command -computername S1, S2 -scriptblock {get-process powershell} -HideComputerName
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
575 15 45100 40988 200 4.68 1392 powershell
777 14 35100 30988 150 3.68 67 powershell
Description
This example shows the effect of using the HideComputerName parameter of Invoke-Command.
The first two commands use the Invoke-Command cmdlet to run a Get-Process command for the PowerShell process. The o
utput of the first command includes the PsComputerName property, which contains the name of the computer on which t
he command ran. The output of the second command, which uses the HideComputerName parameter, does not include the P
sComputerName column.
Using the HideComputerName parameter does not change the object. You can still use the Format cmdlets to display th
e PsComputerName property of any of the affected objects.
-------------------------- EXAMPLE 11 --------------------------
C:\PS>invoke-command -comp (get-content servers.txt) -filepath c:\scripts\sample.ps1 -argumentlist Process, Service
Description
This example uses the Invoke-Command cmdlet to run the Sample.ps1 script on all of the computers listed in the Serv
ers.txt file. The command uses the FilePath parameter to specify the script file. This command allows you to run th
e script on the remote computers, even if the script file is not accessible to the remote computers.
When you submit the command, the content of the Sample.ps1 file is copied into a script block and the script block
is run on each of the remote computers. This procedure is equivalent to using the ScriptBlock parameter to submit t
he contents of the script.
-------------------------- EXAMPLE 12 --------------------------
C:\PS>$LiveCred = Get-Credential
C:\PS> Invoke-Command -ConfigurationName Microsoft.Exchange `
-ConnectionUri https://ps.exchangelabs.com/powershell `
-Credential $LiveCred -Authentication Basic `
-scriptblock {Invoke-Command {Set-Mailbox dan -DisplayName "Dan Park"}
Description
This example shows how to run a command on a remote computer that is identified by a URI (Internet address). This p
articular example runs a Set-Mailbox command on a remote Exchange server. The backtick (`) in the command is the Wi
ndows PowerShell continuation character.
The first command uses the Get-Credential cmdlet to store Windows Live ID credentials in the $LiveCred variab the c
redentials dialog box appears, enter Windows Live ID credentials.
The second command uses the Invoke-Command cmdlet to run a Set-Mailbox command. The command uses the ConfigurationN
ame parameter to specify that the command should run in a session that uses the Microsoft.Exchange session configur
ation. The ConnectionURI parameter specifies the URL of the Exchange server endpoint.
The credential parameter specifies tle. Whenhe Windows Live credentials stored in the $LiveCred variable. The Authe
nticationMechanism parameter specifies the use of basic authentication. The ScriptBlock parameter specifies a scrip
t block that contains the command.
-------------------------- EXAMPLE 13 --------------------------
C:\PS>$max = New-PSSessionOption -MaximumRedirection 1
C:\PS> Invoke-Command -ConnectionUri https://ps.exchangelabs.com/powershell `
-scriptblock {Invoke-Command {Get-Mailbox dan} `
-AllowRedirection -SessionOption $max
Description
This command shows how to use the AllowRedirection and SessionOption parameters to manage URI redirection in a remo
te command.
The first command uses the New-PSSessionOption cmdlet to create a PSSessionOpption object that it saves in the $max
variable. The command uses the MaximumRedirection parameter to set the MaximumConnectionRedirectionCount property
of the PSSessionOption object to 1.
The second command uses the Invoke-Command cmdlet to run a Get-Mailbox command on a remote server running Microsoft
Exchange Server. The command uses the AllowRedirection parameter to provide explicit permission to redirect the co
nnection to an alternate endpoint. It also uses the SessionOption parameter to specify the session object in the $m
ax variable.
As a result, if the remote computer specified by the ConnectionURI parameter returns a redirection message, Windows
PowerShell will redirect the connection, but if the new destination returns another redirection message, the redir
ection count value of 1 is exceeded, and Invoke-Command returns a non-terminating error.
-------------------------- EXAMPLE 14 --------------------------
C:\PS>$so = New-PSSessionOption -SkipCACheck
PS C:\> invoke-command $s { get-hotfix } -SessionOption $so -credential server01\user01
Description
This example shows how to create and use a SessionOption parameter.
The first command uses the New-PSSessionOption cmdlet to create a session option. It saves the resulting SessionOpt
ion object in the $so parameter.
The second command uses the Invoke-Command cmdlet to run a Get-Hotfix command remotely. The value of the SessionOpt
ion parameter is the SessionOption object in the $so variable.
-------------------------- EXAMPLE 15 --------------------------
C:\PS>enable-wsmanCredSSP -delegate server02
C:\PS> connect-wsman Server02
C:\PS> set-item wsman:\server02*\service\auth\credSSP -value $true
C:\PS> $s = new-pssession server02
C:\PS> invoke-command -session $s -script {get-item \\Net03\Scripts\LogFiles.ps1} -authentication credssp -credenti
al domain01\admin01
Description
This example shows how to access a network share from within a remote session.
The command requires that CredSSP delegation be enabled in the client settings on the local computer and in the ser
vice settings on the remote computer. To run the commands in this example, you must be a member of the Administrato
rs group on the local computer and the remote computer.
The first command uses the Enable-WSManCredSSP cmdlet to enable CredSSP delegation from the Server01 local computer
to the Server02 remote computer. This configures the CredSSP client setting on the local computer.
The second command uses the Connect-WSman cmdlet to connect to the Server02 computer. This action adds a node for t
he Server02 computer to the WSMan: drive on the local computer, allowing you to view and change the WS-Management s
ettings on the Server02 computer.
The third command uses the Set-Item cmdlet to change the value of the CredSSP item in the Service node of the Serve
r02 computer to True. This action enables CredSSP in the service settings on the remote computer.
The fourth command uses the New-PSSession cmdlet to create a PSSession on the Server02 computer. It saves the PSSes
sion in the $s variable.
The fifth command uses the Invoke-Command cmdlet to run a Get-Item command in the session in $s that gets a script
from the Net03\Scripts network share. The command uses the Credential parameter and it uses the Authentication para
meter with a value of CredSSP.
I suggest spending som etime learning the basics. It will save you a lot of frustration in the future.
¯\_(ツ)_/¯ -
How to run .tcl scripts with VTK?
I have a bunch of .tcl scripts that use VTK. How do I run them? I have tcl/tk/vtk installed, but when I try to run `tclsh script.tcl` it outputs errors about VTK. On other distros i saw a binary named `vtk` that could run .tcl scripts out of the box. Is there something like this on Arch?
Thanks.Hi, vtk is in community. It should supply the tcl bindings. I once was the maintainer when it was in AUR. It works here with the tcl examples that come with the vtk package. Have not tested the version in community yet.
-
How to Run Indesign Script in a file from plugin code in CS4?
Hi,<br />I have the code to execute the InDesign script stored in external file for InDesign CS3.<br /><br />InterfacePtr<IScriptManager> scriptManager(Utils<IScriptUtils>()->QueryScriptManager(kJavaScriptMgrBoss)); <br />InterfacePtr<IScriptRunner> scriptRunner(scriptManager, UseDefaultIID()); <br /> IDFile scriptFile(scriptFilePath); <br /> if (scriptRunner->CanHandleFile(scriptFile)) <br /> { <br /> ScriptData returnValue; <br /> PMString errorString; <br /> ErrorCode error = scriptRunner->RunFile(scriptFile); <br /> ASSERT(error == kSuccess); <br /> } <br /><br />But the RunFile() method is cs4 expects an additional argument of the type RunScriptParams. <br />Someone please show me with a code snippet on how to excute a script file in CS4??
Dear Ian
Here I'm used the below coding in CS3, Its working fine....
//In CS3 Coding
PMString jsFullPath("c:\\windows\\sample.jsx"); // a path to my java script file
do
const
IDFile outFile(jsFullPath);InterfacePtr<IScriptManager> scriptManager(Utils<IScriptUtils>()->QueryScriptManager(kJavaScriptMgrBoss));
ASSERT( scriptManager ) ;
InterfacePtr<IScriptRunner> scriptRunner(scriptManager,UseDefaultIID());
ASSERT( scriptRunner ) ;
if(scriptManager){
InterfacePtr<IScriptRunner>scriptRunner(scriptManager,UseDefaultIID());
RunScriptParams params(scriptRunner);
ErrorCode err = scriptRunner->RunFile(outFile, kTrue, kFalse);
while(kFalse);
But the same time I used this coding in CS4, Its not woking
//In CS4 Coding
PMString jsFullPath("c:\\windows\\MacID\\BIN\\sample.jsx"); // a path to my java script file
do
const
IDFile outFile(jsFullPath);InterfacePtr<IScriptManager> scriptManager(Utils<IScriptUtils>()->QueryScriptManager(kJavaScriptMgrBoss));
ASSERT( scriptManager ) ;
InterfacePtr<IScriptRunner> scriptRunner(scriptManager,UseDefaultIID());
ASSERT( scriptRunner ) ;
if
(scriptManager){
InterfacePtr<IScriptRunner>scriptRunner(scriptManager,UseDefaultIID());
RunScriptParams params(scriptRunner);
ErrorCode err = scriptRunner->RunFile(outFile, params);
while(kFalse);
I changed the "RunFile" arguments also
RunScriptParams params(scriptRunner);
ErrorCode err = scriptRunner->RunFile(outFile, params);
But Still I'm facing the problem in InDesign CS4. That's mean "Adobe InDesign CS4" shout down for serious error happend.
Please kindly help me, for solving this problem.
Thanks & Regards
T.R.Harihara Sudhan
Message was edited by: Adobe-InDesign CS4 -
How to run a script from Oracle Form (Beside using HOST command)
I would like to run a script from Forms 6.0. I know that we can actually issue this command :
host('plus80.exe' username/password@connect_string @c:\scriptname);
BUT, is there any other alternative ?Sqlplus is a different program, so one way or the other you have to leave Forms to run sqlplus. What is you objection against HOST?
You can also run sqlplus from the database, but again you need a stored java procedure to call sqlplus (sort of HOST command that runs in the database).
Francois' solution works if your script just has a query to run, but if you have specific sqlplus commands (spool etc.) forms_ddl is probably not a solution. -
How to run Open scripts on Mozilla Firefox?
Hi,
My open scripts are working fine on IE7. I want to run same scripts on Firefox 5.0.
Can you please tell me the steps?
Regards,
DeeptiHi,
Not all the firefox versions are supported. Let me point you to Error while recording with fire fox (4.0) browser. So, you'll end up getting errors like that.
As far as using firefox goes (i.e. once you have the right version),
Go to "View" menu in openscript and under
Openscript>Preferences>General>Browsers select firefox.
Thank you,
Narayan
Edited by: nryn on Aug 9, 2011 10:12 PM (link insert went wrong) -
How to run Perl script in Java program?
Some say that the following statement can run Perl script in Java program:
Runtime.getRuntime().exec("C:\\runPerl.pl");
But when I run it, it'll throw IOException:
java.io.IOException: CreateProcess: C:\runPerl.pl error=193
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Win32Process.java:63)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Runtime.java:566)
at java.lang.Runtime.exec(Runtime.java:428)
at java.lang.Runtime.exec(Runtime.java:364)
at java.lang.Runtime.exec(Runtime.java:326)
at test.runPerl.main(runPerl.java:16)
Exception in thread "main"
Where is the problem? In fact, I do have a Perl script named "runPerl.pl" in my C:/ directory. Could anybody tell me why it can't be run? Thanks in advance.Hello sabre,
First of all thanks for your reply.
I have tried like what you mentioned.
Eventhough, i could get the exact error message.
I could get the Exception
"Exception:java.lang.IllegalThreadStateException: process hasn't exited"
<code>
import java.io.*;
public class Sample{
public static void main(String args[]) {
String s = null;
Process p;
try
p = Runtime.getRuntime().exec("tar -vf sample.tar");
//p.waitFor();
if(p.exitValue() == 0)
System.out.println("CommandSuccessful");
else
System.out.println("CommandFailure");
catch(Exception ex)
System.out.println("Exception:"+ex.toString());
</code>
In this code, i tried to run the "tar command". In this command i have given -vf instead -xvf.
But it is throwing
"Error opening message catalog 'Logging.cat': No such file or directory
Exception:java.lang.IllegalThreadStateException: process hasn't exited
CommandFailure"
"Error opening message catalog 'Logging.cat'" what this line means ie,
I dont know what is Logging.cat could you explain me its urgent.
Thanks in advance.
Rgds
tskarthikeyan -
How to run shell script using External Process in Process Flow?
Hi,
We can run external process using Process flow.
I would like to run shell script as external process in Process flow.
Could any one please explain it?
Thanks and regards
Gowtham Sen.HI,
As you said I tried this case. I got the following error. The script is running successfully while I tested at unix command prompt.
The error is as follows..
tarting Execution PFPS_SMPL_RUNSHELL
Starting Task PFPS_SMPL_RUNSHELL
Starting Task PFPS_SMPL_RUNSHELL:EXTERNALPROCESS
/SOURCE_FILES/CollectFiles.sh: line 1: ls: command not found
/SOURCE_FILES/CollectFiles.sh: line 1: wc: command not found
/SOURCE_FILES/CollectFiles.sh: line 1: ls: command not found
Completing Task PFPS_SMPL_RUNSHELL:EXTERNALPROCESS
Starting Task PFPS_SMPL_RUNSHELL:EXTERNALPROCESS_1
SQL*Plus: Release 10.1.0.2.0 - Production on Fri Sep 29 22:57:39 2006
Copyright (c) 1982, 2004, Oracle. All rights reserved.
ERROR:
ORA-12545: Connect failed because target host or object does not exist
Enter user-name: SP2-0306: Invalid option.
Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER}]
where <logon> ::= <username>[<password>][@<connect_identifier>] | /
Enter user-name: SP2-0306: Invalid option.
Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER}]
where <logon> ::= <username>[<password>][@<connect_identifier>] | /
SP2-0157: unable to CONNECT to ORACLE after 3 attempts, exiting SQL*Plus
Completing Task PFPS_SMPL_RUNSHELL:EXTERNALPROCESS_1
Completing Task PFPS_SMPL_RUNSHELL
Completing Execution PFPS_SMPL_RUNSHELL
My scenario is---
I am trying to return a file name from one shell script. I created a external process for that. After completion of this process, I am running another script which takes that file name and trying to create a external table. The both scripts are runnning successfully. But while I am trying to run using process flow, its not coming.
And I am not getting the way to catch the output of external process and pass it as parameter as another external process.
Any suggestions are welcome.
Thanks and regards
Gowtham Sen.
Maybe you are looking for
-
How to delete an article from reading list in safari
Hi my name is kashish i just want to know that how can i remove something or a web page from the reading list in safari iam using iapd 4 retina display with ios7.0.4
-
My 7th Generation iPod Nano shuts off whenever I press a button.
I bought my iPod nano 16 GB a few months ago, and I noticed that sometimes, when I tried to open the screen (pressing the top button or the menu button) instead of opening, the iPod shut itself completely, and then rebooted, I could see the Apple log
-
How to influence the text display of key figures in the interarctive DP
Hello all, Does anyone know if there is a possibility (BADI, etc.) to change the text display of key figures (not characteristics!) in a planning book/data view? I know that you can define a free text in the data view but still, this is only one fixe
-
How do i copy data from a dvd to hard drive?
I have a dvd of a recent event at my church. It contains video clips and still photos in slideshow format. How do I save it to my hard drive and then copy it to a new disc? I looked at this issue on previous posts from 2011 but the links to the sol
-
My waveform graph has two graphs overlaying each other. The graph has two mult-plot cursors. Each cursor is watching a different plot. I tried to use the property node to move the cursor, and it seems like the cursors will go there for a split seco