Skip to content

Instantly share code, notes, and snippets.

@PaulStovell
Created February 26, 2013 12:00
Show Gist options
  • Save PaulStovell/5037973 to your computer and use it in GitHub Desktop.
Save PaulStovell/5037973 to your computer and use it in GitHub Desktop.
Invoking PowerShell, with variables
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Management.Automation;
using System.Text;
using PowerShellHosting.Util;
namespace PowerShellHosting.File
{
public class FileBasedPowerShellRunner : IPowerShell
{
public PowerShellExecutionResult Execute(PowerShellArguments arguments)
{
const string powerShellExe = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
var bootstrapFile = Path.Combine(arguments.WorkingDirectory, "Bootstrap." + Guid.NewGuid().ToString() + ".ps1");
using (var writer = new StreamWriter(bootstrapFile))
{
writer.WriteLine("## Variables:");
foreach (var variable in arguments.Variables)
{
writer.WriteLine("$" + variable.Key + " = [System.Text.Encoding]::Unicode.GetString( [Convert]::FromBase64String( \"" + Convert.ToBase64String(Encoding.Unicode.GetBytes(variable.Value)) + "\" ) )");
}
writer.WriteLine();
writer.WriteLine("## Invoke:");
writer.WriteLine(". .\\Deploy.ps1");
writer.Flush();
}
try
{
var commandArguments = new StringBuilder();
commandArguments.Append("-NonInteractive ");
commandArguments.Append("-NoLogo ");
commandArguments.Append("-ExecutionPolicy Unrestricted ");
commandArguments.AppendFormat("-File \"{0}\"", bootstrapFile);
var exit = SilentProcessRunner.ExecuteCommand(powerShellExe, commandArguments.ToString(), Environment.CurrentDirectory,
output => arguments.OutputStream.OnWritten(output),
error => arguments.OutputStream.OnWritten("ERROR: " + error));
return new PowerShellExecutionResult(exit, null);
}
finally
{
System.IO.File.Delete(bootstrapFile);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment