Home > Enterprise >  C# pass parameter to power shell script file throws error
C# pass parameter to power shell script file throws error

Time:02-01

C# code has to pass parameter value to powershell script file. The code is working fine if I m not paasing any parameter. When I use .AddParameter or AddArgument it throws error.

while using AddArgument it throws error as 'A positional parameter cannot be found that accepts argument 'Test 111'.'

while using AddParameter I am getting erro as : 'A parameter cannot be found that matches parameter name 'FilePrefix'.'

Please find my C# code below

using (PowerShell ps = PowerShell.Create())
            {
                var scriptfile = @"\\cbc0056\work\Powershell\Scenarios\Test.ps1";

                 ps.AddCommand("Set-ExecutionPolicy")
                 .AddParameter("ExecutionPolicy", "RemoteSigned")
                 .AddParameter("Scope", "Process")
                 .AddParameter("Force");
                 ps.AddScript(scriptfile).AddCommand("Out-String");

                //ps.AddArgument("Test 222");
                ps.AddParameter("FilePrefix", "Test 222");

                Collection<PSObject> results = ps.Invoke();
                foreach (PSObject item in results)
                {
                    _logger.LogInformation("Power Shell returned Values as given below "   "\r\n" item.BaseObject.ToString());
 // write some business logic
                }

PowerShelll script Test.ps1 file as given below

Param(
[Parameter(Position=1)]
   [string]$FilePrefix
)
$test = $FilePrefix 
Write-Host "hello  this is a test " | Out-String

Write-Host $test| Out-String

$test 

Get-Process | Out-String

What is wrong in passing parameter ? Any help would be highly appreciated.

CodePudding user response:

  • Use .AddCommand() to execute a script file (.ps1); only use .AddScript() to execute a script block, i.e. a piece of PowerShell code.

  • As Mathias notes, your .AddParameter() call must come before adding another pipeline segement with .AddCommand("Out-String").

ps.AddCommand(scriptfile).AddParameter("FilePrefix", "Test 222").AddCommand("Out-String");

Also note that there's an easier way to set the execution policy, via an object specifying the initial session state: see this answer.

  • Related