管理 Invoke-RestMethod 请求的凭据

Manage credentials for Invoke-RestMethod request

我正在编写一个 PowerShell 脚本来查询应用程序 API (Qualys),第一步是进行身份验证。我只能不安全地做:

[string]$username = "username"
[string]$password = "superpassword"

$hdrs= @{"X-Requested-With"="Powershell"}

$base = "https://application-base-url/api/2.0/fo"
$body= "action=login&username=$username&password=$password"
Invoke-RestMethod -SessionVariable sess -Headers $hdrs -URI "$base/session/" -Method POST -Body $body 

它有效,但如您所见,用户名和密码存储在文件中。我希望 Powershell 提示我用户名和密码,并在安全管理它们的同时使用它进行身份验证。

我尝试使用 Get-Credential,但无法正常工作。有人可以帮忙吗?

显然您需要在正文中输入 plain-text 密码。

要从使用 Get-Credential 获得的凭据对象中检索它,请使用:

$cred = Get-Credential

$username = $cred.UserName
$password = $cred.GetNetworkCredential().Password  # --> the password as plain-text