具有凭据的Invoke-Command

时间:2018-04-25 21:10:32

标签: c# powershell

我正在使用powershell执行一个Invoke Command方法,我需要知道如何在脚本中输入凭据。例如,目前我有:

Invoke-Command -ComputerName 0.0.0.0 -ScriptBlock { Get-Command }

但我需要一次性添加凭据。我需要它的方式,它不会要求我输入凭据,它只是从脚本中获取它们。寻找这样的东西:

Invoke-Command -ComputerName 0.0.0.0 -ScriptBlock { Get-Command } -Credential username ,password

这是我的背景:

private void button1_Click(object sender, EventArgs e) {
    try {
        richTextBox1.Clear();
        if (RunRemotely == true) {
            richTextBox1.Text = RunScript("Invoke-Command -ComputerName" + richTextBox3.Text + " -ScriptBlock { " + richTextBox2.Text + "} -Credential $cred");
        } else {
            richTextBox1.Text = RunScript(richTextBox2.Text);
        }
    } catch (Exception error) {
        richTextBox1.Text += String.Format("\r\nError in script : {0}\r\n", error.Message);
    }
}

我试过了:

private void button1_Click(object sender, EventArgs e) {
    try {
        richTextBox1.Clear();
        if (RunRemotely == true) {
            $username = 'foo'
            $password = 'bar'
            $secpw = ConvertTo - SecureString $password - AsPlainText - Force
            $cred = New - Object** Management.Automation.PSCredential($username, $secpw)

            richTextBox1.Text = RunScript("Invoke-Command -ComputerName" + richTextBox3.Text + " -ScriptBlock { " + richTextBox2.Text + "} -Credential $cred");
        } else {
            richTextBox1.Text = RunScript(richTextBox2.Text);
        }
    } catch (Exception error) {
        richTextBox1.Text += String.Format("\r\nError in script : {0}\r\n", error.Message);
    }
}

这样做:

$username = 'foo'
$password = 'bar'

$secpw = ConvertTo - SecureString $password - AsPlainText - Force
$cred = New - Object Management.Automation.PSCredential($username, $secpw)

它的名字是'用户名'在当前背景下不存在。

1 个答案:

答案 0 :(得分:1)

从用户名和密码构建PSCredential对象,并将其传递给-Credential参数。

$username = 'foo'
$password = 'bar'

$secpw = ConvertTo-SecureString $password -AsPlainText -Force
$cred  = New-Object Management.Automation.PSCredential ($username, $secpw)

Invoke-Command ... -Credential $cred