What is the equivalent to linux's expect in windows? Is there a way for a script to send a password when prompted to by a previous command?
runas /user:admin net user username /add
Trying echo XYZ | runas ...
I got 1326 Logon failure: unknown user name or bad password
. The command works without the piped echo.
There is nothing built into PowerShell. However there is a module that should be able to do this called Await
- https://msconfiggallery.cloudapp.net/packages/Await/
There is a PowerShell Summit session on how to use Await here - https://www.youtube.com/watch?v=tKyAVm7bXcQ
There is no direct equivalent to expect
in Windows that I know of, although you can doubtless write one without too much difficulty. Fortunately, for the special case of supplying credentials in PowerShell, there's a better way, one which doesn't even store passwords in plaintext in the script. This answer to Batch scripting, Powershell, and not triggering the UAC in Windows* starts by saving the user password somewhere as a secure string**:
$pass = Read-Host -AsSecureString
ConvertFrom-SecureString $pass | Out-File pass.txt
Then running the program as administrator with the stored password this way:
function Invoke-ElevatedCommand([String]$FileName, [String]$Arguments) {
$pass = Import-SecureString (Get-Content pass.txt)
$startinfo = New-Object System.Diagnostics.ProcessStartInfo
$startinfo.UserName = "administrator"
$startinfo.Password = $pass
$startinfo.FileName = $FileName
$startinfo.Arguments = $Arguments
[System.Diagnostics.Process]::Start($startinfo)
}
Invoke-ElevatedCommand "net" "user username /add" # Or whatever you need
* Note that this is almost a dupe, but not quite, since the accepted answer is not particularly relevant to this question. Linked answer lightly adapted for the purpose, and upvoted accordingly.
** Note further that, while pass.txt
is not plaintext, it's not safe to leave lying around where just anyone can grab it. Stick some restrictive NTFS permissions on it, maybe EFS, etc.
Sorry, I don't know how linux's expect works... However, at this post there is a Batch-file solution for a problem similar to yours and titled "Automatically respond to runas from batch file":
@if (@CodeSection == @Batch) @then
@echo off
start "" runas /user:testuser c:/path/to/my/program.exe
CScript //nologo //E:JScript "%~F0"
goto :EOF
@end
WScript.CreateObject("WScript.Shell").SendKeys("password{ENTER}");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With