Samselvaprabu
Samselvaprabu

Reputation: 18237

How to ensure that password is entered?

I am trying to get password from user.

If he simply enter nothing [just press the enter key alone], then warning should be thrown.

$NewUserPassword = Read-Host -assecurestring "Please enter New Run time user password"

$NewUserPassword=$NewUserPassword.Trim()
If ( ($NewUserPassword -eq $null) -or ($NewUserPassword -eq "") ){

    Write-Warning "Please enter valid password. Script execution is stopped"
    Exit
}

But script throws error as follows

Method invocation failed because [System.Security.SecureString] doesn't contain a method named 'Trim'.

But if i remove trim() method ,the application still doesn't throw warning.

What could be the reason? How to get valid password?

Upvotes: 1

Views: 835

Answers (3)

Sunny Chakraborty
Sunny Chakraborty

Reputation: 405

Did you try using Get-Credential ? You can store passwords, save them to a file and use that later

$password = Get-Credential $password.Password

Upvotes: 1

jon Z
jon Z

Reputation: 16646

  1. If you convert the SecureString to a String you can use the trim() member function on this object. This might also be handy if you want to perform other checks (password complexity ...)

    $NewUserPassword = ([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($NewUserPassword))).trim()
    
  2. Alternatively you could use length property of the SecureString object. Important: Passwords containing only spaces, will have a length greater than 0.

Upvotes: 1

Chris N
Chris N

Reputation: 7499

You cannot inspect the value of a SecureString instance directly and comparing with a String instance is futile anyway. However, it has a Length property which you can use for checking whether it is empty:

$NewUserPassword = Read-Host -assecurestring "Please enter New Run time user password"
If ($NewUserPassword.Length -eq 0){
    Write-Warning "Please enter valid password. Script execution is stopped"
    Exit
}

Upvotes: 3

Related Questions