1

I am trying to execute a PowerShell script from within a Windows Forms app written in C# on VS.

The issue I have is my PowerShell script has a lot of quote marks in it and I have no idea how to insert that into my code.

Here is my PowerShell script:

param([string]$inParam)
$Username = 'SERVER\domain_user'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
Invoke-Command -ComputerName SERVER_TEST -Authentication Default -ScriptBlock {&"D:\Programs\myapplication.cmd" $inParam} -Credential $Cred

How would I go about inserting this into the following C# code?

using (PowerShell powershellInstance = PowerShell.Create())
{
    powershellInstance.AddScript();
}

Hope this is enough details and thanks in advance for the help!

1 Answer 1

1

Use a multiline string literal and escape the nested double quotes by doubling them:

string script = @"param([string]$inParam)
$Username = 'SERVER\domain_user'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
Invoke-Command -ComputerName SERVER_TEST -Authentication Default -ScriptBlock {&""D:\Programs\myapplication.cmd"" $inParam} -Credential $Cred";
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I did try this but missed the nested double quotes which was causing my issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.