What would be the Windows batch equivalent for HTML's input type=“password”?

前端 未结 12 2144
有刺的猬
有刺的猬 2020-12-01 18:51

I need to get authentication credentials from the users within a Windows script but the classic \"first Google result\" approach:

SET /P USR=Username: 
SET /         


        
12条回答
  •  忘掉有多难
    2020-12-01 19:29

    Another approach is to call PowerShell commands from your Batch script. Here's an example that configures the logon account of a service:

    $password = Read-Host "Enter password" -AsSecureString;
    $decodedpassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password));
    & "sc.exe" config THE_SERVICE_NAME obj= THE_ACCOUNT password= $decodedPassword;
    

    where THE_SERVICE_NAME is the name of the service to configure and THE_ACCOUNT is the logon account.

    Then we can use it from a batch script like that:

    call powershell -Command "$password = Read-Host "Enter password" -AsSecureString; $decodedpassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)); & "sc.exe" config THE_SERVICE_NAME obj= THE_ACCOUNT password= $decodedPassword;"
    

    which is simply calling PowerShell.exe and passing the three commands.

    The advantage of this approach is that the majority of Windows installations today include PowerShell, so no extra program or script is needed. The drawback is that you will need to either use the password inside the PowerShell call (like in my example) or store it in an environment variable and then use it from your batch script. I preffer the former because it is more secure and simpler.

提交回复
热议问题