Invoke-Command with credentials - c#

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.

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

Related

The Term Connect-ExchangeOnline is not recognized name of cmdlet, function, script file or operable program

I am trying to connect with office365 PowerShell. I had also imported the module "ExchangeOnlineManagement". I'm getting the below exception:
"The term Connect-ExchangeOnline is not recognized as cmdlet, function , script or operable problem".
string script = #"
Set-ExecutionPolicy Unrestricted
$user = '<your username>'
$pwd = '<your password>'
$SecurePass = ConvertTo-SecureString -AsPlainText $pwd -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user,$SecurePass
Import-Module -Name ExchangeOnlineManagement
Connect-ExchangeOnline -Credential $Cred
";
try
{
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
Pipeline pipe = runspace.CreatePipeline();
pipe.Commands.AddScript(script);
try
{
var results = pipe.Invoke();
}
catch (Exception e)
{
}
var error = pipe.Error.ReadToEnd();
if (error.Count > 0)
{
foreach (PSObject err in error)
{
//more logging not sharing that code
}
}
}
}
catch (Exception ex)
{ }

WPF UI passing output from powershell function into textbox

I am creating a WPF UI and I am having trouble getting the output from a foreach loop within a function into a WPF textbox. The variables I need to output ar $id $newValue and $serviceName
#Iteration through services perform string replacement
ForEach ($Response in $Responses ) {
$id = $Response.id
$newValue = $Response.value.Replace("\Service", "")
$serviceName = $Response.serviceName
Write-Output $id
Write-Output $serviceName
Write-Output $newValue
#if statement here for testing this should be removed
if ($id -eq ) {
$Payload = #{
hostName = '';
hostOperatingSystem = 0;
optionalFilter1 = '';
optionalFilter2 = '';
description = '';
serviceName = $serviceName;
sectionName = "Services";
signature = 'null';``
value = $newValue
} | ConvertTo-Json -Depth 10
#Service Configuration API PUT method call to update fullpath value
$newURI = $URI + '/' + $id
$Response = Invoke-RestMethod -Uri $newURI -Method PUT -Headers $Headers -Body $Payload -ContentType 'application/json'
}
#here for testing this should be removed
else {
$output.text = "Nothing to do"
}
}
$output.text = "Done!"
}
[xml]$Form = Get-Content "MainWindow.xaml"
$NR = (New-Object System.Xml.XmlNodeReader $Form)
$Win = [Windows.Markup.XamlReader]::Load($NR)
$URL = $win.FindName("URL")
$cid = $win.FindName("Client_ID")
$csecret = $win.FindName("Client_Secret")
$update = $Win.FindName("Update")
$output = $Win.FindName("output")
$update.Add_Click( {
$UserAuthRoute = $URL.text
$client_id = $cid.text
$client_secret = $csecret.text
if ($UserAuthRoute -eq "" -or $client_secret -eq "" -or $client_secret -eq "") {
[System.Windows.MessageBox]::Show("Please enter in all values","Variables Required")
}else{
UpdateServices $UserAuthRoute $client_id $client_secret
$output.text += "Service ID:"+$id , "Service Name: "+$serviceName, "$newValue"
}
})
$Win.ShowDialog() ```
The solution was to append the value and separate with a newline
$output.text += "Service ID: " + $id + "`r`n" + "Service Name: " + $serviceName + "`r`n" + "Service Value: " + $newValue + "`r`n"

Powershell remote commandlet from c# for cim-session

using (PowerShell pInst=PowerShell.Create()) // implements Idisposable
{
string username = Console.ReadLine();
System.Security.SecureString pwd = getPassword();
PSCredential credential = new PSCredential(username, pwd);
pInst.Runspace.SessionStateProxy.SetVariable("cred", credential);
//pInst.AddScript("$cred;");
//pInst.AddScript("$session= New-CimSession -ComputerName anksahawin8a $cred");
//pInst.AddScript("$session;");
//pInst.AddScript("param($param1) $d = get-date;"+"$d; $s; $param1; get-service");
//.AddParameter("param1","Ankit");
//pInst.Invoke(); // Synchronous Invocation
pInst.AddScript("$session= New-CimSession -ComputerName anksahawin8a -Credential $cred;");
//psOutput = pInst.Invoke();
pInst.AddScript("$session;");
Collection<PSObject> psOutput = pInst.Invoke();
//psOutput = pInst.Invoke();
if(pInst.Streams.Error.Count>0) // Errors
{
}
foreach(PSObject pso in psOutput)
{
Console.WriteLine(pso);
if (pso != null)
{
//String result=pso.Members["Value"].Value.ToString();
Console.WriteLine(pso.BaseObject.GetType().FullName);
Console.WriteLine(pso.BaseObject.ToString() + "\n");
}
}
Console.WriteLine("Hello");
}
This code is not working. Whereas
pInst.AddScript("$session= New-CimSession");
for local computer works...

Error message when running a c# powershell code

When I run the code below I get the following error at Response.Write( result.Properties["name"].Value);. "use the 'new' keyword to create and object instance."
I can't figure out how to fix this problem.
String sEmailAddress;
String sPassword;
sEmailAddress = Request.QueryString["value1"];
sPassword = Request.QueryString["value2"];
lbl1.Text = sEmailAddress + " " + sPassword;
SecureString sSecurePW = new SecureString();
foreach (char c in sPassword.ToCharArray())
sSecurePW.AppendChar(c);
PSCredential Credential = new PSCredential(sEmailAddress, sSecurePW);
PowerShell powershell = PowerShell.Create();
powershell.Runspace.SessionStateProxy.SetVariable("cred", Credential);
powershell.AddScript("$s = New-PSSession -ComputerName ExchDC01 -Credential $cred -Authentication Kerberos");
powershell.AddScript("invoke-command -session $s -scriptblock {Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase 'OU=TENANTS,DC=lab,DC=local' -SearchScope OneLevel | ft Name}");
// Collection<PSObject> results = powershell.Invoke();
foreach (PSObject result in powershell.Invoke())
{
Response.Write(result.Properties["name"].Value); //<-- Error:use the 'new' keyword to create and object instance.
}
}
Thanks in advance

Powershell nothing returned from C#, same code runs in ps prompt with \r\n's removed

string cmd = " $srv = new-object Microsoft.SqlServer.Management.Smo.Server('" + svr + "')" + Environment.NewLine;
cmd += " $srv.Logins | where-object {$_.Name -eq 'DOMAIN\server55' } | select-object 'State'" + Environment.NewLine;
That code is added between the PSSnapin & PSSession code then invoked:
util>string prep = "$hasSnapin = get-pssnapin | Select { $_.Name.toLower().Trim() = 'sqlservercmdletsnapin100' }" + Environment.NewLine;
util>prep += "if ($hasSnapin -eq $null) { Add-Pssnapin SqlServerCmdletSnapin100 }" + Environment.NewLine;
util>cmd = prep;
util>cmd = "$pssessSql = New-PSSession -ComputerName " + svr + Environment.NewLine;
util>cmd += " Invoke-Command -session $pssessSql -ScriptBlock {" + Environment.NewLine;
util>cmd += " " + " sqlps -nologo -noprofile -command {" + Environment.NewLine;
util>cmd += " " + command + " }" + Environment.NewLine;
util>cmd += " }" + Environment.NewLine;
util>cmd += " Remove-PSSession -Session $pssessSql" + Environment.NewLine;
util>cmd += " exit";
util>try {
util>IList<System.Management.Automation.PSObject> results = pipeline.Invoke();
util>runspace.Close();
util>return results;
util>}
If I capture the script going to the Invoke it works by replacing "\r\n" with a newline, why wouldn't it work in C#, I have a other scripts working from the C# so may be missing something obvious, here's the captured code that runs from a ps prompt:
$hasSnapin = get-pssnapin | Select { $_.Name.toLower().Trim() = 'sqlservercmdletsnapin100' }
if ($hasSnapin -eq $null) { Add-Pssnapin SqlServerCmdletSnapin100 }
$pssessSql = New-PSSession -ComputerName Server54
Invoke-Command -session $pssessSql -ScriptBlock {
sqlps -nologo -noprofile -command {
$srv = new-object Microsoft.SqlServer.Management.Smo.Server('Server54')
$srv.Logins | where-object {$_.Name -like 'DOMAIN\Server55$' } | select-object 'State' }
}
Remove-PSSession -Session $pssessSql
exit
Thanks for any clues, I've had trouble with nested quotes but able to get most of those so this is I think from the \r\n's in the code but not sure how to find that out, I can't get the results to return from the app but the whole script does fine via a ps prompt.
Could the problem be the loading of the snapin on the remote end?
You have:
cmd = prep;
cmd = "$pssessSql ...";
which means that the prep code is completely ignored/overwritten by the second assignment.
One alternative is is to unconditionally add the snapin, specifying that you want errors to be ignored.
Add-Pssnapin -ErrorAction SilentlyContinue SqlServerCmdletSnapin100
Found it, the code is fine but I was using formatting, when I commented that out I was able to get my results. Before that it was returning formatting objects but I couldn't get values from them ... glad I tried without:
query += "\r\n" + "$data = $cmdCheckLogin.ExecuteReader()";
query += "\r\n" + "$dt = new-object System.Data.DataTable";
query += "\r\n" + "$dt.Load($data)";
query += "\r\n" + "$dt"; // | format-table -hidetableheaders";
query += "\r\n" + "$conn.Close()";

Categories

Resources