Login Login
MORE

WIDGETS

Widgets

Wanted articles
Who is online?
Article tools

Difference between revisions of "Windows7:Script Tips"

From Aino Wiki

Jump to: navigation, search
(Shell DOS, Prompt comandi)
 
(No difference)

Latest revision as of 12:20, 17 July 2023

Windows ha due command shells (interprete comandi): la "Command shell" e "PowerShell". Ogni shell è un programma che fornisce diretta comunicazione tra l'operatore ed il sistema operativo o applicazione, fornendo un ambiente per automatizzare operazioni.

Shell DOS, Prompt comandi

Da command Prompt o finestra terminale DOS ecco un elenco di Tips sul come fare per

FileSystem

Copia

Doc microsoft

Copia cartella e sottocartelle

Es.:

x>xcopy C:\cartellaOrigine C:\cartellaDestinazione /S /E

Comando XCopy

XCOPY source [destination] [/A | /M] [/D[:date]] [/P] [/S [/E]] [/V] [/W]
                           [/C] [/I] [/Q] [/F] [/L] [/H] [/R] [/T] [/U]
                           [/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z]
                           [/EXCLUDE:file1[+file2][+file3]...]

  source       Specifies the file(s) to copy.
  destination  Specifies the location and/or name of new files.
  /A           Copies only files with the archive attribute set,
               doesn't change the attribute.
  /M           Copies only files with the archive attribute set,
               turns off the archive attribute.
  /D:m-d-y     Copies files changed on or after the specified date.
               If no date is given, copies only those files whose
               source time is newer than the destination time.
  /EXCLUDE:file1[+file2][+file3]...
               Specifies a list of files containing strings.  When any of the
               strings match any part of the absolute path of the file to be
               copied, that file will be excluded from being copied.  For
               example, specifying a string like \obj\ or .obj will exclude
               all files underneath the directory obj or all files with the
               .obj extension respectively.
  /P           Prompts you before creating each destination file.
  /S           Copies directories and subdirectories except empty ones.
  /E           Copies directories and subdirectories, including empty ones.
               Same as /S /E. May be used to modify /T.
  /V           Verifies each new file.
  /W           Prompts you to press a key before copying.
  /C           Continues copying even if errors occur.
  /I           If destination does not exist and copying more than one file,
               assumes that destination must be a directory.
  /Q           Does not display file names while copying.
  /F           Displays full source and destination file names while copying.
  /L           Displays files that would be copied.
  /H           Copies hidden and system files also.
  /R           Overwrites read-only files.
  /T           Creates directory structure, but does not copy files. Does not
               include empty directories or subdirectories. /T /E includes
               empty directories and subdirectories.
  /U           Copies only files that already exist in destination.
  /K           Copies attributes. Normal Xcopy will reset read-only attributes.
  /N           Copies using the generated short names.
  /O           Copies file ownership and ACL information.
  /X           Copies file audit settings (implies /O).
  /Y           Suppresses prompting to confirm you want to overwrite an
               existing destination file.
  /-Y          Causes prompting to confirm you want to overwrite an
               existing destination file.
  /Z           Copies networked files in restartable mode.

The switch /Y may be preset in the COPYCMD environment variable.
This may be overridden with /-Y on the command line.
Copia con caratteri speciali nel nome

La copia di file che hanno i seguenti caratteri nel nome fallirà a meno di usare caratteri di escape per codificarli:
< > ( ) & | , ; "
tali caratteri dovranno essere preceduti dal simbolo ^
Es.:
per copiare il file You&Me.txt dal prompt comandi di DOS:

C:\>copy "D:\Mia Cartella\You^&Me.txt" D:\CartellaDestinazione

Move, spostamento

Attualmente è un comando "interno" non lo è sempre stato. Seguono esempi d'uso:

c:\move c:\windows\temp\*.* c:\temp
 
C:\move stats.doc, morestats.doc c:\statistics

Sintassi:

To move one or more files:
MOVE [/Y | /-Y] [drive:][path]file name1[,...] destination

To rename a directory:
MOVE [/Y | /-Y] [drive:][path]dirname1 dirname2

[drive:][path]file name1	Specifies the location and name of the file or files you want to move.
destination	                Specifies the new location of the file. Destination can consist of a drive letter and colon, a directory name, or a combination. If you are moving only one file, you can also include a file name if you want to rename the file when you move it.
[drive:][path]dirname1	        Specifies the directory you want to rename.
dirname2	Specifies the new name of the directory.

/Y	Suppresses prompting to confirm you want to overwrite an existing destination file.
/-Y	Causes prompting to confirm you want to overwrite an existing destination file.

The switch /Y may be present in the COPYCMD environment variable. This switch may be overridden with /-Y on the command line. Default is to prompt on overwrites unless MOVE command is being executed from within a batch script.

Accodare più file in uno

Supponendo di avere in una sola cartella tutti i file, in formato ASCII, da copiare, accodandoli, Aprire una finestra terminale, e scrivere il seguente:

x>Copy *.* ContieneTutto.txt

Una applicazione pratica di questo procedimento può essere per copiare l'elenco di contatti dalla rubrica del cellulare in un unico file, per alternative leggere il supporto di Google. Si può trasferire via bluetooth da cellulare al PC l'intera rubrica questo produrrà un elenco di file vcf (VCards), il risultato è quello di avere n files dove n è il numero di contatti ottenuti.Come riunire in un unico file questo elenco? La risposta è nell'uso del comando indicato prima.

Cancellazione

Uso del comando Delete o brevemente Del

DEL [/P] [/F] [/S] [/Q] [/A[[:]attributes]] names
ERASE [/P] [/F] [/S] [/Q] [/A[[:]attributes]] names

Significato ed uso dei parametri:

/P	Prompts for confirmation before deleting each file.
/F	Force deleting of read-only files.
/S	Delete specified files from all subdirectories.
/Q	Quiet mode, do not ask if ok to delete on global wildcard
/A	Selects files to delete based on attributes
attributes	R Read-only files S System files H Hidden files A Files ready for archiving - Prefix meaning not

Cancellazione di file senza errore se non esiste!

C:\) if exist c:\folder\file.ext del c:\folder\file.ext

Stessa tecnica usata su una cartella:

C:\) if exist c:\folder\

NOTA il '\' finale obbligatorio.

Verifica se un file esiste

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Compressione di files o cartelle

Usando eseguibile
ZIP

In un batch file si userà un eseguibile che comprimerà la cartella\e in un univo file.
Nell'esempio seguente si userà "pkzip25.exe" (versione shareware autore PKWARE Inc.) reperibile da codesto sito pkzip
Il seguente script cancella (Del) il precedente file zip (Archivio.zip) se esistente (Exist), comprime nel file e apre l'explorer nella cartella di lavoro:

REM Spostamento cartella di lavoro
CD C:\Cartella da cui comprimere file o cartelle contenute

REM cancellazione precedente file
if exist "C:\Cartella da cui comprimere file o cartelle contenute\Archivio.zip" 
  DEL "C:\Cartella da cui comprimere file o cartelle contenute\Archivio.zip"

REM zip all files to transfer
pkzip25 -add -dir=relative "C:\Cartella da cui comprimere file o cartelle contenute\Archivio.zip"
"C:\Cartella da cui comprimere file o cartelle contenute\Dir con files\*"
 
explorer C:\Cartella da cui comprimere file o cartelle contenute
 
:END
PAUSE

Mentre per decomprimere ecco l'esempio:

@echo off
cls
 
echo .
rem ---------------------- ESTRAZIONE ---------------
echo ESTRAZIONE
 
rd C:\Deploy\Temp\Dir_destinazione\ /S/Q 
md C:\Deploy\Temp\Archivio
copy C:\Deploy\Repository\Archivio.zip C:\Deploy\Temp\Archivio\
cd C:\Deploy\Temp\Archivio\
C:\Deploy\Batches\pkzip25.exe -extr -dir Archivio.zip *
del Archivio.zip
 
:END
echo .
echo FINE
 
explorer C:\Deploy\Temp\MwSynchro
 
PAUSE
Installare pkzip25.exe

Un modo per rendere sempre disponibile il compressore è di installarlo con la seguente guida (anche come disinstallarlo).

  • Da una finestra terminale (eseguendo cmd) digitare
 regsvr32 PKZIP25.EXE

premere Enter

  1. Quindi per installarlo: scrivere: regsvr32 PKZIP25.EXE
  2. Per disinstallarlo: regsvr32 -u PKZIP25.EXE
7ZIP

Basta installare 7Zip che è un software openSource e che funziona benissimo con Windows 10 (a differenza dello ZIP citato prima che ora inizia ad avere problemi si "sicurezza").
7Zip è una Desktop Application ma nella cartella di installazione c'è un eseguibile che si può usare da linea comando ed è leggerissimo 460K, si chiama 7z.exe. La sintassi è simile a quella illustrata nello ZIP

 
Impostare una cartella come compressa

Istruzioni prese da articolo technet
Le cartelle o i file così impostati manterranno l'estensione naturale ma saranno memorizzate sul FileSystem in formato compresso.

Sintassi:

compact [{/c|/u}] [/s[:dir]] [/a] [/i] [/f] [/q] [FileName[...]]

Esempio, compressione di una data directory:

compact /c/s:percorsoDirectory nomeFilecompresso

CONTARE i files in cartelle

Il conteggio dovrà avvenire includendo le sottocartelle (subdirectory) e dovrà essere indipendentemente dalla lingua. Indipendente dalla lingua in quanto si una il FIND e questo comando effettua ricerche in testo

@echo off
cls
SET Count=0
SET dirPath="D:\Documenti\Fox_Australia\Dev\FOX.Dashboard.Apac"
@echo File count of:
@echo.%dirPath%
 
SET cmd="DIR %dirPath% /A-D /B /S | FIND /C /V """
 
FOR /F "tokens=*" %%i IN (' %cmd% ') DO SET Count=%%i
 
@ECHO.Il numero e'  %Count%
 
if %Count% lss 10 (
@echo[
@echo Error! Operation abort, script exit.
@echo[
goto :End_script
@
) else (
@echo[
@echo ok
@echo[
)
 
 
@echo[
@echo We do something ....
@echo[
 
:End_script

File più recente in cartella

Segue un esempio per ottenere il file più recente in una cartella:

echo off
for /f %%i in ('dir "\\Backup\DB\RS Bkp\SRC_Projects_IT_FromFile\*.bak" /b/a-d/od/t:c') do set LAST=%%i
echo The most recently created file is %LAST%

Retention - cancellare files vecchi

Il seguente script cancellerà i files xlsx più vecchi di 60 giorni

ForFiles /p "D:\Tmp\RetentionPolicy" /s /m *.xlsx /d -60 /c "cmd /c del /q @file"

Il Linguaggio di Scripting

Proveniente dal DOS, son stati aggiunti nuovi comandi ed istruzioni

IF

Esempio per la verifica se un file\directory esiste:
rem oppure:    if not exist
rem per le cartelle valutare così:  if exist "F:\tmp\*.*
rem per i nomi di files/cartelle con con spazi in mezzo usare i doppi apici all'inizio ed alla fine --> "nome file.ext"
 
if exist "F:\tmp\fileCivetta" (
    rem file Esiste
) else (
    rem file non esiste
)

Operatori usuali
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command


Operatori numerici

Operatore Significato
NEQ not equal
LSS less than
LEQ less than or equal
GTR greater than
GEQ greater than or equal

Esempio:

rem Get elapsed time:
set /A elapsed=end-start
rem Show elapsed time:
set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%
if %cc% lss 10 set cc=0%cc%

FOR

ToDo ...
Esempio 1

for /F "tokens=1-4 delims=:.," %%a in ("%time%") do (
   set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)

Esempio 2
Conteggio dei files presenti in una cartella.
La ricerca è fatta sfruttando l'OUTPUT del comando 'dir', in pratica acquisisce il numero antecedente la stringa "File(s)". Dare un'occhiata qui: stackoverflow.com

for /f %%A in ('dir ^| find "File(s)"') do set cnt=%%A
echo File count = %cnt%

Variabili

Si usa il comando SET, di default sono tutte stringe altrimenti si userà in aggiunta l'opzione /A<code> per indicare che la variabile conterrà un numero naturale.

echo off
cls
SET rootPath=\\Spxmiw3658\f$\6Backup\Digitalk_MaintenancePlan
SET fileFilter=\*.bak
SET fullPattern=%rootPath%%fileFilter%
ECHO %fullPattern%
 
SET /A numero1=123
SET /A numero2=977
SET /A numTot=%numero1% + %numero2%
ECHO %numTot%

Produrrà:

\\Spxmiw3658\f$\6Backup\Digitalk_MaintenancePlan\*.bak
1100

C:\> _

Argomenti CommandLine

Sono indicati con la percentuale seguita da un numero progressivo. Esempio se in uno script avessimo 3 parametri il seguente ne stamperebbe in output il contenuto:

@echo off 
echo %1 
echo %2 
echo %3

Commenti

REM Metodo 1 per commentare

:: Metodo 2 per commentare

Aprire Esplora risorse

Per aprire Esplora risorse su una cartella specifica:

x>Explorer "D:\Mia cartella"

Aprire Internet Explorer su pagina specifica

Per aprire Esplora risorse su una cartella specifica:

@echo Apertura url voluto..
start "C:\Program Files\Internet Explorer" IEXPLORE.EXE http://aino.it/Downloads/KT/Release_

Esecuzione come amministratore

Crea un file di testo e riversaci il contenuto:

del %temp%\sudo.tmp.vbs
@echo Set objShell = CreateObject("Shell.Application") > %temp%\sudo.tmp.vbs
@echo args = Right("%*", (Len("%*") - Len("%1"))) >> %temp%\sudo.tmp.vbs
@echo objShell.ShellExecute "%1", args, "", "runas" >> %temp%\sudo.tmp.vbs
@cscript %temp%\sudo.tmp.vbs
  1. Salvalo come SUDO.cmd
  2. Copia il file script di prima nella cartella C:\Windows\System32
  3. Ora per eseguire un programma con i privilegi di amministratore digita:
sudo cmd /k javaw.exe JAVA file

cmd /k Esegue il comando specificato nella stringa e rimane

GoTo

Il seguente esegue un loop infinito

@echo off
:Ciclo
 
telnet 10.10.10.10 5969
 
goto Ciclo

Chiamare un Bat da un Bat

Esempio di come chiamare uno script batch da un altro per molularizzare le funzioni.
Si suppongono 2 file batch, _uno.bat e _due.bat, _uno chimerà _due mediante il comando CALL.
Ecco cosa conterrà _uno.bat:

@echo off
del UnifiedCollector.exe.config
del UnifiedCollector.vshost.exe
del UnifiedCollector.vshost.exe.config
 
@echo Chiamata pulizia da DLL non modificate
Call _due.bat
 
pause

Ecco cosa conterrà _due.bat:

del Opc.Ua.Core.dll
del OpcLabs.BaseLibForms.dll
del OpcLabs.EasyOpcUAInternal.dll
del OpcLabs.EasyOpcUAInternal.xml
 
@echo fine pulizia DLL non modificate

BitLocker

Ecco come sbloccare 2 driver che sono protetti da BitLocker, poi RI-avviare Explorer e RI-avviare SQL Server e SQL Server Agent:

manage-bde -unlock D: -password
manage-bde -unlock F: -password
taskkill /im explorer.exe /f
start explorer.exe
net stop mssqlserver /y
net start mssqlserver
net stop SQLSERVERAGENT /y
net start SQLSERVERAGENT

Lo script che sarà un classico file <code>.bat dovrà essere eseguito in modalità amministratore.
I comandi net stop sono seguiti da /y allo scopo di non chiedere conferma all'utente dello stop del servizio.

Varie

  • Visualizzare l'utente corrente:
whoami

che può produrre ad es:

  • dominio\UserName_UtenteSistemaOperativo
  • nt service\mssqlserver

Power Shell

Guida interna: PowerShell

Mappa e Link


Windows 7

Keys: Command Prompt