Skip to content

Microsoft.PowerShell.SDK - AddScript does not work w/ script path or nested Powershell files #16893

Closed

Description

Prerequisites

Steps to reproduce

I am attempting to invoke a Powershell file via c# using the Microsoft.PowerShell.SDK (7.2.1, net6)

I can only get back the return value if AddScript is passed the raw script text. However, that method starts failing when nested Powershell files get used.

The AddScript documentation appears incorrect -- it only referes to AddCommand in the examples.

I was looking at the Powershell.AddCommand(CommandInfo info overload, but all the constructors of those implementations have been marked internal, so that public overload does not allow anything to be passed into it? :/

I could only find a similar example here

C# code

private object TestPowershell(string path)
    {
        var ps = PowerShell.Create();

        var text = File.ReadAllText(path);

        ps = ps
            // .AddScript(text) <- this works when using raw settings.  Nested powershell files does not
            // .AddCommand(path) <- does not work at all.
            .AddScript(path) // <- does not work at all.
            .AddParameter("Env", "local")
        ;


        var psResult = ps.Invoke();

        return psResult;
    }

simple powershell file:

Param (
    [string]$Env = "local"
)

$settings = @{
    Test = "hi!"
}

$settings

nested powershell file (invokes the one above)

Param (
    [string]$Env = "local"
)

return (& "$PSScriptRoot\..\local\Settings.ps1")

Expected behavior

Can pass in script path via AddScript + nested powershell files work the same as invoked from terminal

Actual behavior

When using the script path (or a nested script is involved), the result set is always empty.

Raw script text w/ just a simple file works fine (so I know I'm at least close!)

Error details

No response

Environment data

<TargetFramework>net6.0</TargetFramework>
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.1" />

Visuals

No response

Activity

  1. added
    Needs-Triage
    on Feb 17, 2022
  2. iSazonov commented on Feb 17, 2022

    @iSazonov
    Collaborator

    The AddScript documentation appears incorrect -- it only referes to AddCommand in the examples.

    This must be fixed in the repository (ex., #15568)

  3. added
    Documentation Needed in this repo
    Issue-Question
    WG-DevEx-SDK
    on Feb 17, 2022
  4. iSazonov commented on Feb 17, 2022

    @iSazonov
    Collaborator
  5. iSazonov commented on Feb 17, 2022

    @iSazonov
    Collaborator

    Examples for files
    https://stackoverflow.com/questions/68941818/how-to-execute-a-powershell-script-using-c-sharp-and-setting-execution-policy
    https://stackoverflow.com/questions/527513/execute-powershell-script-from-c-sharp-with-commandline-arguments

    Stack Overflow
    I tried to combine two answers from stackoverflow (first & second) InitialSessionState iss = InitialSessionState.CreateDefault(); // Override ExecutionPolicy

    PropertyInfo execPolProp = iss.Get...

    Stack Overflow
    I need to execute a PowerShell script from within C#. The script needs commandline arguments.

    This is what I have done so far:

    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration....

  6. cmeyertons commented on Feb 17, 2022

    @cmeyertons
    Author

    Ilya (@iSazonov) you are a life saver! Was banging my head against the wall on that one for a while.

    Would it be worth documenting this code path? It seems like a pretty common pattern to invoke an existing .ps1 file from .NET core. I don't see any samples in the MSDN docs for this use case

    For those that come across this, here is my final working example for running an external script using the Powershell SDK:

    private object TestPowershell(string path)
        {
            // not required, but nice to do if you don't want the execution policy to block
            var iss = InitialSessionState.CreateDefault();
            iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
    
            using var runspace = RunspaceFactory.CreateRunspace(iss);
            runspace.Open();
            using var pipeline = runspace.CreatePipeline();
    
            var cmd = new Command(path);
            cmd.Parameters.Add("Env", "local");
    
            pipeline.Commands.Add(cmd);
    
            return pipeline.Invoke();
        }
  7. iSazonov commented on Feb 17, 2022

    @iSazonov
    Collaborator

    Would it be worth documenting this code path? It seems like a pretty common pattern to invoke an existing .ps1 file from .NET core. I don't see any samples in the MSDN docs for this use case

    You can open new issue https://github.com/MicrosoftDocs/PowerShell-Docs

    GitHub
    The official PowerShell documentation sources. Contribute to MicrosoftDocs/PowerShell-Docs development by creating an account on GitHub.
  8. added
    Up-for-Grabs
    Issue-Code Cleanup
    and removed
    Issue-Question
    on Feb 17, 2022
  9. cmeyertons commented on Feb 17, 2022

    @cmeyertons
    Author

    Done on my side! Feel free to close if desired!

  10. iSazonov commented on Feb 18, 2022

    @iSazonov
    Collaborator

    We keep the issue opened to fix docs in code #16893 (comment)

  11. sebsub321 commented on Dec 17, 2022

    @sebsub321
    **[Adding and invoking commands - PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/developer/hosting/adding-and-invoking-commands)** Adding and invoking commands
  12. ghost removed
    Needs-Triage
    on Apr 18, 2023
  13. daxian-dbw commented on Apr 18, 2023

    @daxian-dbw
    Member

    The doc issue is tracked by MicrosoftDocs/PowerShell-Docs#8594

  14. added
    Resolution-Answered
    and removed
    Up-for-Grabs
    Issue-Code Cleanup
    Documentation Needed in this repo
    on Apr 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution-AnsweredWG-DevEx-SDK

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions