/// <summary> /// Method to run the sample script and handle debugger events. /// </summary> public void RunFile(string filePath) { using (Runspace runspace = RunspaceFactory.CreateRunspace()) { runspace.Open(); runspace.Debugger.SetDebugMode(DebugModes.LocalScript); using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = runspace; runspace.Debugger.BreakpointUpdated += HandlerBreakpointUpdatedEvent; runspace.Debugger.DebuggerStop += HandleDebuggerStopEvent; UserIOImpl.PrintMessage("Starting script file: " + filePath); powerShell.AddStatement().AddCommand("Set-PSBreakpoint").AddParameter("Script", filePath).AddParameter("Line", 1); foreach (var kv in VariableReplaceMap) { UserIOImpl.PrintMessage("Setting variable breakpoint on: " + kv.Key); powerShell.AddStatement().AddCommand("Set-PSBreakpoint").AddParameter("Variable", kv.Key); } powerShell.AddStatement().AddCommand("Set-ExecutionPolicy").AddParameter("ExecutionPolicy", "Bypass").AddParameter("Scope", "CurrentUser"); powerShell.AddScript(filePath); var scriptOutput = new PSDataCollection <PSObject>(); scriptOutput.DataAdded += (sender, args) => { foreach (var item in scriptOutput.ReadAll()) { UserIOImpl.PrintMessage("| " + item); } }; powerShell.Invoke <PSObject>(null, scriptOutput); if (powerShell.Streams.Error != null) { foreach (ErrorRecord errorRecord in powerShell.Streams.Error.ReadAll()) { if (errorRecord != null && errorRecord.ErrorDetails != null) { UserIOImpl.PrintMessage(errorRecord.ErrorDetails.Message); } } } } } }
public override bool Execute() { bool isSuccess = false; try { _ps = PowerShell.Create(); _ps .AddCommand("Set-ExecutionPolicy") .AddArgument("Unrestricted") .AddParameter("Scope", "CurrentUser"); _ps .AddStatement() .AddCommand(BuildEntryPs1) .AddParameter("srcDirectory", TrimEndingDirectorySeparator(SolutionRoot)) .AddParameter("sdkPath", TrimEndingDirectorySeparator(SdkInstallPath)) .AddParameter("gamePath", TrimEndingDirectorySeparator(GameInstallPath)) .AddParameter("config", BuildEntryConfig); BindStreamEntryCallback(_ps.Streams.Debug, record => LogOutput(record.ToString())); BindStreamEntryCallback(_ps.Streams.Information, record => LogOutput(record.ToString())); BindStreamEntryCallback(_ps.Streams.Verbose, record => LogOutput(record.ToString())); BindStreamEntryCallback(_ps.Streams.Warning, record => LogOutput(record.ToString())); // TODO: More flashy output? BindStreamEntryCallback(_ps.Streams.Error, record => { // TODO: Less info than when from console // TODO: More flashy output? LogOutput(record.ToString()); Log.LogError(record.ToString()); isSuccess = false; }); _ps.InvocationStateChanged += (sender, args) => { if (args.InvocationStateInfo.State == PSInvocationState.Running) { _startingMre.Set(); } }; isSuccess = true; _ps.Invoke(); } catch (System.Exception e) { Log.LogError(e.Message); isSuccess = false; } return(isSuccess); }
static void Main(string[] args) { SecureString secString = new NetworkCredential("", "passWord").SecurePassword; SecureString passPhrase = new SecureString(); SecureString passWord = new SecureString(); Array.ForEach("P@ssw0rD!".ToCharArray(), passPhrase.AppendChar); PSCredential c = new PSCredential(@"contoso\farmAccount", secString); var hTable = new Hashtable { { "SPIisWebServiceApplicationPool", c }, { "SPUnattendedDataRefresh", c }, { "SecureStoreEncryptionKey", c }, { "SPFarmService", c } }; //This is used by SPFarmInitializationSettings to retrieve credentials. Thread.SetData(Thread.GetNamedDataSlot("SPConfig_Secrets"), hTable); using (PowerShell instance = PowerShell.Create()) { instance.AddCommand("Add-PSSnapin").AddParameter("Name", "Microsoft.SharePoint.PowerShell"); instance.AddStatement(); instance.AddCommand("New-SPConfigurationDatabase").AddParameter("DatabaseName", "Config").AddParameter("AdministrationContentDatabaseName", "Admin"). AddParameter("DatabaseServer", "SqlServerName").AddParameter("LocalServerRole", "Custom").AddParameter("Passphrase", passPhrase). AddParameter("FarmCredentials", c); instance.AddStatement(); Collection <PSObject> PSOutput = instance.Invoke(); if (instance.Streams.Error.Count > 0) { Console.WriteLine(instance.Streams.Error.ElementAt(0).Exception.ToString()); while (Console.ReadKey().Key != ConsoleKey.Enter) { } ; } } }
private void SetVariable(PowerShell powershell, string name, object value) { if (Log.IsDebugEnabled) { Log.Debug($"{name} = {value}"); } powershell.AddStatement() .AddCommand("Set-Variable", true) .AddParameter("Name", name) .AddParameter("Value", value); }
private void SetVariables(PowerShell powerShell, Dictionary <string, object> variables) { foreach (var variable in variables) { if (Log.IsDebugEnabled) { Log.Debug($"{variable.Key} = {variable.Value}"); } powerShell.AddStatement() .AddCommand("Set-Variable", true) .AddParameter("Name", variable.Key) .AddParameter("Value", variable.Value); } }
private string SetupSharedData(PowerShell ps, string script, ExecutionContext context, out bool hasGetSharedData) { bool hasPublishSharedData = script.Contains("Publish-UDSharedData"); hasGetSharedData = script.Contains("Get-UDSharedData"); if (hasPublishSharedData || hasGetSharedData) { ps.AddStatement() .AddCommand("Set-Variable", true) .AddParameter("Name", "MemoryCacheUdShared") .AddParameter("Value", MemoryCache); } if (hasPublishSharedData) { script = ReplaceIfNotReplaced(script, "Publish-UDSharedData ", "Publish-UDSharedData -MemoryCache $MemoryCacheUdShared "); } if (hasGetSharedData) { ps.AddStatement() .AddCommand("Set-Variable", true) .AddParameter("Name", "ExecutionContextUdShared") .AddParameter("Value", context); ps.AddStatement() .AddCommand("Set-Variable", true) .AddParameter("Name", "ExecutionServiceUdShared") .AddParameter("Value", this); script = ReplaceIfNotReplaced(script, "Get-UDSharedData ", "Get-UDSharedData -ExecutionContext $ExecutionContextUdShared -ExecutionService $ExecutionServiceUdShared -MemoryCache $MemoryCacheUdShared "); } return(script); }
/// <summary> /// Import azure subscription /// </summary> /// <param name="filePath">Azure subscription file path</param> public static void ImportAzureSubscriptionAndSetStorageAccount(string filePath, string subscriptionName, string storageAccountName) { PowerShell ps = PowerShell.Create(_InitState); //TODO add tests for positional parameter ps.AddCommand("Import-AzurePublishSettingsFile"); ps.BindParameter("PublishSettingsFile", filePath); ps.AddStatement(); ps.AddCommand("Set-AzureSubscription"); ps.BindParameter("SubscriptionName", subscriptionName); ps.BindParameter("CurrentStorageAccountName", storageAccountName); Test.Info("set current storage account in subscription, Cmdline: {0}", GetCommandLine(ps)); ps.Invoke(); if (ps.Streams.Error.Count > 0) { Test.Error("Can't set current storage account to {0} in subscription {1}. Exception: {2}", storageAccountName, subscriptionName, ps.Streams.Error[0].Exception.Message); } }
/// <summary> /// Synchronously invokes the PowerShell script by using the supplied input parameters. /// </summary> /// <param name="apiController">The ApiController. This is an extension method to ApiController, when you use instance method syntax to call this method, omit this parameter.</param> /// <param name="scriptPath">The fully qualified location of the PowerShell script to be run.</param> /// <param name="parameters">A set of parameters to the PowerShell script. The parameter names and values are taken from the keys and values of a collection.</param> /// <returns>A complete HttpResponseMessage contains result data returned by the PowerShell script.</returns> public static HttpResponseMessage InvokePowerShell(this ApiController apiController, string scriptPath, IEnumerable <KeyValuePair <string, object> > parameters) { PSContentNegotiator contentNegotiator = new PSContentNegotiator(apiController.Request); PSConverterRegistry converter = contentNegotiator.NegotiatedPsConverter; Encoding encoding = contentNegotiator.NegotiatedEncoding; if (converter == null) { throw new HttpResponseException(HttpStatusCode.NotAcceptable); } using (PowerShell ps = PowerShell.Create()) { ps.RunspacePool = _runspacePool; ps.AddCommand("Set-Location").AddParameter("LiteralPath", Path.GetDirectoryName(scriptPath)); ps.AddStatement().AddCommand(scriptPath, true).Commands.AddParameters(parameters); if (!string.IsNullOrWhiteSpace(converter.ConversionCmdlet)) { ps.AddCommand(converter.ConversionCmdlet, true).Commands.AddParameters(converter.CmdletParameters); } try { string stringResult = GetPsResult(ps.Invoke(), encoding); ps.CheckErrors(); StringContent responseContent = new StringContent(stringResult, encoding, contentNegotiator.NegotiatedMediaType.MediaType); responseContent.Headers.SetContentHeader(ps.Streams); return(new HttpResponseMessage(string.IsNullOrEmpty(stringResult) ? HttpStatusCode.NoContent : HttpStatusCode.OK) { Content = responseContent }); } catch (CommandNotFoundException) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } } }
protected override void EndProcessing() { if (ParameterSetName == "Simple") { connbuilder = new ConnectionString(); connbuilder.Connection = Mode; connbuilder.InitialSize = InitialSize; connbuilder.Collation = collation; if (Credential != null) { connbuilder.Password = Credential.GetNetworkCredential().Password; } if (ReadOnly) { connbuilder.ReadOnly = true; } if (Upgrade) { connbuilder.Upgrade = true; } if (Database != null && !string.IsNullOrEmpty(Database) && !string.IsNullOrWhiteSpace(Database)) { resolvedPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(Database); if (File.Exists(resolvedPath)) { connbuilder.Filename = resolvedPath; _connectioninfo = connbuilder; try { _connection = new LiteDatabase(connbuilder); _connectioninfo.Password = null; } catch (Exception) { throw; } } else { throw new Exception(string.Format("Path not found:\t['{0}']", resolvedPath)); } } else { _connection = new LiteDatabase(new MemoryStream()); WriteVerbose($"Open-LiteDBConnection: Opened connection to In-Memory database"); } } else { //custom connection string passed by the user try { _connection = new LiteDatabase(ConnectionString); _connectioninfo = null; } catch (Exception) { throw; } } BsonMapper.Global.SerializeNullValues = true; if (DontSerializeNullValues) { BsonMapper.Global.SerializeNullValues = false; } if (DontTrimWhitespace) { BsonMapper.Global.TrimWhitespace = false; } if (DontConvertEmptyStringToNull) { BsonMapper.Global.EmptyStringToNull = false; } if (IncludeFields) { BsonMapper.Global.IncludeFields = true; } using (PowerShell PowerShellInstance = PowerShell.Create()) { //add the database path as a custom property to the connection object PowerShellInstance.Commands.AddCommand("Add-Member").AddParameter("inputobject", _connection).AddParameter("MemberType", "NoteProperty"). AddParameter("Name", "Database").AddParameter("Value", resolvedPath); PowerShellInstance.AddStatement(); PowerShellInstance.Commands.AddCommand("Add-Member").AddParameter("inputobject", _connection).AddParameter("MemberType", "NoteProperty"). AddParameter("Name", "ConnectionInfo").AddParameter("Value", _connectioninfo).AddParameter("PassThru", true); var PSOutput = PowerShellInstance.Invoke(); } //check if there is an existing connection variable if yes then dont overwrite it! try { var conns = (LiteDatabase)SessionState.PSVariable.Get("LiteDBPSConnection").Value; } catch (Exception) { SessionState.PSVariable.Set("LiteDBPSConnection", _connection); } //write the connection to the pipeline WriteObject(_connection); }
public static Dictionary <string, PSResult> ResetADPassword(string userName, SecureString newPassword, bool forceChange, bool unlock) { Logger.Log("Initiating AD password reset...", MethodBase.GetCurrentMethod().Name); Dictionary <string, PSResult> ResultValueMap = new Dictionary <string, PSResult>(); PSResult resetSuccess = new PSResult("ResetSuccess"); PSResult unlockStatus = new PSResult("UnlockSuccess"); if (newPassword != null) { Logger.Log("New password not null. Continuing...", MethodBase.GetCurrentMethod().Name); if (unlock && IsADAccountLocked(userName)) { Logger.Log("AD Account is locked. User selected option to unlock. Attempting ot unlock.", MethodBase.GetCurrentMethod().Name); bool unlockSuccess = UnlockADAccount(userName); Logger.Log("Unlock successful " + unlockSuccess, MethodBase.GetCurrentMethod().Name); unlockStatus.SetSuccessValue(unlockSuccess); ResultValueMap.Add(unlockStatus.Name, unlockStatus); } else { if (unlock) { Logger.Log("User selected option to unlock but account was not locked.", MethodBase.GetCurrentMethod().Name); } else { Logger.Log("User did not select option to unlock.", MethodBase.GetCurrentMethod().Name); } unlockStatus.SetSuccessValue(false); unlockStatus.SetMessage(""); ResultValueMap.Add(unlockStatus.Name, unlockStatus); } using (PowerShell PowerShellInstance = PowerShell.Create()) { PowerShellInstance.AddCommand("Set-ADAccountPassword"); PowerShellInstance.AddParameter("-Reset"); PowerShellInstance.AddParameter("-NewPassword", newPassword); PowerShellInstance.AddParameter("Identity", userName); PowerShellInstance.AddStatement(); if (forceChange) { Logger.Log("User selected option to have the password force changed.", MethodBase.GetCurrentMethod().Name); PowerShellInstance.AddCommand("Set-ADUser"); PowerShellInstance.AddParameter("Identity", userName); PowerShellInstance.AddParameter("-ChangePasswordAtLogon", true); PowerShellInstance.AddStatement(); } try { Collection <PSObject> psOutput = PowerShellInstance.Invoke(); resetSuccess.SetSuccessValue(true); resetSuccess.SetMessage("Password reset successfully."); ResultValueMap.Add(resetSuccess.Name, resetSuccess); Logger.Log("Password was reset.", MethodBase.GetCurrentMethod().Name); } catch (CmdletInvocationException e) { if (e.Message.Equals("The password does not meet the length, complexity, or history requirement of the domain.")) { Logger.Log(e.Message, MethodBase.GetCurrentMethod().Name); resetSuccess.SetSuccessValue(false); resetSuccess.SetMessage(e.Message); ResultValueMap.Add(resetSuccess.Name, resetSuccess); } } catch (Exception e) { resetSuccess.SetSuccessValue(false); resetSuccess.SetMessage(e.Message); ResultValueMap.Add(resetSuccess.Name, resetSuccess); Logger.Log("Exception resetting password for user: " + userName, MethodBase.GetCurrentMethod().Name); } } return(ResultValueMap); } return(null); }