Pagina per appunti per i linguaggi che eseguono sul windows script host.
VBscript learning
In windows (XP) il linguaggio di script che conoscevo era quello che permetteva di creare i .bat , ovvero il linguaggio di scripting ereditato da msdos ed espanso man mano. E' discretamente potente ma per fare cose che, apparentemente, dovrebbero esser semplici, si diventa prolissi. Un linguaggio di scripting, invece, deve essere "semplice" da usare, ovvero con sintassi compatta molto simile al linguaggio naturale e, per questo, si accetta che non sia proprio efficiente come linguaggi più vicini al linguaggio macchina (uno dei quali C, che è potentissimo ma decisamente prolisso in termini di istruzioni) ma che permetta di fare, comunque, molte cose.
Io che sono lento a scoprire e capire le cose, ho scoperto l'evoluzione del .bat su windows che sono gli script in [[http://en.wikipedia.org/wiki/VBScript|VBscript]] (recentemente sostituiti dalla windows powershell solo su alcune versioni di win) che hanno un'elevata compatibilità di esecuzione in ambienti windows (non dos), proprio come i .bat (powershell invece non è così portabile).
Mumble, gli script VBS non sono proprio esenti da macchine virtuali, anche se non del calibro dell'ambiente .netFramework che, almeno sul disco (in ram non sempre) è un piombo. Bisogna usare l'ambiente windows script host. Mi correggo, WSH è già presente come modulo aggiuntivo in diverse installazioni di windows, è possibile aggiornarlo senza troppi problemi (anche se magari non alle ultime versioni, a versioni molto simili all'ultima). Per netframework non è sempre così, ad esempio su Vista e 7 è disponibile di base ma va aggiornato, su 2k (che è XP leggermente limitato) l'ultimo netframework disponibile è il 2.0 . Ora, io capisco non supportare più sistemi con una certa architettura, ma nt5 e nt6 sono molto simili, non supportarli pienamente entrambi è assurdo (imo). A livello commerciale no perchè spinge all'upgrade e l'azienda ci guadagna.
Tuttavia, siccome la msdn library non è facilmente scaricabile e la vedo un pochino confusionaria, devo farmi una lista di link utili.
Nota: Ormai visual basic "puro" non si può più usare salvo non si voglia usare il 6 che è un'implementazione del 1998. Le nuove avviano necessariamente una parte della macchina virtuale compresa nel package .net framework quindi script in visual basic sarebbero non poco pesanti (e poco portabili poichè a seconda del .net framework richiesto non è possibile eseguirli su alcuni sistemi win). Invece Visual basic for application ((posto di considerare solo office dal 2007 in poi, perchè gli office precedenti producono, loro stessi, semplicemente documenti poco stabili e quindi il lavoro si perde)) e VBscript sono decisamente utili, senza contare che la sintassi del basic non cambia molto qualora volessi puntare su implementazioni di basic open (gambas per esempio). Ora, basic è visto come "il male" ma non necessariamente è così, dipende dall'implementazione e dalle estensioni alla sintassi, comunque sia è potentissimo per sviluppare velocemente in modo compatto (con roba direttamente eseguibile senza altre richieste) roba semplice ma utile. Altri linguaggi per fare le stesse come (Pascal, C, etc..) richiedono più codice scritto e maggiori conoscenze (anche se, ovviamente, sono più professionali).
Link utili
(occhio che poi devi aggiornarli che la MSDN ogni tanto cambia)
Qualità MSDN library
Incredibile, è vero che ho letto abbastanza sul linguaggio basic (in vari dialetti molto simili) e mi sono sporcato un pochino le mani, ma anche senza comprare o ottenere alcun manuale relativo al basic, le sezioni sulla MSDN library dovrebbero bastare a dare una discreta conoscenza del linguaggio. Confermo con un pochino di ragionamento (ma forse sono influenzato dalle esperienze precedenti) si capisce parecchio, ad esempio ora ho capito che le property di un oggetto sono le funzioni GET (vedi link sezione precedente), mentre quando usavo VBA pensavo fossero variabili d'istanza.
PsPad VBScript.Def
utile per crearsi una libreria ai singoli comandi senza appesantire la lista dei link utili
; PSPad clip definition file for VBScript
;
; author: ing. Jan Fiala pspad@wo.cz
; last revision : 30.8.2003
;
;[Add | Adds a key and item pair to a Dictionary object]
;Add |key, item
;[Add | Adds a new Folder to a Folders collection]
;Add(|folderName)
;[BuildPath | Appends a name to an existing path]
;BuildPath(|path, name)
;[Clear | Clears all property settings of the Err object]
;Clear|
;[Close | Closes an open TextStream file]
;Close|
;[Copy | Copies a specified file or folder from one location to another]
;Copy destination|[, overwrite]
;[CopyFile | Copies one or more files from one location to another]
;CopyFile source, destination|[, overwrite]
;[CopyFolder | Recursively copies a folder from one location to another]
;CopyFolder source, destination|[, overwrite]
;[CreateFolder | Creates a folder]
;CreateFolder(|foldername)
;[CreateTextFile | Creates a specified file name and returns a TextStream object that can be used to read from or write to the file]
;CreateTextFile(|filename[, overwrite[, unicode]])
;[Delete | Deletes a specified file or folder]
;Delete |force
;[DeleteFile | Deletes a specified file]
;DeleteFile filespec|[, force]
;[DeleteFolder | Deletes a specified folder and its contents]
;;DeleteFolder folderspec|[, force]
;[DriveExists | Returns True if the specified drive exists; False if it does not]
;DriveExists(|drivespec)
;[Execute | Executes a regular expression search against a specified string]
;Execute(|string)
;[Exists | Returns True if a specified key exists in the Dictionary object, False if it does not]
;Exists(|key)
;[FileExists | Returns True if a specified file exists; False if it does not]
;FileExists(|filespec)
;[FolderExists | Returns True if a specified folder exists; False if it does not]
;FolderExists(|folderspec)
;[GetAbsolutePathName | Returns a complete and unambiguous path from a provided path specification]
;GetAbsolutePathName(|pathspec)
;[GetBaseName | Returns a string containing the base name of the file (less any file extension), or folder in a provided path specification]
;GetBaseName(|path)
;[GetDrive | Returns a Drive object corresponding to the drive in a specified path]
;GetDrive |drivespec
;[GetDriveName | Returns a string containing the name of the drive for a specified path]
;GetDriveName(|path)
;[GetExtensionName | Returns a string containing the extension name for the last component in a path]
;GetExtensionName(|path)
;[GetFile | Returns a File object corresponding to the file in a specified path]
;GetFile(|filespec)
;[GetFileName | Returns the last file name or folder of a specified path that is not part of the drive specification]
;GetFileName(|pathspec)
;[GetFolder | Returns a Folder object corresponding to the folder in a specified path]
;GetFolder(|folderspec)
;[GetParentFolderName | Returns a string containing the name of the parent folder of the last file or folder in a specified path]
;GetParentFolderName(|path)
;[GetSpecialFolder | Returns the special folder specified]
;GetSpecialFolder(|folderspec)
;[GetTempName | Returns a randomly generated temporary file or folder name that is useful for performing operations that require a temporary file or folder]
;GetTempName|
;[Items | Returns an array containing all the items in a Dictionary object]
;Items|
;[Keys | Returns an array containing all existing keys in a Dictionary object]
;Keys|
;[Move | Moves a specified file or folder from one location to another]
;Move |destination
;[MoveFile | Moves one or more files from one location to another]
;MoveFile |source, destination
;[MoveFolder | Moves one or more folders from one location to another]
;MoveFolder |source, destination
;[OpenAsTextStream | Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file]
;OpenAsTextStream(|[iomode, [format]])
;[OpenTextFile | Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file]
;OpenTextFile(|filename[, iomode[, create[, format]]])
;[Raise | Generates a run-time error]
;Raise(|number, source, description, helpfile, helpcontext)
;[Read | Reads a specified number of characters from a TextStream file and returns the resulting string]
;Read(|characters)
;[ReadAll | Reads an entire TextStream file and returns the resulting string]
;ReadAll|
;[ReadLine | Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string]
;ReadLine|
;[Remove | Removes a key, item pair from a Dictionary object]
;Remove(|key)
;[RemoveAll | The RemoveAll method removes all key, item pairs from a Dictionary object]
;RemoveAll|
;[Replace | Replaces text found in a regular expression search]
;Replace(|string1, string2)
;[Skip | Skips a specified number of characters when reading a TextStream file]
;Skip(|characters)
;[SkipLine | Skips the next line when reading a TextStream file]
;SkipLine|
;[Test | Executes a regular expression search against a specified string and returns a Boolean value that indicates if a pattern match was found]
;Test(|string)
;[Write | Writes a specified string to a TextStream file]
;Write(|string)
;[WriteBlankLines | Writes a specified number of newline characters to a TextStream file]
;WriteBlankLines(|lines)
;[WriteLine | Writes a specified string and newline character to a TextStream file]
;WriteLine(|[string])
;[AtEndOfLine | Returns True if the file pointer immediately precedes the end-of-line marker in a TextStream file; False if it is not. Read-only]
;AtEndOfLine|
;[AtEndOfStream | Returns True if the file pointer is at the end of a TextStream file; False if it is not. Read-only]
;AtEndOfStream|
;[Attributes | Sets or returns the attributes of files or folders. Read/write or read-only, depending on the attribute]
;Attributes |[= newattributes]
;[AvailableSpace | Returns the amount of space available to a user on the specified drive or network share]
;AvailableSpace|
;[Column | Read-only property that returns the column number of the current character position in a TextStream file]
;Column|
;[CompareMode | Sets and returns the comparison mode for comparing string keys in a Dictionary object]
;CompareMode|[ = compare]
;[Count | Returns the number of items in a collection or Dictionary object. Read-only]
;Count|
;[DateCreated | Returns the date and time that the specified file or folder was created. Read-only]
;DateCreated|
;[DateLastAccessed | Returns the date and time that the specified file or folder was last accessed. Read-only]
;DateLastAccessed|
;[DateLastModified | Returns the date and time that the specified file or folder was last modified. Read-only]
;DateLastModified|
;[Description | Returns or sets a descriptive string associated with an error]
;Description |[= stringexpression]
;[Drive | Returns the drive letter of the drive on which the specified file or folder resides. Read-only]
;Drive|
;[DriveLetter | Returns the drive letter of a physical local drive or a network share. Read-only]
;DriveLetter|
;[Drives | Returns a Drives collection consisting of all Drive objects available on the local machine]
;Drives|
;[DriveType | Returns a value indicating the type of a specified drive]
;DriveType|
;[Files | Returns a Files collection consisting of all File objects contained in the specified folder, including those with hidden and system file attributes set]
;Files|
;[FileSystem | Returns the type of file system in use for the specified drive]
;FileSystem|
;[FirstIndex | Returns the position in a search string where a match occurs]
;FirstIndex|
;[FreeSpace | Returns the amount of free space available to a user on the specified drive or network share. Read-only]
;FreeSpace|
;[Global | Sets or returns a Boolean value that indicates if a pattern should match all occurrences in an entire search string or just the first one]
;Global |[= True | False ]
;[HelpContext | Sets or returns a context ID for a topic in a Help File]
;HelpContext |[= contextID]
;[HelpFile | Sets or returns a fully qualified path to a Help File]
;HelpFile |[= contextID]
;[IgnoreCase | Sets or returns a Boolean value that indicates if a pattern search is case-sensitive or not]
;IgnoreCase |[= True | False ]
;[IsReady | Returns True if the specified drive is ready; False if it is not]
;IsReady|
;[IsRootFolder | Returns True if the specified folder is the root folder; False if it is not]
;IsRootFolder|
;[Item | Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write]
;Item(|key) [= newitem]
;[Key | Sets a key in a Dictionary object]
;Key(|key) = newkey
;[Length | Returns the length of a match found in a search string]
;Length|
;[Line | Read-only property that returns the current line number in a TextStream file]
;Line|
;[Name | Sets or returns the name of a specified file or folder. Read/write]
;Name |[= newname]
;[Number | Returns or sets a numeric value specifying an error. Number is the Err object's default property]
;Number |[= errornumber]
;[ParentFolder | Returns the folder object for the parent of the specified file or folder. Read-only]
;ParentFolder|
;[Path | Returns the path for a specified file, folder, or drive]
;Path|
;[Pattern | Sets or returns the regular expression pattern being searched for]
;Pattern |[= "searchstring"]
;[RootFolder | Returns a Folder object representing the root folder of a specified drive. Read-only]
;RootFolder|
;[SerialNumber | Returns the decimal serial number used to uniquely identify a disk volume]
;SerialNumber|
;[ShareName | Returns the network share name for a specified drive]
;ShareName|
;[ShortName | Returns the short name used by programs that require the earlier 8.3 naming convention]
;ShortName|
;[ShortPath | Returns the short path used by programs that require the earlier 8.3 file naming convention]
;ShortPath|
;[Size | For files, returns the size, in bytes, of the specified file. For folders, returns the size, in bytes, of all files and subfolders contained in the folder]
;Size|
;[Source | Returns or sets the name of the object or application that originally generated the error]
;Source |[= stringexpression]
;[SubFolders | Returns a Folders collection consisting of all folders contained in a specified folder, including those with Hidden and System file attributes set]
;SubFolders|
;[TotalSize | Returns the total space, in bytes, of a drive or network share]
;TotalSize|
;[Type | Returns information about the type of a file or folder. For example, for files ending in .TXT, "Text Document" is returned]
;Type|
;[Value | Returns the value or text of a match found in a search string]
;Value|
;[VolumeName | Sets or returns the volume name of the specified drive. Read/write]
;VolumeName |[= newname]
; Pier additions
; see http://gogogadgetscott.info/pspad/clips.htm
; format:
; [clip def]
; comments with link to msdn definition of the command (hoping that MS don't change the links)
; clip code
;
; For object code section, use separation semicolon breaks before and after.
; note for methods on object of Type T. Do this clip definition
; "TObject.MethodName"
; .MethodName|
[Dim | declare new variable. normal usage Dim varName {AS Type}]
; http://msdn.microsoft.com/en-us/library/zexdsyc0.aspx
Dim |
[Set | set an object to a variable]
; http://msdn.microsoft.com/en-us/library/4afksd44.aspx
Set |
[Sub | Sub procedure block]
; http://msdn.microsoft.com/en-us/library/tt223ahx.aspx
Sub | ()
End Sub
[iomodes | io modes to open a file]
; http://msdn.microsoft.com/en-us/library/hwfw5c59%28v=VS.85%29.aspx
Const ForReading = 1, ForWriting = 2, ForAppending = 8
|
[Format2openFile | format to open a file]
; http://msdn.microsoft.com/en-us/library/hwfw5c59%28v=VS.85%29.aspx
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
|
[Replace(expression, find, replacewith{, start{, count{, compare}}}) | Returns a string in which a specified substring has been replaced with another substring]
; http://msdn.microsoft.com/en-us/library/238kz954.aspx
Replace(|)
;
;OBJECTS SECTION
;OBJECTS SECTION
;
;WSCRIPT OBJECT SECTION
[Wscript | Calls the WSH main object]
; http://msdn.microsoft.com/en-us/library/at5ydy31%28v=vs.85%29.aspx
Wscript|
[WscriptObject.Arguments | returns a WSHarguments object]
; http://msdn.microsoft.com/en-us/library/z2b05k8s%28v=vs.85%29.aspx
Arguments|
[WScriptObject.Sleep(intTime) | Suspends script execution for a specified length of time, then continues execution]
; http://msdn.microsoft.com/en-us/library/6t81adfd%28v=vs.85%29.aspx
Sleep(|)
[WscriptObject.CreateObject(strProgID{,strPrefix}) | Creates a COM object]
; http://msdn.microsoft.com/en-us/library/xzysf6hc%28v=vs.85%29.aspx
CreateObject(|)
[WScriptObj.StdIn | Exposes the read-only input stream for the current script]
; http://msdn.microsoft.com/en-us/library/1y8934a7%28v=vs.85%29.aspx
StdIn
[WScriptObj.StdOut | Exposes the write-only output stream for the current script]
; http://msdn.microsoft.com/en-us/library/c61dx86d%28v=vs.85%29.aspx
StdOut
;
;
;WshArguments ObjSection
[WshArguments | returns a WSHarguments object, called on Wscript object]
; http://msdn.microsoft.com/en-us/library/ss1ysb2a%28v=vs.85%29.aspx
WScript.Arguments|
[WshArgumentsObject.Item(integer) | returns an item stored in WshArgumentsObject]
;http://msdn.microsoft.com/en-us/library/ss1ysb2a%28v=vs.85%29.aspx (description for item on wshArguments and not on generic object)
Item(|)
[WshArgumentsObject.Count | Returns the number of members in an WshArgumentsObject]
;http://msdn.microsoft.com/en-us/library/6x47fysb%28v=vs.85%29.aspx
Count|
;
;
;FileSystemObject
[FileSystemObject | returns a fileSystemObject (FSO)]
; http://msdn.microsoft.com/en-us/library/z9ty6h50%28v=VS.85%29.aspx#Y114
CreateObject("Scripting.FileSystemObject")|
[FileSystemObject.FileExists(filePath) | Returns True if a specified file exists; False if it does not]
; http://msdn.microsoft.com/en-us/library/x23stk5t%28v=VS.85%29.aspx
FileExists(|)
[FileSystemObject.FolderExists(folderPath) | Returns True if a specified folder exists; False if it does not]
; http://msdn.microsoft.com/en-us/library/5xc78d8d%28v=VS.85%29.aspx
FolderExists(|)
[FileSystemObject.GetFolder(folderPath) | Returns a Folder object corresponding to the folder in a specified path]
; http://msdn.microsoft.com/en-us/library/f1xtf7ta%28v=VS.85%29.aspx
GetFolder(|)
[FileSystemObject.OpenTextFile(filename{, iomode{, create{, format}}}) | Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file]
; http://msdn.microsoft.com/en-us/library/314cz14s%28v=VS.85%29.aspx
OpenTextFile(|)
[FileSystemObject.MoveFile(sourcePath, destinationPath) | Moves one or more files from one location to another]
; http://msdn.microsoft.com/en-us/library/2wcf3ba6%28v=VS.85%29.aspx
MoveFile(|)
[FileSystemObject.MoveFolder (sourcePath, destinationPath) | Moves one or more folders from one location to another]
; http://msdn.microsoft.com/en-us/library/465s5y8s%28v=VS.85%29.aspx
MoveFolder(|)
[FileSystemObject.CreateTextFile(filename{, overwrite{, unicode}}) | Creates a specified file name and returns a TextStream object]
; http://msdn.microsoft.com/en-us/library/5t9b5c0c%28v=VS.85%29.aspx
CreateTextFile(|)
;
;
; folder object
; http://msdn.microsoft.com/en-us/library/1c87day3%28v=VS.85%29.aspx
; folders collection
; http://msdn.microsoft.com/en-us/library/9kcx47hd%28v=VS.85%29.aspx
[FolderObject.Files | Returns a Files collection consisting of all File objects contained in the specified folder]
; http://msdn.microsoft.com/en-us/library/18b41306%28v=VS.85%29.aspx
Files
[FolderObject.SubFolders | Returns a Folders collection consisting of all folders contained in a specified folder]
; http://msdn.microsoft.com/en-us/library/e1dthkks%28v=VS.85%29.aspx
SubFolders
[FolderObject.Move(destinationPath) | Moves or Rename a specified folder from one location to another]
; http://msdn.microsoft.com/en-us/library/kxtftw67%28v=VS.85%29.aspx
Move(|)
;
;
; file object
; http://msdn.microsoft.com/en-us/library/1ft05taf%28v=VS.85%29.aspx
; file collection
; http://msdn.microsoft.com/en-us/library/wz72a8c0%28v=VS.85%29.aspx
[FileObject.OpenAsTextStream({iomode, {format}}) | Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file]
; http://msdn.microsoft.com/en-us/library/hwfw5c59%28v=VS.85%29.aspx
OpenAsTextStream(|)
[FileObject.Move(destinationPath) | Moves or Rename a specified file from one location to another]
; http://msdn.microsoft.com/en-us/library/kxtftw67%28v=VS.85%29.aspx
Move(|)
;
;
; textStream object
; http://msdn.microsoft.com/en-us/library/312a5kbt%28v=VS.85%29.aspx
; working with files
; http://msdn.microsoft.com/en-us/library/czxefwt8%28v=VS.85%29.aspx
[TextStreamObj.Read(charNumb) | Reads a specified number of characters from a TextStream file]
; http://msdn.microsoft.com/en-us/library/dhyx75w2%28v=VS.85%29.aspx
read(|)
[TextStreamObj.ReadLine() | Reads an entire line (up to, but not including, the newline character)]
; http://msdn.microsoft.com/en-us/library/h7se9d4f%28v=VS.85%29.aspx
ReadLine()|
;
;
;
Logical operation between bits
dim bitLogical
bitLogical = (0 and 2)
'dovrebbe effettuare l'and bit per bit tra 0 e 2
'ora 0 ha tutti zero mentre 2 solo uno, il risultato è solo 0'
wscript.stdout.writeline("Log op:" & bitLogical)
bitLogical = (1 and 2)
wscript.stdout.writeline("Log op:" & bitLogical)
'1 ha il primo bit ad uno, mentre 2 ha il secondo bit ad uno, sono sfasati e quindi ottengo 0'
bitLogical = (2 and 2)
wscript.stdout.writeline("Log op:" & bitLogical)
'2 e 2 sono uguali quindi torna l'identità'
bitLogical = (3 and 2)
wscript.stdout.writeline("Log op:" & bitLogical)
'3 e 2 hanno un bit ad 1 nella stessa posizione, quindi si torna 2'
bitLogical = (4 and 2)
wscript.stdout.writeline("Log op:" & bitLogical)
'4 e 2 non hanno nessun bit ad uno nella stessa posizione torna 0'
dim enumerate
enumerate = array((4+2),(8+2), (8+4+2))
'una serie di numeri con il secondo bit ad 1'
dim i
for i=0 to ubound(enumerate)
bitLogical = (enumerate(i) and 2)
wscript.stdout.writeline("Log op:" & bitLogical)
next
Jscript
E' il cugino di VBscript perchè esegue sempre sul windows script host (quindi molti link per vbscript sono riutilizzabili perchè gli oggetti forniti dal WSH sono uguali) ma dovrebbe essere simile a javascript, molto simile. In questo modo scrivere script per il WSH in jscript renderebbe questi, a differenza del vbscript, molto più portabili perchè di engine javascript ne esistono molti ed ha quanto ho capito adattare uno jscript ad uno javascript (se non si usano molte chiamate a funzioni offerte dal WSH) non costa molto.
Si, sulla stessa MSDN invece di Jscript scrivono chiaramente Javascript, quindi dovrebbe essere praticamente simile se non identico.
Link utili
WMI tools
(Con jscript + windows script host + wmi posso definitivamente dire che linux spacca ma windows non scherza solo che le cose pro di windows sono poco conosciute, ho scoperto questi fantastici strumenti in ritardissimo. Maledetto me)