Powershell 启动进程-凭据

Powershell 启动进程-凭据

我似乎在使用 powershell 运行提升的管理时遇到了一些问题。

说实话,我对 powershell 不太擅长。

因此我正在运行这个脚本[powershell -command "Start-Process iexplore -Verb -RunAs"]。

我知道 powershell Start-Process cmdlet 有参数 -Credential。

但是当我执行 Get-Help Start-Process 时,它并没有解释这个参数,而且谷歌也没有给我提供任何帮助。

最后运行 -RunAs 会调用我的本地管理员而不是我的 AD 管理员 ID,这样就没问题了。

我想知道如何在 powershell Start-Process 行中实际插入我的用户 ID/密码。

在命令提示符中运行 RunAs 效果并不好,但我知道使用“/User:[用户] 密码”会更容易。

答案1

-credential 参数的使用方式如下:

-credential "ComputerNameOrIP\admin"

例子:

-credential "192.168.1.1\admin\"

-credential "SomeComputerName\SomeUsername"

对于域帐户,只需使用域名而不是计算机名,其工作原理相同。

如果您正确使用它,在启动时,它将生成一个登录屏幕,您只需在其中输入密码并单击“确定”即可。

您可以将密码存储在外部文件中,然后在脚本中使用它。

 read-host -assecurestring | convertfrom-securestring | out-file C:\pass.txt

$password = get-content C:\pass.txt | convertto-securestring

$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "UserName",$password

答案2

-Credential 参数也可以与对象一起使用System.Management.Automation.PSCredential,这样更安全。在 Powershell 中,你可以使用以下命令创建此类型的对象

$UserName = 'domainpart\userIdPart'
$SecureStringPassword = Get_Password $UserName
$Credential = New-Object System.Management.Automation.PSCredential($UserName,$SecureStringPassword)
Start-Process $SomeExe -Credential $Credential ... 

然后,您必须实施function Get_Password某种安全方法来检索密码。从文本文件中读取明文密码并不是解决问题的办法。正如 Zeitlin 上面所说,这可能是人们能想到的最糟糕的安全做法 - 甚至比将密码贴在屏幕上更糟糕。

相反,将密码作为加密字符串存储在 .txt 文件中,如下所示。首先,获取密码作为输入,对其进行加密,然后存储加密字符串:

function Global:Get_PasswordFileName($Username)
{
    $baseName = "encrypted_$UserName.txt" -replace '\','_'
    "${env:LOCALAPPDATA}\$baseName"
}

$encryptedString = Read-Host -AsSecureString "Enter password for $UserName" | convertfrom-securestring
$passwordFileName = Get_PasswordFileName $Username
[System.IO.File]::WriteAllLines($passwdFileName, $encryptedString)

写入文件的方法有很多种,[System.IO.File]::WriteAllLines这只是其中一种,并且Get_PasswordfileName可以进行调整以使用任何合理的目录。

然后定义Get_Password

function Global:Get_Password($UserName)
{
    $passwordFileName = Get_PasswordFileName $Username
    $EncryptedString = Get-Content $passwordFileName
    ConvertTo-SecureString $EncryptedString
}

相关内容