所以我的问题来自于想要使用批处理从文本文件中获取特定数字。这是我试图阅读的文本文件
Force user logoff how long after time expires?: Never
Minimum password age (days): 0
Maximum password age (days): 40
Minimum password length: 7
Length of password history maintained: None
Lockout threshold: Never
Lockout duration (minutes): 30
Lockout observation window (minutes): 30
Computer role: WORKSTATION
The command completed successfully.
正如您所看到的,它只是批量net accounts
命令的标准输出。我想要做的是保护计算机密码策略,但如果他们想要撤消它,也要备份。我有脚本来保护它,但撤消它是困难的部分。这个输出来自我创建的备份。我试图从此文件中获取旧的最小密码期限,最长密码期限和最小密码长度。它们目前是0,40和7。
我是批量编程的新手,所以任何帮助都将不胜感激。再次感谢
答案 0 :(得分:1)
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q45181780.txt"
FOR %%a IN (minpassage maxpaxxage minpasslen) DO SET "%%a="
FOR /f "usebackqtokens=1*delims=:" %%a IN ("%filename1%") DO (
IF "%%a"=="Minimum password age (days)" SET /a minpassage=%%b
IF "%%a"=="Maximum password age (days)" SET /a maxpassage=%%b
IF "%%a"=="Minimum password length" SET /a minpasslen=%%b
)
ECHO Min pass age=%minpassage%
ECHO Max pass age=%maxpassage%
ECHO Min pass len=%minpasslen%
:: adding in the "net account" command
:: Note that this command is merely ECHOed for testing.
:: If all seems in order, remove the "ECHO " from the following command
ECHO net accounts /minpwlen:%minpasslen%
GOTO :EOF
您需要更改sourcedir
的设置以适合您的具体情况。
我使用了一个名为q45181780.txt
的文件,其中包含我的测试数据。
清除要使用的变量(以防它们已经获得指定的值)
阅读文件的每一行,在:
上进行标记并将第一个标记分配给%%a
,将第二个标记分配给%%b
。如果%%a
与重要字符串匹配,请使用set /a
设置变量(因为这些数据项是数字的)
报告。
答案 1 :(得分:1)
以下是我的表现,(特定语言):
@Echo Off
For %%A In (min max len) Do Set "%%A="
For /F "Tokens=2 Delims=:" %%A In ('Find "imum"^<"accountinfo.txt"'
) Do For %%B In (%%A) Do If Not Defined min (Set "min=%%B"
) Else If Not Defined max (Set "max=%%B") Else Set "len=%%B"
For %%A In (min max len) Do Set %%A
Pause
请记得将accountinfo.txt更改为实际网络帐户输出文件的名称。
<小时/> 您还应该能够只读取值而不输出到文本文件:
@Echo Off
For %%A In (min max len) Do Set "%%A="
For /F "Tokens=2 Delims=:" %%A In ('Net Accounts^|Find "imum"'
) Do For %%B In (%%A) Do If Not Defined min (Set "min=%%B"
) Else If Not Defined max (Set "max=%%B") Else Set "len=%%B"
For %%A In (min max len) Do Set %%A
Pause
答案 2 :(得分:1)
受到Compo第二批的启发,我想为什么不从文本中获取变量名称:
> type PassMinMax.cmd
@Echo off
For /F "tokens=1,2delims=:" %%A in ('net accounts^|find "imum"'
) Do For /f "tokens=1-3" %%C in ("%%A") Do @Set /A %%D_%%C_%%E=%%B
Set Pass
示例输出:
> PassMinMax.cmd
password_Maximum_age=42
password_Minimum_age=0
password_Minimum_length=0
答案 3 :(得分:1)
这可以通过在PowerShell中使用正则表达式解析每一行来实现。
$lines = Get-Content -Path ./parsepw.txt
foreach ($line in $lines) {
if ($line -match '\s*Minimum password age \(days\):\s*([0-9]*)\w*') { $minpwage = [int]$Matches[1] }
elseif ($line -match '\s*Maximum password age \(days\):\s*([0-9]*)\w*') { $maxpwage = [int]$Matches[1] }
elseif ($line -match '\s*Minimum password length:\s*([0-9]*)\w*') { $minpwlen = [int]$Matches[1] }
}
$minpwage
$maxpwage
$minpwlen