Skip to content

cmd

Windows Home Profile

Percorso Profilo Utente di Windows

La variabile %HOMEPROFILE% contiene il percorso del profilo corrente, tipicamente:

c:\Users\username

mentre la cartella dei documenti è di default la sua sottocartella Documents quindi:

c:\Users\username\Documents

tuttavia il nome della cartella Documents è configurabile e potrebbe essere stato impostato a piacere, per cui non si può dare per scontato che il percorso %HOMEPROFILE%\Documents sia sempre quello corretto.

Il percorso corretto è registrato nella seguente posizione del registro di Windows:

λ reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v Personal

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
    Personal    REG_SZ    C:\Users\username\Documents

Alcuni linguaggi di programmazione mettono a disposizione librerie e funzioni apposite per interrogare il registro, mentre con la shell è necessario utilizzare uno script apposito.

Script di lettura Percorso

Il seguente script legge il percorso richiesto, e lo memorizza nella variabile %value%:

@echo OFF
setlocal ENABLEEXTENSIONS

set KEY_NAME="HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
set VALUE_NAME="Personal"

for /F "tokens=2*" %%A IN ('reg query %KEY_NAME% /v %VALUE_NAME%') do (
    set value=%%B
)
echo %value%

questo script sembra funzionare sia con le versioni più recenti di Windows che con le precedenti, e supporta percorsi con gli spazi.

Cut a fixed width text file in CMD

I recently had the need to cut a fixed width text file at a certain column, and I had to do it in the Windows 10 world, without any particular utility.

In linux it would be rather simple, thanks to the cut command:

$ cut -c -10 example.txt

On my windows machines there's always Perl available, and one alternative solution would be using one liner substitution:

perl -pe s/(.{10}).*/$1/ example.txt

but on my colleagues machines there are no particular utilities installed, so I had to create the following script:

@echo off
setlocal EnableDelayedExpansion
for /f "delims=" %%r in (example.txt) do (
    set s=%%r
    echo !s:~0,10!
)

it's still possible to use a single line command, without the need of a .cmd script, but firts we have to launch the prompt with a special parameter cmd /v which indicates that delayed expansion is enabled (it is disabled by default to be compatible with MS-DOS 2.0 batch files!). After we launch cmd /v the command becomes:

for /f "delims=" %r in (example.txt) do @(set s=%r && echo !s:~0,10!)

not really intuitive, is it? I think I am missing my teenager days when I used to program Assembly x86: that was complex, but for good reasons. Cmd scripting is still complicated, but for no knowns reasons! Also, please note that this solution is painfully slow.