简体   繁体   中英

Using double quotes in PowerShell script executed from C# application

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!

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM