When you are running a PowerShell script, you might get the error:
System.Management.Automation.PSSecurityException : File Test.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
Solution
In development set the execution policy to Unrestricted.
Set-ExecutionPolicy Unrestricted
PowerShell script (runs a function from an custom assembly)
Param
(
[String]$Connection = "", #The database connectionstring
[String]$Folder = "" #The AppPool UserName
)
[System.Reflection.Assembly]::LoadWithPartialName("Ada.Cdf")
$dd = new-object Ada.Cdf.Deployment.DatabaseDeployment
$dd.ExecuteReCreatableScriptsInFolder($Connection, $Folder)
Unittest
[Test] [Explicit("Not a unittest")] public void RunExecuteReCreatableScriptsInFolder() { List<string> parameters = new List<string>(){@"Data Source=.;Initial Catalog=TestDB;Integrated Security=SSPI;", @"C:\Temp"}; // Run a PowerShell script with two parameter and set execution policy to Unrestricted RunPowershellScript(@"C:\Temp\Test.ps1", parameters); }
Function private static void RunPowershellScript(string scriptFile, List<string> parameters) { // Validate parameters if (string.IsNullOrEmpty(scriptFile)) { throw new ArgumentNullException("scriptFile"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration)) { runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); Pipeline pipeline = runspace.CreatePipeline(); Command scriptCommand = new Command(scriptFile); Collection<CommandParameter> commandParameters = new Collection<CommandParameter>(); foreach (string scriptParameter in parameters) { CommandParameter commandParm = new CommandParameter(null, scriptParameter); commandParameters.Add(commandParm); scriptCommand.Parameters.Add(commandParm); } pipeline.Commands.Add(scriptCommand); Collection<PSObject> psObjects; psObjects = pipeline.Invoke(); } }