Isaac Lyne
Isaac Lyne

Reputation: 300

Invoke-Command with credentials

I am doing an Invoke Command method using powershell and I need to know how to input credentials into the script. For example at the moment I have:

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

But I need to add Credentials all in one. I need it in a way it wont ask me to type in credentials, it just takes them from the script. Looking for something like this:

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

This is my context:

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);
    }
}

I have tried:

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);
    }
}

While doing this:

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

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

It says the name 'username' does not exist in the current context.

Upvotes: 2

Views: 13348

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200473

Build a PSCredential object from username and password and pass that to the -Credential parameter.

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

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

Invoke-Command ... -Credential $cred

Upvotes: 8

Related Questions