2012-08-01 46 views
1

我想從用戶那裏得到密碼。如何確保輸入密碼?

如果他只是簡單地輸入任何東西[只需按Enter鍵],那麼應該拋出警告。

$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 
} 

但是腳本如下

方法調用失敗,因爲[爲System.Security.SecureString] 不包含名爲 '修剪' 方法拋出錯誤。

但是,如果我刪除trim()方法,應用程序仍然不會引發警告。

可能是什麼原因?如何獲得有效的密碼?

回答

3

您無法直接檢查SecureString實例的值,並且與String實例進行比較無論如何都是徒勞的。然而,它有一個Length屬性,它可以用於檢查它是否是空:

$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 
} 
1
  1. 如果轉換SecureStringString可以使用trim()成員函數這個對象上。這也可能是方便的,如果你想進行其他檢查(密碼複雜性......)

    $NewUserPassword = ([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($NewUserPassword))).trim() 
    
  2. 另外,您可以使用SecureString對象的length財產。 重要提示:只包含空格密碼,將有一個長度大於0

1

更大您是否嘗試過使用Get-憑據? 你可以存儲密碼,將它們保存到一個文件,並使用以後

$密碼= GET-憑證 $ password.Password