.bat上的%userprofile%无效

问题描述 投票:0回答:1

我在.bat的脚本如下:

@echo off
mode 34,18
color f0
start /min "" "%userprofile%\Arquivos Extratos"&start CieloTan.iim"
echo.
echo.
echo Extraindo os Extratos...
echo Aguarde...
echo.
echo.
timeout /nobreak /t 300 >nul 2>nul
cls
echo.
echo.
echo Ajustando Arquivo de texto...
echo Aguarde...
echo.
echo.
ren "%userprofile%\Documents\iMacros\Downloads\extract.csv" "extract.txt" >nul 2>nul
move "%userprofile%\Documents\iMacros\Downloads\extract.txt" "%userprofile%\Arquivos Extratos\extract.txt" >nul 2>nul
set "$file=extract.txt"
set "$search=Previsto"
set $repl[2]=TOTAL         
set $repl[3]=Visa            
set $repl[4]=Mastercard  
set $repl[5]=Amex          
set $repl[6]=Sorocred     
set $repl[7]=Elo              
set $repl[8]=Diners         
set $repl[9]=Agiplan       
set $repl[10]=Banescard   
set $repl[11]=Cabal          
set $repl[12]=Credsystem 
set $repl[13]=Hipercard   
set $repl[14]=Credz         
set $repl[15]=Hiper          
setlocal enabledelayedexpansion
set $count=1
(for /f "delims=" %%a in (%$file%) do (
   call:replace "%%a" !$count!
   set/a $count+=1
   )
)> "Futuros Cielo Tan.txt"
echo. >> "Futuros Cielo Tan.txt"
echo ---  FUTUROS CIELO TAN --- >> "Futuros Cielo Tan.txt"
del extract.txt
mkdir "c:\Users\%username%\Desktop\Extratos Banco"
move "Futuros Cielo Tan.txt" "c:\Users\%username%\Desktop\Extratos Banco"
exit/b
:replace
set "$line=%~1"
set $repl=!$repl[%2]!
set "$line=!$line:%$search%=%$repl%!"
echo !$line!
if "%2"=="1" echo.
if "%2"=="2" echo.

但是代码的以下部分存在错误:

mkdir "c:\Users\%username%\Desktop\Extratos Banco"
move "Futuros Cielo Tan.txt" "c:\Users\%username%\Desktop\Extratos Banco"

当脚本运行时,它在“C:\ Users”中创建一个名为“Desktop \ Extratos Bancos”的文件夹。它无法识别我当前的用户名。有人能帮我吗?


请参见下图,其中创建目录:

Directory tree

batch-file
1个回答
1
投票

与你的头衔相反,它是username,而不是userprofile似乎是问题的根源。

通常情况下,操作系统会设置这两个变量(以及其他变量),并且它被视为改变其内容的糟糕编程习惯。

我怀疑前一批已经改变了username - 这对于没有经验的游戏者来说是一个有吸引力且有意义的变量名。

缺乏经验的另一个迹象是在setlocal之后没有@echo off命令。虽然这不是强制性的,但它确保批次结束时废弃对批次环境的更改,因此它们不会随着连续的批次运行而累积。

因此,我会检查username在启动此批次时是非空的,所以也许添加

echo username=%username%
if not defined username echo no username&pause&goto :eof

@echo off之后发出警告并中止。

在脚本的其他地方,使用userprofile。我看不出任何理由将有关线路改为c:\users\%username%,因为这通常与%userprofile%相同。


发布相关细节后:

@ECHO OFF
SETLOCAL
SET "user_name=!M D!"
SET "destdir=U:\destdir"
SETLOCAL ENABLEDELAYEDEXPANSION
DIR /ad "%destdir%"
ECHO ---------------------------------
MD "%destdir%\%user_name%\Banquo's ghost"
DIR /ad "%destdir%"
ECHO ---------------------------------
SETLOCAL DISABLEDELAYEDEXPANSION
MD "%destdir%\%user_name%\Banquo's ghost"
DIR /ad "%destdir%"
ECHO ---------------------------------

GOTO :EOF

问题是你的用户名是!M D!并且你调用了delayedexpansion所以批量替换变量username的值(我使用user_name,因为我不喜欢更改系统集变量)因此...!M D!...然后替换为空的M D的值。

上面的演示重复你的情况,报告当前创建目录的尝试,然后治愈 - 关闭delayedexpansion

© www.soinside.com 2019 - 2024. All rights reserved.