我怎样才能静默 运行 一个远程 PowerShell 命令而不必硬编码我的密码?

How can I silently run a remote PowerShell command without having to hard code my password?

我正在尝试 运行:

Invoke-Command -Computer $computer -ScriptBlock {...}

但我收到错误 "Access is denied" winrm 错误,我对使用以下内容犹豫不决:

Invoke-Command -Computer $computer -Credential $cred -ScriptBlock {...}

其中 $cred 是:

$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -
argumentlist $username, $secstr

必须是远程的运行而且必须是静音的。所以我不能让 PSCredential 弹出 window 中间脚本。

有人可以向我展示或指出可以引导我找到可能解决方案的文档吗?

提前致谢。

您可以做的一件事是加密密码并将其保存到磁盘。然后您可以读取该文件,并将加密的密码转换为安全字符串,并从中创建一个凭证对象。请注意,这必须使用将用于 运行 脚本的帐户来完成。

'$uper$secret1' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Set-Content .\AccountPass.txt

这会将您的密码以文本文件的形式保存到磁盘。如果您打开文本文件,它将看起来像:

01000000d08c9ddf0115d1118c7a00c04fc297eb01000000b584d55e9c47c942904dd30531d3ad070000000002000000000003660000c0000000100000003060266c3c4333a41e7f0e92176fb3d50000000004800000a000000010000000a2c8bbb2a3666c092004bb5e66fd440320000000636a413a6905789e0f3521cea3d8703405897cd5948da955192bcccd08990ffc1400000068c1

5f8ac088ef0972dfce7d5a20ff3bbcdac4cc 现在,创建该文件的帐户将是唯一可以解密它的帐户,但该帐户可以 运行:

$Password = Get-Content .\AccountPass.txt | ConvertTo-SecureString
$Creds = New-Object System.Management.Automation.PSCredential ("$env:UserDomain$env:UserName",$Password)

现在您有了一个凭据对象,而无需以明文形式保存密码。如前所述,唯一可以解密文本文件中密码的帐户是生成文本文件的帐户,并且每当更改密码时都必须更新文本文件。