Skip to content

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

@cmeyertons

Description

@cmeyertons

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution-AnsweredThe question is answered.WG-DevEx-SDKhosting PowerShell as a runtime, PowerShell's APIs, PowerShell Standard, or development of modules

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions