How did you start scripting?

Discuss and share scripts and script files...
Post Reply
Biggynuff
Posts: 101
Joined: 13 May 2010 14:08

How did you start scripting?

Post by Biggynuff » 16 May 2010 17:27

Hi all,

Maybe a silly question, but how did you start to learn how to create even simple scripts? Did you have previous programming knowledge and did it help? Where did you find the reference material/examples you needed?

I've been looking at the 'source' code for some simple scripts and find some parts fairly straightforward, but others are just beyond me 8)

It's actually not as easy to get into as it seems . . . for instance, I know that some commands have reference numbers so they can be called within a script, such as '#123' etc, but where can I find the complete list of these commands and what they do? I've searched everywhere I can think of and can't see anything!

Are there any web pages or documents that can take me through the creation of some usable scripts to get started? I've had the XYPlorer help guide open almost constantly, and whilst there is a script reference section the examples are a little limited and I'm lost once I try to progress

I guess my question is "where did you start?" :lol:

I have ideas to create scripts for some of the monotonous, manual tasks that I often complete and I'd love to know where to strart - I'm just a bit worried about going off on the wrong track!

Thank you

Great app by the way!

Biggy

admin
Site Admin
Posts: 46881
Joined: 22 May 2004 16:48
Location: Cologne, Win 8.1, Win 10
Contact:

Re: How did you start scripting?

Post by admin » 16 May 2010 17:59


Biggynuff
Posts: 101
Joined: 13 May 2010 14:08

Re: How did you start scripting?

Post by Biggynuff » 16 May 2010 20:46

Hi Don, and thank you

Yes, I've been working my way through that page but I get stuck for information when I try to so something a little 'individual'

For instance, I had the idea to write a little script to rename a folder to the name of it's parent folder. Not a task I have to do very often, but I thought it would be quite a simple place to start experimenting

I can find the script reference to pass the current path of the folder to the script - <curpath> - but when it comes to passing the path of the parent folder I'm just stuck! I really do understand that this is probably a very simple thing for experienced scriptologists ( :P ) but for me it's a major step

That's why I wondered how other people had gone further into this

Thanks for a wonderful app which is now my one and only file explorer. I honestly don't know how I ever managed without this :wink:

Biggy

Stefan
Posts: 1360
Joined: 18 Nov 2008 21:47
Location: Germany, EU

Re: How did you start scripting?

Post by Stefan » 16 May 2010 20:50

And on the bottom of the side linked by Don you find an link to the wiki,
and there you find an paragraph about Command IDs #123;

Also in XYplorer help (press F1-button) you find under "Advanced Topics" something about scripting.
(also take an look into "User-Defined Commands" where you find an list of <XY Vars>)

To start scripting think about an task you want to automate, then write it down in plain english, step-by-step
what is to do, then search for the right scripting command in help / wiki /forum and create your own script.

It's also good to search the script forum for an interesting script and try to modify them.
But be warned that the syntax has changed over time.

At the first days of learning don't try to long at your own to solve an problem to not become frustrated,
just ask here for an hint (especially the right ""quoting"" can be horror). Later on you should use the "Step Mode"
and double checking your code to track down your problem. Or let it be for an day or two and then come back to
your script and solve it.




Common questions:

To comment out an line or the rest of an line, use two slash
//comment

To comment out an block of lines use
/*
lines
*/


The dot is used for concatenation like with PHP:
"<curfile>" . "ext" == fileext
"<curfile>" . ".ext" == file.ext


The Debug dialog appears always if you use menu "Scripting > Try Script..."
no matter if "Scripting > Step Mode" is set or not.




If/ElseIf/Else Blocks

Code: Select all

if (expression) {
    statement(s);
   }
    elseif (expression) {
    statement(s);
   }
   else {
   statement(s);
}
See help "Advanced Topics > Scripting > If/ElseIf/Else Blocks" for more.


Statement s

While Loops / While statement

Code: Select all

while (expression) {
    statement(s);
    }


$count = 1;
 while($count < 4){
   msg "iteration no " . $count . " of three";
   incr $count;
   }


//Do-While loop
$count = 1;
 while(true){
   msg "Hi you!";
   incr $count;
   if($count > 4){break;}
   }
See help "Advanced Topics > Scripting > While Loops" for more.


For Loop / For statement
For x = 1 To 10

Code: Select all

$Count = 1;
  While ($Count<11){
  //your code here
  incr $Count;
}

For x = 1 To 6 step 2

Code: Select all

$Count = 1;
  While ($Count < 7){
  //your code here
  msg "iteration no " . $Count . " of six (or of three only?)";
  incr $Count,,2;
  }

For x = 10 To 0

Code: Select all

$Count = 10;
  While ($Count > 0){
  //your code here
  msg "Count down " . $Count;
  incr $Count,,-1;
  }else{msg "0, GO!";}
Don wrote: Using Quotes in Scripting

It's strongly recommended that you (double- or single-) quote your strings!
While the script engine is currently still permissive with unquoted strings (msg Hi! works)
this might not be so in the future, so you better do msg "Hi!" right away!

Here's the basic laws of quoting:

(1) Everything is either in double-quotes, or in single-quotes, or outside of any quotes.
(2) To have double-quotes inside double-quotes they must be doubled.
(3) To have single-quotes inside single-quotes they must be doubled.
(4) Variables are resolved in double-quotes and outside of any quotes, but not in single-quotes

That's also why in the examples of use below for selfilter, you have this:
http://88.191.26.34/XYwiki/index.php/Sc ... _selfilter
selfilter "readme"; //Selects all items whose name contains "readme" (eg: readme, readme.txt, !readme.now)
selfilter """readme"""; //Selects item named "readme" and only that one item
selfilter "foobar"; // pattern is foobar
selfilter '"foobar"'; // pattern is "foobar"
MY explanation of quoting:
http://www.xyplorer.com/xyfc/viewtopic. ... 846#p40846


HTH? :D


I collected some more tips from others:
admin wrote:Try this for starters:
http://www.xyplorer.com/tour/index.php?page=scripting
Don
Muroph wrote:to learn about scripting i used the wiki:
http://88.191.26.34/XYwiki/index.php/Scripting
http://88.191.26.34/XYwiki/index.php/Script_Variables
i think it's not completely up to date, but it's a start.
for example, some script commands, like replace, have been converted to functions.
the help file is up to date, though, and it's a good option.
hit shift+F1 and you'll be taken directly to the "script commands" page.

regex is relatively easy to learn.
this is the best place i know:
http://www.regular-expressions.info/
note that xyplorer uses vbscript regex, which doesn't support all features:
http://www.regular-expressions.info/vbscript.html
http://88.191.26.34/XYwiki/index.php/Scripting

Code: Select all

    * 1 Introduction
    * 2 What Is A Script ? How Does It Work ?
    * 3 How to execute an Script ?
    * 4 Syntax
          o 4.1 Commands And Functions
                + 4.1.1 Calling Functions Without Commands
          o 4.2 Parameters Syntax
          o 4.3 Quotes
                + 4.3.1 Single Quotes vs Double Quotes
                + 4.3.2 Quotes for command lines and parameters
          o 4.4 String Operators
          o 4.5 Conditions and Loops
    * 5 Use Variables
    * 6 Expressions
          o 6.1 Nested Expressions
          o 6.2 Calculation
          o 6.3 Boolean Operators
          o 6.4 Comparisons
                + 6.4.1 Cross-Type Comparisons
                + 6.4.2 Examples
          o 6.5 Ternary Conditions
                + 6.5.1 Examples
    * 7 Conditional Statements
    * 8 Arrays
    * 9 The Next Level : Multi-line Scripts, or Script Files
    * 10 Comments
    * 11 Importance Of Settings
    * 12 Error & Debugging
    * 13 Script Commands And Functions
          o 13.1 Command IDs
          o 13.2 "Real" Commands And Functions


Examples:

Code: Select all

IS item file or path:

$item=(getinfo(countselected)<1)?(<curpath>):(<curitem>);
  open """%programfiles%\Avira\AntiVir Desktop\avscan.exe"" /PATH=""$item""";

Code: Select all

Scripting check if file or folder IsFile IsFolder


"Test if dir or file"
 text report("{name} is a {dir folder|file|drive}.<crlf>");
 sel 1;
 while(1){
   msg report ("This {name}-item is an {Dir Folder|File|Drive}",1);
   sel +1;
   end (<curitem>==""), "Last item reached. Script ends.";
 }

-------

"Test if dir or file"
 text report("{name} is a {dir folder|file|drive}.<crlf>");
 sel 1;
 while(1){
   //msg report ("This {name}-item is an {Dir Folder|File|Drive}",1);
   $IsFile = report ("{Dir No|Yes|Drive}",1);
   //$IsFOlder = report ("{Dir Yes|No|Drive}",1);
   //msg "IsFile?: " . $IsFile . ". IsFOlder?: " . $IsFOlder;
   msg "IsFile?: " . $IsFile;
   sel +1;
   end (<curitem>==""), "Last item reached. Script ends.";
 }

-------

Code: Select all

 while(1) ==> infinity loop  /// till end (<curitem>=="")  ==> if there is no file left, then end
 if (exists($curitem)==1)   ==> check if this is an file (and NOT an dir/folder)
 if (exists("<curpath>\$criteria")==2) ==> check if an folder with this name already exists

Code: Select all

// reality check 
if (1 == 2) { 
    echo "Help!";
    } else { 
    echo "Relax."; 
    }
Though it should be noted that you can abort script execution at any time in XY simply by pressing ESC
ScriptRecursionWarningOff to 1 in your INI file will get ride of the recursion checker.

Code: Select all

wait msec   //sleep pause
wait 1000; // sleep for an second
wait 60000; // sleep for an minute

Code: Select all

INI file handling
$a='"test2"';
  echo $a;
  setkey quote($a),test,test,"%temp%\test.ini";
  getkey $b,test,test,"%temp%\test.ini";
  echo "$a<crlf>$b";

Code: Select all

Loop
while(1){
 if("$file"==""){break;}
}

//loop through selected items
"Text Loop"
   $filelist = getinfo('SelectedItemsPathNames', '|');
   $count=1;
   while(1){
      $file=gettoken($filelist,$count,"|");
      if("$file"==""){break;}
      $data=regexreplace(readfile("$file"), "\n", "<crlf>");
      $base=regexreplace($file,"^(.+)\..+?$","$1");
      writefile("$base.nfo", "$data");
      $count++;}
   status "Done!",,ready;



"Loop through selected files"
    //collect the selected files into var $fileslist:
   $filelist = getinfo('SelectedItemsPathNames', '|');
   //initialize loop-counter var:
   $count=1;
   //start an infinity loop:
   while(1){
       //put one file after the other into var $file:
      $file=gettoken($filelist,$count,"|");
	  //if var $file is empty break the script:
      if("$file"==""){break;}
	  
	  //your code here

      //increase the count by one, to get the next file from filelist in the next loop
      $count++;}
   //just an info for the user:
   status "Done!",,ready;
  beep 800,100; beep 400,100; beep 600,100;


Press F1 in XYplorer and read "Advanced Topics > Scripting Commands Reference" to understand what this commands do and how to modify them.
For more about scripting and how to execute an script read the wiki at http://88.191.26.34/XYwiki/index.php/Scripting



   

// loop through the whole list
   //sel 1;
   while ( <curitem> != '' )
   { 
     msg <curitem>; 
     sel +1;
    }


// loop through the whole list
   sel 1;
   $count=0;
   $array="";
   while ( <curitem> != '' )
   { 
     IF (strpos(<curitem>,"2009") != -1)
     // or e.g.: IF ("<curext>"=="exe")
     {
       //msg <curitem>; 
       $array = $array . <curitem> . <crlf>;
       incr $count;
      }
     sel +1;
    }
    IF ($count > 0){ text $array; }else{msg "Nothing found";}

Code: Select all

DOS command line commandline
Run("""C:\hasher.exe"" sha256 ""<curitem>"" > ""<curitem>.sha256""");
::Run("cmd /k ""hasher.exe"" sha256 <curitem> > <curitem>.sha256");



Code:
run """cmd"" /k ""D:\Portable Programs\XYplorer\wget\wget"" --help";

or if you don't need to resolve any variables you could use single quotes to avoid the need to escape:
Code:
run '"cmd" /k "D:\Portable Programs\XYplorer\wget\wget" --help';


file in double-quotes "..."  => double the double quotes ""..."" => whole cmd in double quotes too => "cmd ""...""";
run "cmd /k ""%tmp%\xyMapShares.cmd""";
-----------------------

FYI, this Open-UDC:
"cmd" /k "cd <curpath>"
will open the DOS box at the current path. 

"cmd" /k "cd <curpath>&&dir"
will open the DOS box at the current path, and show the directory listing. 

Yep, "&&" is the command concatenator... did you know?
-----------------------


"Open DOS-Box here"
 #1005;
"Open DOS-Box with Admin rights"
 $tmp = %tmp%\xy.<date ddhhnnss> . ".CMD"; // path/file for temp file
 writefile($tmp, '@Echo off && Title Launch console as ADMIN && COLOR 1F' . <crlf>);
 writefile($tmp, 'RUNAS /USER:Administrator "cmd /T:4F /K TITLE ADMIN RIGHTS" && "/K /F:ON /E:ON"',a);
 $tmp = quote($tmp);
 run ("cmd /k $tmp"); 
 //run notepad  $tmp;
 Delete 0, 0, $tmp;
-----------------------
admin  07 May 2008
This will do "DIR C:" in the console box:
::open "cmd" /k dir c:\

cmd.exe switches (there are more...):
/c Carries out the command and then terminates
/k Carries out the command but remains

More elegant would be to add a new scripting command "cmd" and have:
cmd command, [remain=1]
::cmd "dir c:"


Code: Select all

Get file from both panes
   Focus("PI");
   $fileOtherPanel = "<focitem>";
   Focus("PI");
   
   Focus("PI");
   $Target= "<curpath>";
   Focus("PI");


"Swap Pane Locations"
  $pA = "<curpath>";
  Focus("PI");
  $pI = "<curpath>";
  Goto("$pA");
  Focus("PI");
  Goto("$pI");



"Open Location In Inactive Pane"
$pA = "<curpath>";
  #351; //Close Tab
  Focus("PI");
  #340; //Open Tab
  Goto("$pA");
  Focus("List");

"Open Location In Inactive Pane & Migrate List Settings"
  $pA = "<curpath>";
  Focus("PI");
  #340; //Open Tab
  Goto("$pA");
  #1071; //Copy List Settings from Other Pane
  Focus("PI");
  #351; //Close Tab
  Focus("PI");

Code: Select all

getinfo getinfo getinfo getinfo getinfo getinfo getinfo collecting collect files 
get all files list of files filelist fileslist listfile list files 

	$items = getinfo("selecteditemsnames","<crlf>"); //list names of selected items
	 writefile("%tmp%\filename.txt", $items);
	 run notepad "%tmp%\filename.txt";
or	
	writefile("%tmp%\filename2.txt", getinfo("selecteditemsnames","<crlf>"));
	 run notepad "%tmp%\filename2.txt";
or
   $tmp = %tmp%\xy.<date ddhhnnss>;                            // path/file for temp file
      writefile($tmp, getinfo("selecteditemsnames","<crlf>")); // write collected items to temp file
      run notepad $tmp;                                       // do your work here
      delete 0, 0, $tmp;                                      // clean up	



Quote each file in double quotes (here coma separated):
$Files = """" . getinfo("SelectedItemsPathNames", """ ,""") . """";

Code: Select all

http://88.191.26.34/XYwiki/index.php/Script_Variables#XY_Variables

  Variables

XY variables are all those variables you already know and use elsewhere :

<crlf> 
    Resolves to a CRLF (0D0A) Unlike the usual line break 
	(which can be changed using br, default <br>) which is only resolved 
	when using command msg, text, and copytext, this one is resolved all the time. 

<xyexe> 
    Name of the running XYplorer's executable (usually XYplorer.exe but you 
	can rename it to customize the app's titlebar) 
<xyver> 
    Version number of running XYplorer (e.g. 7.50.0003) 
<xypath> 
    Application folder (path to running XYplorer's executable) 
<xydata> 
    Application data (path where the application's data are stored, 
	for more about it and how to set it, see Application Data Path) 
<xyini> 
    Filename of the currently loaded Configuration file (filename.ini) 
	Note: This file is always located under <xydata> 
<focitem> 
    Full path/name of the currently focused item on Tree if focus is on Tree, 
	otherwise focused item on List. (Use command focus to focus the control of your choice) 
<curfolder> 
    Name of the current folder (without path) 
<curpath> 
    Current path 
<curpath_s> 
    "Special" current path (e.g. "Desktop\Folder" instead of 
	"C:\Documents and Settings\User\Desktop\Folder" as would return <curpath>) 
	when applicable, or else the same as <curpath> 
<curitempath> 
    Full path of currently selected & focused List item. Especially useful in 
	Search Results where the item's path might differ from current path (<curpath>) 
<curitem> 
    Full path/name of the currently focused & selected List item 
<curname> 
    Name (base.ext) of the currently focused & selected List item 
	(used to be called <curtitle> which is now deprecated) 
<curbase> 
    Base-name of the currently focused & selected List item 
<curext> 
    Extension of the currently focused & selected List item 
<curver> 
    Version of the currently focused & selected List item. 
	This variable now accepts an optional parameter allowing you to 
	format the way the version information will be returned. 
	The syntax is: <curver|text here> 
    When such parameter is specified, if a version info is found for the item, 
	then the text specified will be returned as prefix to the version info proper. 
	You can actually specify where to put it within your text, using wildchar * as placeholder. 
	For example, using <curver| [ver *]> would return nothing with a text file (no version info), 
	and " [ver 7.20.0000]" for XYplorer.exe v7.20.0000 
<date yyyymmdd_hhnnss> 
    Current date/time 
<datec yyyymmdd_hhnnss> 
    Created date/time of the currently focused & selected List item. 
	Note that when used on pattern for Batch Rename feature, it will be 
	the Created date/time of each of the renamed items. 
<datem yyyymmdd_hhnnss> 
    Modified date/time of the currently focused & selected List item. 
	Note that when used on pattern for Batch Rename feature, it will be 
	the Modified date/time of each of the renamed items. 
<datea yyyymmdd_hhnnss> 
    Accessed date/time of the currently focused & selected List item. 
	Note that when used on pattern for Batch Rename feature, it will be 
	the Accessed date/time of each of the renamed items. 
<srcdatec yyyymmdd_hhnnss> 
    Created date/time of the source item ("source item" refers to argument source in command new) 
<srcdatem yyyymmdd_hhnnss> 
    Modified date/time of the source item ("source item" refers to argument source in command new) 
<srcdatea yyyymmdd_hhnnss> 
    Accessed date/time of the source item ("source item" refers to argument source in command new) 
<clipboard> 
    The content of the clipboard. If files have been cut/copied in clipboard, 
	their full path/names will be listed, one per line ending with CRLF 

Informations	

Paths' Syntax Convention In Script

The paths returned in scripting, either through variables or commands (like inputfolder), 
will not be slashed (no final \) so that you can always use them without problems. 
So if the current location is C:\ then <curpath> will only return is C: in an attempt to consistency. 
That way, you can always add a \ to ensure that you have the full path, without worrying about 
the special cases of drives' roots, and it remains easier to work on (since for example <curpath>\New Folder 
is easier to work with than <curpath>New Folder)


Informations	
Please note that the focused item on Tree might not be the current location (e.g. <curpath>), 
if your tree is locked. See Locked Tree for more. So you should not rely on the focused item on 
Tree to know the current location.



Date Variables

Of course you can specify the format the date/time should be displayed. 
You can also use the general system default date format, as well as the current List column format :

    * No format specified (eg. <date> or <datec>) : will use the general system default date format.
    * Using "List" (case-sensitive!) as format (eg. <date List> or <datec List>) : will use the 
	current List date column date format, which you can define on menu View|Date Column Format. 

If no items are selected, the variables for Created, Modified and Accessed dates will return nothing.

Note that support for old versions of the date variables (format <myyyymmdd_hhnnss>) has been 
discontinued with v7.50.0001



Environment Variables

Environment variables are common Windows variables (like %tmp%) to different common system/user locations. 
For more about it as well as the list of extra variables added by XY, please refer to Environment Variables 


http://88.191.26.34/XYwiki/index.php/Environment_Variables

Here's a list of common Windows environment variables, and of all XY-specific variables :
Common Windows Variables
%allusersprofile% 	All Users Profile
%appdata% 		Application Date
%commonprogramfiles% 	Common Program Files
%programfiles% 		Program Files
%systemdrive% 		System Drive
%systemroot% 		System Root
%temp% 			Temp
%tmp% 			Tmp
%userprofile% 		User Profile
%windir% 		Windows Directory
 
XYplorer Variables
%computer% 		My Computer (drives listing)
%desktop% 		Desktop
%net% 			My Network Places
%personal% 		My Documents
%desktopreal% 		Desktop Real Path
%personalreal% 		My Documents Real Path
%winsysdir% 		Windows System Directory 

Do something every nth iteration only:

Code: Select all

$count=1; $ActOn=6; $iteration=$ActOn; $max=42; $Loops=1;
   msg "Watch status in status bar.";
   while(1)
   {
   if ($count==$ActOn)
     {
     
     //Do something every nth iteration only:
     status "Loop $count, act on every $iteration iteration, so act now: BEEP (No. $Loops)";
     //beep 300,500; 
   
     wait 4000;
     $ActOn =eval($ActOn+$iteration); incr $Loops;
    
    }else{
            status "Loop $count of $max. Act on every $iteration iteration. Press ESC to break now,"; 
           //beep 500,200; 
    } 
    wait 2000;
 
   incr $count;
   if ($count > $max){status "Script finished"; beep 800,200;  break;}
   }
----------- since the wiki is down i add my examples here:

Code: Select all

How to execute an Script ?
A) How to execute an script without saving the code to an file first
To execute an script without creating an script file first you have for example this seven possibilities.
Chose one of this:

1.) Use XYplorer menu "Scripting > Try Script.."
    Paste or type in the script and press OK. (Note that the debug window appears; try an right click on the [Continue] button and spot the additional
options)
    Note that you can reuse this script till you overwrite it.

2.) Use the XYplorer address bar for an one-liner script
    Example: ::$temp = "<curitem>"; msg $temp; $new = replace($temp, "\", "_"); msg $new;
    Note that you have to enable "Quick scripting" in XY Configuration > Advanced (F9 key)
    - "Quick scripting" (Extended Scripting)
    Enable entering scripts through location interfaces (Address Bar, Go To, Catalog, Favorites).
    Such scripts must be additionally prefixed with a double-colon (::) to distinguish them from normal locations.
    Note that that script is stored from XYplorer internally and you can reuse it e.g. from the address bar history.

3.) Use User-Defined Commands (UDC) for an one-liner script
    XYplorer menu "User > Manage Commands... > Run Script > New > Script: your code here;" (Example: msg "Hello world!")
    See the XY wiki for more http://88.191.26.34/XYwiki/index.php/User-Defined_Commands
    See examples: http://www.xyplorer.com/xyfc/viewtopic.php?f=3&t=3146
    Note that that script is saved from XYplorer internally for later reuse.

4.) Use Custom Toolbar Buttons (CTB) for an one-liner script
       4a. Use menu "Tools > Customize Toolbar..."
       4b. Add an User-Buttons  and click [OK]
       4c. Right click this new User-Button
       4c.2. Name:  and  Icon: (optional, this is not really needed)
       4c.3. On Click: "your code here"  (Example: msg "<xypath>";)
       4c.4. On right-click:  (optional script if you right click this CTB)
    See introduce of CTB at http://www.xyplorer.com/release_8.40.htm
    See an example: http://www.xyplorer.com/xyfc/viewtopic.php?p=40908
    Note that that script is saved from XYplorer internally for later reuse.

5.) Use Portable Openwith Menu (POM) for an one-liner script
    XYplorer menu "Tools > Customize Files Associations... > New > |"My Description" \;*>your code here;"
    Later The Portable Openwith Menu (POM) is opened via menu "File | Open With... (Ctrl+Alt+Enter)".
    See introduce of POM at http://www.xyplorer.com/release_7.10.htm
    Info about PFA/POM features: http://88.191.26.34/XYwiki/index.php/Portable_File_Associations
    See the XY wiki for more http://88.191.26.34/XYwiki/index.php/Glossary#POM:_Portable_Openwith_Menu
    Note that that script is saved from XYplorer internally for later reuse.
    Examples: http://www.xyplorer.com/xyfc/viewtopic.php?p=28660
    Examples: http://www.xyplorer.com/xyfc/viewtopic.php?p=42122

6.) Use Custom Keyboard Shortcuts (CKS) for an one-liner script
    Define an "User-Defined Command" and add an keyboard shortcut

7.) Use Custom Event Actions (CEA) for an one-liner script
    E.g. from an custom right click context menu:
    Sorry, CEA are not implemented right now.



B.) How to execute an script by loading it from an file

First save the script to an plain text file, best in XYplorers Scripts folder.
select and copy the whole script to the clipboard
in XYplorer go to the script folder (using menu "Go > Go to Scripts Folder")
there right click on the number column or on an empty space below of any file
    and chose "Paste Special > Paste Text Into New File" from context menu.
    Give that file an nice name and use XYS as extension.
    E.g.: "X:\Tools\XYplorer\Scripts\scriptname.xys"

Next you can call that script from several places as shown below.
Use one of this:

1.) XYplorer menu "Scripting > Load Script File..." to load an saved script file

2.) Use the XYplorer address bar to load an saved script file
    Example: ::Load scriptname;
    Note that the script path and also the extension is not needed to use here. (if it is in XYplorer\Scripts folder)
    Note that you have to enable "Quick scripting" in XY menu "Configuration > Advanced"
    - "Quick scripting" (Extended Scripting)
    Enable entering scripts through location interfaces (Address Bar, Go To, Catalog, Favorites).
    Such scripts must be additionally prefixed with a double-colon (::) to distinguish them from normal locations.

3.) Use User-Defined Commands (UDC) to load an saved script file
    XYplorer menu "User > Manage Commands... > Load Script File> New > Script File: scriptname"
    See the XY wiki for more http://88.191.26.34/XYwiki/index.php/User-Defined_Commands
    See examples: http://www.xyplorer.com/xyfc/viewtopic.php?f=3&t=3146

4.) Use Custom Toolbar Buttons (CTB) to load an saved script file
4a. Use menu "Tools > Customize Toolbar..." 
4b. Add an User-Buttons  and click [OK]
4c. Right click this new User-Button
4c.2. Name:  and  Icon: (optional, this is not really needed)
4c.3. On Click: "your code here" (Example: load MyFirstScript;)
4c.4. On right-click:  (optional script if you right click this CTB)
    See introduction of CTB at http://www.xyplorer.com/release_8.40.htm
    See example: http://www.xyplorer.com/xyfc/viewtopic.php?p=40908

5.) Use Portable Openwith Menu (POM) to load an saved script file
    XYplorer menu "Tools > Customize Files Associations... > New > |"My Description" \;*>::Load scriptname;"
    Later The Portable Openwith Menu (POM) is opened via menu "File | Open With... (Ctrl+Alt+Enter)".
    See introducement of POM at http://www.xyplorer.com/release_7.10.htm
    Info about PFA/POM features: http://88.191.26.34/XYwiki/index.php/Portable_File_Associations
    See the XY wiki for more http://88.191.26.34/XYwiki/index.php/Glossary#POM:_Portable_Openwith_Menu
    Examples: http://www.xyplorer.com/xyfc/viewtopic.php?p=39914

6.) Use Custom Keyboard Shortcuts (CKS) to load an saved script file
    Define an "User-Defined Command" and add an keyboard shortcut

7.) Use Custom Event Actions (CEA) to load an saved script file
    E.g. from an custom right click context menu:
    Sorry, CEA are not implemented right now.

Hint about Script warning about Recursion:
   Use setting AllowRecursion;
    See XY wiki http://88.191.26.34/XYwiki/index.php/Script_command:_setting

Hint about debug window:
   Enable "Scripting > Step Mode" to see the debug window for every script execution.

   Note: do an right click on the [Continue] button to see some options.
Hint about " " quotes:
    If something doesn't works please try to add or remove quotes from commands.
    Because here for this examples ""-quotes are used often for explanations to show you an start and end point,
    and should NOT be used in real life. On the other hand quotes ARE needed if your commands, names or paths contain spaces.
    You may want to read section "4.3 Quotes" too?

Code: Select all

Quotes for command lines and parameters

If you launch an application by using the run or open command
and if the path to this app, or the file name of the executable contains spaces,
you have to proper quote the command line (further referred to as 'string')
and maybe also the command line parameters (arguments) too.

This could be a little tricky since the script engine itself removes the outer quotes.
That has to be done because the engine have to know where the string starts and ends, so the string is enclosed between quotes.
Like: "C:\Program Files\AutoHotkey\AutoHotkey.exe"

So, if you want that your string is processed include quotes, you have to double the outer double quotes.
Like: ""C:\Program Files\AutoHotkey\AutoHotkey.exe""

But this is read as
Like: "EmptyString"C:\Program Files\AutoHotkey\AutoHotkey.exe"EmptyString"

That's why you have to use triple double quotes: """String"""
Like: """C:\Program Files\AutoHotkey\AutoHotkey.exe"""
""" simply means: give me an string which contains just one single "-sign

It's strongly recommended that you (double- or single-) quote your strings!

Even if they doesn't contains spaces. This is just your script works in future script versions too.

While the script engine is currently still permissive with unquoted strings (msg Hi! works)
this might not be so in the future, so you better do msg "Hi!" right away!

Here's the basic laws of quoting:

(1) Everything is either in double-quotes, or in single-quotes, or outside of any quotes.
(2) To have double-quotes inside double-quotes they must be doubled.
(3) To have single-quotes inside single-quotes they must be doubled.
(4) Variables are resolved in double-quotes and outside of any quotes, but not in single-quotes

Examples:
selfilter "readme"; //Selects all items whose name contains "readme" (eg: readme, readme.txt, !readme.now)
selfilter """readme"""; //Selects item named "readme" and only that one item
selfilter "foobar"; // pattern is foobar
selfilter '"foobar"'; // pattern is "foobar"

run """C:\Program Files\AutoHotkey\AutoHotkey.exe""";
run '"C:\Program Files\AutoHotkey\AutoHotkey.exe"';
run quote("C:\Program Files\AutoHotkey\AutoHotkey.exe");
run("""C:\hasher.exe"" sha256 ""<curitem>"" > ""<curitem>.sha256""");

run """cmd"" /k ""D:\Portable Programs\XYplorer\wget\wget"" --help";
run '"cmd" /k "D:\Portable Programs\XYplorer\wget\wget" --help';
run "cmd /k ""%tmp%\xyMapShares.cmd""";
open quote("notepad")." ".quote(<curitem>);
Last edited by Stefan on 06 Nov 2010 22:47, edited 12 times in total.

Stefan
Posts: 1360
Joined: 18 Nov 2008 21:47
Location: Germany, EU

Re: How did you start scripting?

Post by Stefan » 16 May 2010 20:58

Biggynuff wrote:For instance, I had the idea to write a little script to rename a folder to the name of it's parent folder. Not a task I have to do very often, but I thought it would be quite a simple place to start experimenting

I can find the script reference to pass the current path of the folder to the script - <curpath> - but when it comes to passing the path of the parent folder I'm just stuck!
There is no script command to just get the parent folder.
You have to use e.g. <curpath> and split them by using regexreplace() or by gettoken()

$path = "<curpath>";
    $fold = gettoken($path, 2, "\");

$path = "<curpath>";
    $parent = regexreplace($path, '^.+\\([^\\]+)$', '$1');


Read every script in the script forum and save them for reverence, then you see such constructs.
And you may collect them in an own scripting reference text file.

----------- since the wiki is down i add my examples here:





Split path file name part parts base extension array

Code: Select all

//set array  to test string:
$ARRAY = "C:\Documents and Settings\Administrador\Meus documentos\XYplorer\Contas a receber.docx.bak";
   
  $DELIM = "\";     //use to split the string at
   
  //get top amount of delimiters:
  $UBound=1; While(1){ $T = gettoken( $ARRAY, $UBound, $DELIM); IF ($T==""){$UBound--;break;} $UBound++;}
   
  //split the string into parts
  //assign array elements to $Vars:
  $DRIVE             = gettoken( $ARRAY,           1, "\");
  $TopFolder         = gettoken( $ARRAY,           2, "\");
  $SubFolder         = gettoken( $ARRAY,           3, "\");
  $GrantParentFolder = gettoken( $ARRAY, $UBound - 2, "\");
  $ParentFolder      = gettoken( $ARRAY, $UBound - 1, "\");
  $FILE              = gettoken( $ARRAY, $UBound    , "\");
   
   //split FileName into base and extension:
   $Base = "not an file";
   $Exte = "not an file",
   If ($FILE != "")
    {
     If (strpos($FILE, ".") > 0)
     {
      while($Index < strlen($FILE))
       {
         $check = strpos( $FILE, ".", strlen($FILE) - $Index );
         If ($check > -1){$InStrRev = $check +1; break;}
         $Index++;
       }
     $Base = substr($FILE, 0, $InStrRev -1);
     $Exte = substr($FILE, $InStrRev);
     }
    }
   
   
  //test output:
  text Drive: <tab 2> $DRIVE<crlf>
       TopFolder: <tab> $TopFolder<crlf>
       GrantParent: <tab> $GrantParentFolder<crlf>
       ParentFolder: <tab> $ParentFolder<crlf>
       File: <tab 2> $FILE<crlf>
       Base: <tab 2> $Base<crlf>
       Ext: <tab 2> $Exte;
Test Output for "C:\Documents and Settings\Administrador\Meus documentos\XYplorer\Contas a receber.docx.bak"

Code: Select all

Drive:        C:
TopFolder:       Documents and Settings
GrantParent:     Meus documentos
ParentFolder:     XYplorer
File:          Contas a receber.docx.bak
Base:         Contas a receber.docx
Ext:          bak

----

Code: Select all

global $FileName, $InStrRev, $Sign;
    
    $FileName = "This is No. 1 of my File name.ext"
    
    //split extension:
    $Sign = "."; sub "_InStrRev";
    $Base = substr($FileName, 0, $InStrRev -1);
    $Exte = substr($FileName, $InStrRev);
    
    
"_InStrRev" //Function
//"_InStrRev" gives last possition of $Sign in $FileName
//Syntax: $Sign = ".";  sub "_InStrRev";
//Return: last pos of $Sign in $FileName
global $FileName, $InStrRev, $Sign;
   $Index=0;
   while($Index < strlen($FileName))
   {
     If ($FileName==""){break;}
     $check = strpos( $FileName, "$Sign", strlen($FileName) - $Index );
     If ($check > -1){$InStrRev = $check +1; break;}
     $Index++;
   }
----------------

For Each Item In Items Do
For Each File In Files Do

Code: Select all

  $ITEMS = "Eins, Zwei, Drei";
  foreach($item, $ITEMS, ",")
  {
    msg $item;
  }
   
   //-----
    
   $Array="";
   $Files = get("SelectedItemsPathNames", "|");
   foreach($file , $Files)
   {
     $Array = $Array . $file<crlf>;
   }
   text $Array;

-----------------

wiki Scripting_HowTo - XYwiki 2010-08-08b

Code: Select all

Scripting/HowTo

From XYwiki

Hi, i try to collect here some howtos, some tips and tricks to do scripting.

Contents
1 Common questions, mistakes and pitfalls
2 For Each Item In Items Do (old way)
3 For Each Item in Items Do (Report)
4 For Each Item In List Do (simple)
5 For Each Char In Chars Do
6 IsFolder / IsFile, check type of item
7 Build an {GUID}
8 OEM to ANSI / ANSI to OEM"
9 ROT13 ROT5 ROT18
10 Beep, Bip Bip, Beeeeep
11 Mass Downloader
12 Random FileName
13 Get the name of the parent folder
14 Split path\file.exe into parts
15 Only for chosen extension
16 Decide between if there is an selection or not
17 Only files older than 30 days
18 Only files of size greater/lesser than
19 Get info from both panes (path or file names)
20 Do something every nth iteration only
21 Rename only Nth Iteration
22 INI file handling
23 DOS command line
24 Edit this script
25 Hex 2 DEC
26 Convert Lineenders
27 Execute an VBScript





Common questions, mistakes and pitfalls
- - - - - - - - - - - - - - - - - -

Note that for each script only the first line must/should start at column position 1!
All other following lines MUST be indented by at least one space/blank.

Exceptions from this rule:
A.) If the first line of your script is an caption in quotes then THIS has to start at pos1.
    Then the first line with code and all following has then to be indented.

B.) You can have more than one script inside a script file.
    The first script may have, the second and following scripts must have an caption 
    wrapped in quotes to identify (or say: separate)  each script. You will be prompted with an menu.
    This caption line(s) MUST start at pos1 too. The code has too be indent in that case.

C.) Comment lines starting with // are ignored and may be at pos 1 too, but don't have to.

Examples:

Right script usage:

----------------------------------------
$a = "Hello";
  msg $a;
----------------------------------------

or

----------------------------------------
$a = "Hello";
        msg $a;
----------------------------------------

or

----------------------------------------
"This is the CAPTION"
//with comment line
  $a = "Hello";
   msg $a;
----------------------------------------

and

----------------------------------------
"This is the caption of script No. 1"
   //with comment line
   $a = "Hello";
   msg $a;

"This is the caption of the second script"
   $a = "How are you?";
   msg $a;
"_Third script (hidden)"
/*
Multi-line comment:
You may hide scripts by prefixing an underscore (_) to their caption.
Hidden scripts can be executed but are not shown in the script file's popup menu.
*/
    $a = "How are you?";
    msg $a;
----------------------------------------

And here only the second script (here used as function) has an caption.
At the first script the code line starts at pos 1,
For the second script the caption starts at pos 1, the code is indented:

----------------------------------------
global $count;
  $a = "How are you?";
  msg $a;
  $count = 3;
  sub "_Second script (hidden)";

"_Second script (hidden)"
  global $count;
  $Loop=1;
  while( $Loop < $count )
  {
    msg "No. $Loop out of $count",1;
    $Loop++;
  }
----------------------------------------




Wrong usage:

----------------------------------------
$a = "Hello";
msg $a;
//not indented, you will be prompted with an wired menu.
----------------------------------------

or

----------------------------------------
"This is an script"
  $a = "Hello";
   msg $a;
  "This is an second script"
    $a = "How are you?";
    msg $a;
//caption of second script must NOT be indented.
----------------------------------------

But the only "problem" will be that you will be surprised once you execute
such an wrong indented script by an unexpected dialog shown you ;-)

Note that there is an another exception of this rule:
See XYplorer help "Advanced Topics > Scripting > Heredoc Syntax" for more.


Summarized:
Only the first line of an script are allowed to (and should) start at position 1.
Script "Caption"-lines MUST start at position 1.
   Following lines MUST be indented.
Comment line could start at position 1 since the are ignored.
An exception is the "Heredoc Syntax".
See XYplorer help "Advanced Topics > Scripting" for more.

- - - - - - - - - - - - - - - - - -

To comment-out an line or the rest of an line, use two slashes
//this is an comment
msg "Hi you!"; //this is an comment
//msg "Hi you!"; this is an disabled command
- - - - - - - - - - - - - - - - - -
To comment out an block of lines use
/*
 line
 line
 msg "Hi you!";
 more lines
*/
- - - - - - - - - - - - - - - - - -
The dot is used for concatenation like with PHP:
  $TEST = "File name";
    msg $TEST.ext;      //===> results in 'File nameext'
    msg $TEST."ext";    //===> results in 'File nameext'
    msg $TEST.".ext";   //===> results in 'File name.ext'
    msg "$TEST.ext";    //===> results in 'File name.ext'
So always use quotes "...". See http://88.191.26.34/XYwiki/index.php/Category:Scripting#Quotes
- - - - - - - - - - - - - - - - - -
The debug dialog "Stepping through a Script" 
  appears always if you use menu "Scripting > Try Script..."
  no matter if "Scripting > Step Mode" is set or not.
But since recently you can use "Scripting > Run Script..." without this "Step Mode"
 Addition note: see the help for step; and unstep; with which you can use the debug dialog 
                for your script at an point you really need to check out.
- - - - - - - - - - - - - - - - - -
To watch the value of an variable while the script is running you may use the status() command.

Example:
$a = 1;
  while ($a <= 100)
  {
    status "Var "."$"."a is " . $a . "     -  Press ESC to stop.";
  incr $a;
  }
status "Script done!";

See XYplorer help "Advanced Topics > Scripting Commands Reference > status()" for more.
See http://88.191.26.34/XYwiki/index.php/Scripting#Quotes about my queer quoting used at the status command.
- - - - - - - - - - - - - - - - - -
See XYplorer help "Advanced Topics > Scripting Commands Reference > assert()"
for how to interrupts processing on certain conditions.
- - - - - - - - - - - - - - - - - -

User variables are case-sensitive!

$ITEM = "Do you see this?";
  msg $Item;
  msg $ITEM;

Script commands are sometimes too:
  $a ="a";
  if ("$a" like "A"){ msg "1: Yes, $a is like A<crlf>Wrong! but always TRUE because 
           of wrong spelled parameter 'Like' as 'like'"; }
           else{ msg "1: No, $a is not like A"; } 
  if ("$a" Like "A"){ msg "2: Yes, $a is like A"; }
           else{ msg "2: No, $a is not like A.<crlf>Note the correct spelled 'Like'"; }
- - - - - - - - - - - - - - - - - -


You can abort script execution at any time (if it is not an infinity loop) in XYplorer simply by pressing ESC
IF you have programmed an infinity loop, close XYplorer by using the windowsTM task manager
- - - - - - - - - - - - - - - - - -
If your script works recursive, i.e. the script calls itself, you get an warning about that.
Set "ScriptRecursionWarningOff=" to 1 in your INI file to get ride of the recursion checker.

But it is better to disable this warning only if you know what you do (and that your script works as it should),
you can do this script-wise by using the following command:
setting name, [value (1|0|r)], [permanent (p)]

Example: 
setting "AllowRecursion"; // Show no warning on script recursions
See XYplorer help "Advanced Topics > Scripting Commands Reference > setting()" for more.
- - - - - - - - - - - - - - - - - -
Pause, Wait, Sleep
Undocumented and unsupported!
wait msec
wait 1000;  // sleep for an second
wait 60000; // sleep for an minute
- - - - - - - - - - - - - - - - - -


How to Stop an script, exit an loop, end if condition:

Press ESC-key

- - - - - - - -

While Loop

while(1) //infinity loop
 {
    break;  //exit loop, see help to exit nested loops
 }

- - - - - - - -

If statement

If (1)
 {
   end(1) //end the whole script
 }

- - - - - - - -

end condition, [message], [scope=0]

end (getinfo("CountSelected")<1), "Nothing selected. Script quits.";
  msg "Do you see this dialog?<crlf>Then you had at least one item selected.";

See XYplorer help "Advanced Topics > Scripting Commands Reference > break" for more.
See XYplorer help "Advanced Topics > Scripting Commands Reference > end()" for more.
- - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -




For Each Item In Items Do (old way)
 /*
 Some possible commands to use here:
 getinfo("SelectedItemsPathNames", [delimiter=CRLF]);
 getinfo("SelectedItemsNames", [delimiter=CRLF]);
 getinfo("CountItems", [(unused)]);
 getinfo("CountSelected", [(unused)]);
 */


 //If nothing is selected, select all first:
  $CountSelected = getinfo("CountSelected");
  IF ($CountSelected<1){sel a;} //Select all.
  
  
  $CountSelected = getinfo("CountSelected");
  IF ($CountSelected > 3 ){ msg "You have selected more then 5 items.<crlf>
  You may select only a few items for this test to save some time. ;-)<crlf>
  Or is it OK to continue with $CountSelected items?",1;} 
  
  //Collect all selected files into variable "$filelist":
  //We use an pipe '|' symbol as separator.
  $filelist = getinfo("SelectedItemsNames", "|");
     
  //The var "$count" counts the iterations and decides which token is to use:
  $count=1;
  
  //while(1) starts an infinity loop
  while(1){
  
     //Put token number "$count" from "$filelist",
     //separated at the '|' pipe, into new var "$file":
     $file = gettoken($filelist, $count, "|");
     
     //If there is no more token, the var "$file" is empty.
     //If var "$file" is empty, we tell the script to exit this loop:
     if("$file"==""){break;}
     
     
     //Do something useful here ;-):
     
     //Show an MessageBox to test if it works:
     //Remember to use always the '1' parameter for the MsgBox, 
     //so you have an change to cancel the script.
     msg "File No.: $count<crlf>Item name: $file",1;
     
     //Increment the var $count by one to get next token:
     $count++;}
     
  //At the end, show an info in the XYplorer status line:
  status "Done!",,ready;
.<EOE>


If you need only the name without the extension you may use:

$filebase = regexreplace($file,"^(.+[^.])\.(.+)$","$1");
     $fileext = regexreplace($file,"^(.+[^.])\.(.+)$","$2");
     
     msg "File No.: $count<crlf>Item name: $file<crlf>
     File base name: $filebase<crlf>
     File extension: $fileext ",1;

Or use the newer way, see "Split path\file.exe into parts" below at http://88.191.26.34/XYwiki/index.php/Scripting
/HowTo#Split_path.5Cfile.exe_into_parts
.<EOE>






For Each Item in Items Do (Report)

You can also use the report() command to collect items.
report([template], [itemlist=0 : 0,1,items], [header], [footer]);
   {FullName} gives you the full file name incl. path
   {Name} gives you the file name with the extension
   {BaseName} gives you just the file name without extension
   {Ext} gives you just the file extension
For more about report() see http://88.191.26.34/XYwiki/index.php/Script_function:_report%28%29

Example:
$filelist = report("{FullName}<crlf>{Name}<crlf>{BaseName} with extension {Ext}<crlf><crlf><crlf>",1);
   if ($filelist<" "){$filelist="You have to select some items first, because we had used 
      the '1' parameter for the report command.";}
   text $filelist ;
.<EOE>

Example:
 //Collect all selected items names and add an \r\n line break, so each item is on an own line:
    $ITEMS = report("{Name}<crlf>",1);
    //Test, show us the collected items:
    text $ITEMS;
    
    //For Each Item In Items Do:
    $LOOP=1;
    while(1)
    {
        $item = gettoken($ITEMS, $LOOP, "<crlf>");
        if ($item==""){break;}
        //Do something useful:
        msg $item,1;
    incr $LOOP;     
    }
.<EOE>






For Each Item In List Do (simple)
Depending on what you want to do, maybe this simpler example will do?

sel 1;
 while(true){ msg "<curitem>",1;  sel +1; if("<curitem>"==""){break;}

that is
 sel 1;
 while(true)
 {
   msg "<curitem>",1;
   sel +1; 
   if("<curitem>"==""){break;}
 }
See http://88.191.26.34/XYwiki/index.php/Script_Variables#XY_Variables for more about <XYvars>
.<EOE>







For Each Char In Chars Do

$STRING = "XYplorer";
$LOOPs = strlen($STRING);
$ITERATION=0;
$OUTPUT="";
while($ITERATION <= $LOOPs)
 {
    $Token = substr($STRING, $ITERATION, 1);
    if ($Token==""){break;}
   msg $Token,1;
 incr $ITERATION;
 }
.<EOE>


"Splitter (Split an text at n chars)"
 //$String = "Many a mickle makes a muckle. Manya mickle makesa muckle. Manyamickle makes amuckle. ";
 $String = "<clipboard>";
 $SplitAtPos = 55;
 $StringLength = strlen($String);
 $StartPos = 0;
 $out = "";
 
 while($StartPos <= $StringLength - $SplitAtPos)
 {
      //don't break inbetween an word
     //check if next char after $Pos+$SplitAtPos is an blank:
     $IfBlank = "a";
     $IfBlankCount = 1;
     while ($IfBlank != ' ')
     {
         $IfBlank = substr($String, $StartPos + $SplitAtPos + $IfBlankCount ,1);
         incr $IfBlankCount ;
     }
     
     $temp = substr($String, $StartPos, $SplitAtPos + $IfBlankCount );
     $out = $out$temp<crlf>;
     incr $StartPos, ,$SplitAtPos + $IfBlankCount ;
     status $StartPos;
 }
   //last part of the string:
   $temp = substr($String, $StartPos);
   $out = $out$temp;
    
   //output:
   //msg  Length $StringLength<crlf>
   //      StartPos $StartPos<crlf>
   //      IfBlankCount $IfBlankCount<crlf>
   //      Split at $SplitAtPos<crlf>
   //      $out;
   copytext $out;
<EOE>







IsFolder / IsFile, check type of item
If you want to check if an item is an folder or an file,
maybe to do something for files only, you have several ways:

Use report()
text report("{name} is a {dir folder|file|drive}.<crlf>");
.<EOE>

sel 1;
while(1){
  msg report ("This item: {name} is an {Dir Folder|File|Drive}",1
  sel +1;
  end ("<curitem>"==""), "Last item reached. Script ends.";
.<EOE>


sel 1;
 while(1){
   $IsFolder = report ("{Dir Yes|No|Drive}",1);
   if ($IsFolder=="Yes")
   {
        msg "IsFolder? <curname>: " . $IsFolder,1;
   }else{
        msg "IsFolder? <curname>: " . $IsFolder,1;
   }
   sel +1;
   end (<curitem>==""), "Last item reached. Script ends.";
 }
.<EOE>
sel 1;
 while(1){
   $IsFile = report ("{Dir No|Yes|Drive}",1);
   if ($IsFile=="Yes")
   {
        msg "IsFile? <curname>: " . $IsFile,1;
   }else{
        msg "IsFile? <curname>: " . $IsFile,1;
   }
   sel +1;
   end (<curitem>==""), "Last item reached. Script ends.";
 }
.<EOE>



Use "<cursize>"
sel 1;
 while ( "<curitem>" != "" )
  {
    //Skip folders:
    IF ("<cursize>" != "")
     {
        msg "<curitem>",1;
     }else {
        msg "upps, this is an folder ;-)",1;
     }
  sel +1;
  }
Note that ("<cursize>" > 0) wouldn't work but match 0-byte files too!
So we check here for IF("<cursize>" == Empty) or IF("<cursize>" != Empty)
OK, you could use IF("<cursize>" > -1) too ;-)
.<EOE>

sel 1;
 while ( "<curitem>" != "" )
 {
    //Skip files:
    IF ("<cursize>" == ""){ msg "<curname><crlf>Yes, it's an folder. Do something.",1; }
 sel +1;
 }
 msg "End reached, Done!";
.<EOE>


Use exists()
//check if this is an file (and NOT an dir/folder or drive)
if (exists("<curitem>")==1)  {msg "<curname> is an file.",1;}else{msg "<curname> is an folder.",1;}
<EOE>

//check if this is an folder (and NOT an file or drive)
if (exists("<curitem>")==2)  {msg "<curname> is an folder.",1;}else{msg "<curname> is an file.",1;}
<EOE>

See XYplorer help "Advanced Topics > Scripting Commands Reference > Exists()" for more.
exists(item)
tem: Full path (local or UNC) to a file system item.
eturn: 0 = does not exist /// 1 = exists (file) /// 2 = exists (folder; drive; share; server)








Build an {GUID}

rest will follow soon....
Last edited by Stefan on 12 Mar 2011 22:15, edited 6 times in total.

Biggynuff
Posts: 101
Joined: 13 May 2010 14:08

Re: How did you start scripting?

Post by Biggynuff » 16 May 2010 22:06

Hi Stefan,

I can't thank you enough for taking the time to answer these 'new user' questions!

I've just spent a few moments looking through the script you've written above and looked up the reference for 'gettoken' and it all just seems to make sense 8) . It's just so frustrating when the answer is so simple but incredibly difficult to find when not sure where to start

I've already started to collect scripts from all over the forum and I'm trying to take them apart to see how they work. As you mention, I've also found references to commands that no longer work. This is why I'm still a bit unsure if I'm in the right direction!

Once again, thanks, I'm really gonna enjoy trying some little scripts out and working out how the commands fit together

Biggy

Biggynuff
Posts: 101
Joined: 13 May 2010 14:08

Re: How did you start scripting?

Post by Biggynuff » 16 May 2010 22:22

Well, I'm learning a lot already!

It's difficult to use the 'gettoken' command because the index references the path from the left of the path name, and with a deeply burried sub folder we wouldn't know what digit to use as the index (we don't know how deep it will be, or we'll have to make a new command for each depth. Not practical :lol:

However, I'm delighted that the Regex version works superbly!

Now I have a major headache . . . I have to learn scripting AND Regex :P . Actually, this is gonna be fun!

Thanks Stefan

Biggy

Muroph
Posts: 561
Joined: 21 Aug 2007 16:13

Re: How did you start scripting?

Post by Muroph » 16 May 2010 23:01

to learn about scripting i used the wiki:
http://88.191.26.34/XYwiki/index.php/Scripting
http://88.191.26.34/XYwiki/index.php/Script_Variables
i think it's not completely up to date, but it's a start.
for example, some script commands, like replace, have been converted to functions.
the help file is up to date, though, and it's a good option.
hit shift+F1 and you'll be taken directly to the "script commands" page.

regex is relatively easy to learn.
this is the best place i know:
http://www.regular-expressions.info/
note that xyplorer uses vbscript regex, which doesn't support all features:
http://www.regular-expressions.info/vbscript.html
My shared scripts:
TeraCopy Integration, Tag Manager, Comments Menu, Text Replacer, Image and Media Tools, Checksum Calculator, Video Calculator
only 5 URLs are allowed on the sig...

Biggynuff
Posts: 101
Joined: 13 May 2010 14:08

Re: How did you start scripting?

Post by Biggynuff » 20 May 2010 17:02

Hi Muroph,

Thanks for the links. I've picked up a copy of Sams "Regex in 10 minutes" and I'm already starting to wonder what life was like before XY and Regex 8)

I've also found this page to be extremely useful:

http://gskinner.com/RegExr/

You can paste any text you like into the bottom panel and type a regex into the 'input' field. The resulting matches are shown instantly. There's also a handy reference panel on the right of the page. Nice :o

Thanks

Biggy

Post Reply