1

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.

sha
  • 73
  • 1
  • 2
  • 7
  • 1
    You need to call `AddParameter` _before_ tacking `Out-String` onto the pipeline: `ps.AddScript(scriptfile).AddParameter("FilePrefix", "Test 222").AddCommand("Out-String");` – Mathias R. Jessen Jan 30 '23 at 13:32
  • but still the parameter value "Test 222" not getting in powershell script. IS there any issue with my powershell script – sha Jan 30 '23 at 14:36

1 Answers1

0
  • 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.

mklement0
  • 382,024
  • 64
  • 607
  • 775