techmanc
techmanc

Reputation: 293

Adding a Batch/Powershell file to a compilation (Build) C# Powershell

I'm working on a c# project where i'm trying to run powershell scripts, output them to a CSV and read the CSV and output it to a Checked list box.

I've added a powershell file as a resource with Build Action 'Compile' and Copy to output directory 'Do Not Copy'.

The basic content of the file is :

Get-CimInstance -Query "SELECT * from Win32_Service where name LIKE 'sql%'" | select Name, State , StartMode | convertto-csv > proctest.csv

i try to access this file using this string

string ps_path = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "\\GetSvc.ps1";

The PS code i use is

RunspaceConfiguration runspaceconfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceconfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
Command mycommand = new Command(ps_path);
pipeline.Commands.Add(mycommand);
pipeline.Invoke();
runspace.Close();

This works fine during compilation but when i build an exe and try to run it, i get an error saying the GetSvc.ps1 file is not found.

How do i make the file a part of the build ?!

Upvotes: 0

Views: 681

Answers (1)

Keith Hill
Keith Hill

Reputation: 201952

Make the build action for the script be Embedded Resource. Then take a look at lines 149-155 on how to extract the script inside the C# exe. In this example, I had zipped the script to compact it. If you skip that step then you can remove line 152 and in line 153 use stream instead of gZipStream.

Upvotes: 1

Related Questions