隐藏在控制台中输入的密码-批处理脚本 [英] Hide Password typed in Console - Batch script

查看:356
本文介绍了隐藏在控制台中输入的密码-批处理脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

BAT文件中使用的Powershell命令消除了用户在控制台中指定的密码中可用的转义字符并将其保存在文件中.

Powershell command used in BAT file is eliminating the escape character available in the password specified by user in the console and saving it in a file.

我有一个BAT脚本,它提示用户在控制台中指定密码.用户在控制台中输入密码时,密码应屏蔽为*****.密码将类似于wel!123.该密码被保存到变量中,最后被复制到文本文件中.我几乎没有建议在BAT文件中使用以下代码,但是实际密码(Wel!123)中的转义字符已消除,并将密码Wel123保存到login.txt文件中.

I have a BAT script which prompt the user to specify the password in console. Password should be masked as ***** while user typing it in console. Password will be something like wel!123. This password is saved into variable and finally getting copied to a text file. I got few suggestion use the below code in my BAT file, but the escape character in the actual password( Wel!123) is getting eliminated and saving the password as Wel123 into login.txt file.

SetLocal
set "psCmd=powershell -Command "$pwd = read-host 'Enter Your Password' - 
AsSecureString; $BSTR= 
[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd); 
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /F "usebackq delims=" %%# in (`%psCmd%`) do set "pwd=%%#"

@echo %pwd%>>login.txt

推荐答案

!字符消失与PowerShell无关-它建议cmd.exeenabledelayedexpansion选项为实际上,在这种情况下,!用作变量名定界符-在这种情况下,隔离的是!字符.只是丢弃.

! characters disappearing is unrelated to PowerShell - it suggests that cmd.exe's enabledelayedexpansion option is in effect, in which case ! serves as a variable-name delimiter - and in which case isolated ! chars. are simply discarded.

顺便说一句:!因此不是转义字符.

As an aside: ! is therefore not an escape character.

因此,您需要:

  • 使用setLocal disabledelayedexpansion 禁用延迟变量扩展:

  • Disable delayed variable expansion with setLocal disabledelayedexpansion:

  • 请注意,默认情况下延迟扩展是 off ,因此您环境中的某些设备必须已将其打开.
  • Note that delayed expansion is off by default, so something in your environment must have turned it on.

此外,如 Squashman 指出的那样,^字符-cmd.exe的转义字符.用不带引号的字符串表示-将被吃掉",因此您必须转义所有^字符.为^^ ,您可以使用 %pwd:^=^^% .

Additionally, as Squashman points out, ^ characters - cmd.exe's escape char. in unquoted strings - would be "eaten", so you must escape all ^ chars. as ^^, which can you do with %pwd:^=^^%.

将它们放在一起:

@echo off
setLocal disabledelayedexpansion

set "psCmd=powershell -Command "$pwd = read-host 'Enter Your Password' -AsSecureString; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd); [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""

for /F "usebackq delims=" %%# in (`%psCmd%`) do set "pwd=%%#"

echo %pwd:^=^^%>>login.txt

这篇关于隐藏在控制台中输入的密码-批处理脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆