public PowerShellHost() { this._runspace = RunspaceFactory.CreateRunspace(); }
public void SetRunspace() { _runspace = RunspaceFactory.CreateRunspace(); }
public static async Task <ReturnModel> QueryWmi(this QueryWmiModel model) { try { ReturnModel returnModel = new ReturnModel(); InitialSessionState iss = InitialSessionState.CreateDefault(); iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted; using (Runspace rs = RunspaceFactory.CreateRunspace(iss)) { rs.Open(); var script = string.Empty; if (model.isRemoteConnection) { script = await("PowerShellAPIFramework.Core.Scripts.query-wmi-remote.ps1").GetTextFromEmbeddedResource(); } else { script = await("PowerShellAPIFramework.Core.Scripts.query-wmi.ps1").GetTextFromEmbeddedResource(); } Command queryWmi = new Command(script, true); queryWmi.Parameters.Add("query", model.query); queryWmi.Parameters.Add("computername", model.computername); queryWmi.Parameters.Add("wmiNamespace", model.wmiNamespace); if (model.isRemoteConnection) { queryWmi.Parameters.Add("credential", new PSCredential(model.username, model.securePassword)); } using (PowerShell ps = PowerShell.Create()) { ps.Runspace = rs; ps.Commands.AddCommand(queryWmi); var psResults = ps.Invoke(); if (ps.HadErrors) { if (ps.Streams.Error.Count > 0) { var exceptions = new StringBuilder(); foreach (var error in ps.Streams.Error) { exceptions.AppendLine(error.Exception.GetExceptionMessageChain()); } throw new Exception(exceptions.ToString()); } } else { foreach (var result in psResults) { if (psResults.IndexOf(result) == 0) { returnModel.properties = result.Properties.Select(x => x.Name).ToList(); } var resultModel = new ResultModel { propertyValues = result.Properties.Select(x => new PropertyValueModel { property = x.Name, value = x.Value }).AsEnumerable() }; returnModel.results.Add(resultModel); } } } } return(returnModel); } catch (Exception ex) { throw new Exception(ex.GetExceptionMessageChain()); } }
private Collection <PSObject> Invoke(string script, PowershellSettings settings) { //Create Runspace Runspace runspace = null; if (String.IsNullOrEmpty(settings.ComputerName)) { //Local runspace = RunspaceFactory.CreateRunspace(new CakePSHost(_Log)); } else { //Remote WSManConnectionInfo connection = new WSManConnectionInfo(); connection.ComputerName = settings.ComputerName; if (settings.Port > 0) { connection.Port = settings.Port; } else { connection.Port = 5985; } if (!String.IsNullOrEmpty(settings.Username)) { connection.Credential = new PSCredential(settings.Username, settings.Password.MakeSecure()); } if (settings.Timeout.HasValue) { connection.OperationTimeout = settings.Timeout.Value; connection.OpenTimeout = settings.Timeout.Value; } runspace = RunspaceFactory.CreateRunspace(new CakePSHost(_Log), connection); } runspace.Open(); //Create Pipline Collection <PSObject> results = null; using (Pipeline pipeline = runspace.CreatePipeline()) { //Invoke Command if (settings.WorkingDirectory != null) { pipeline.Commands.AddScript("Set-Location -Path " + settings.WorkingDirectory.FullPath); } if ((settings.Modules != null) && (settings.Modules.Count > 0)) { pipeline.Commands.AddScript("Import-Module " + settings.Modules); } pipeline.Commands.AddScript(script); if (settings.FormatOutput) { pipeline.Commands.Add("Out-String"); } results = pipeline.Invoke(); //Log Errors if (pipeline.Error.Count > 0) { while (!pipeline.Error.EndOfPipeline) { PSObject value = (PSObject)pipeline.Error.Read(); if (value != null) { ErrorRecord record = (ErrorRecord)value.BaseObject; if (record != null) { _Log.Error(Verbosity.Normal, record.Exception.Message); } } } } } runspace.Close(); runspace.Dispose(); //Log Results if (settings.LogOutput) { foreach (PSObject res in results) { _Log.Debug(Verbosity.Normal, res.ToString()); } } return(results); }
/// <summary> /// Initializes a new instance of the PowerShellApi class with default settings /// </summary> public PowerShellApi() { runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); }
public Runspace NewRunspace(WSManConnectionInfo connectionInfo) { Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo); return(runspace); }
public PSScriptExecutor(string pathToScripts, string[] modulesToLoad, string psExecutionPolicy, string psOutputDelimiter) { this.pathToScripts = pathToScripts; this.modulesToLoad = modulesToLoad; this.psExecutionPolicy = psExecutionPolicy; this.psOutputDelimiter = psOutputDelimiter; // Initialise PowerShell Runspace and preload necessary modules. // See here: http://stackoverflow.com/a/17071164 // See here: http://nivot.org/blog/post/2010/05/03/PowerShell20DeveloperEssentials1InitializingARunspaceWithAModule InitialSessionState initialSession = InitialSessionState.CreateDefault2(); if (modulesToLoad != null && modulesToLoad.Length > 0) { initialSession.ImportPSModule(modulesToLoad); } if (psExecutionPolicy != "None") { PSScriptInvoker.logInfo("Setting custom PowerShell Execution Policy: " + psExecutionPolicy); switch (psExecutionPolicy) { case "AllSigned": initialSession.ExecutionPolicy = ExecutionPolicy.AllSigned; break; case "Bypass": initialSession.ExecutionPolicy = ExecutionPolicy.Bypass; break; case "RemoteSigned": initialSession.ExecutionPolicy = ExecutionPolicy.RemoteSigned; break; case "Restricted": initialSession.ExecutionPolicy = ExecutionPolicy.Restricted; break; case "Undefined": initialSession.ExecutionPolicy = ExecutionPolicy.Undefined; break; case "Unrestricted": initialSession.ExecutionPolicy = ExecutionPolicy.Unrestricted; break; default: PSScriptInvoker.logWarning("Given custom PowerShell Execution Policy is unknown: " + psExecutionPolicy + ". Only one of the following custom policies is allowed: AllSigned, Bypass, RemoteSigned, Restricted, Undefined, Unrestricted. Set to policy 'Default'."); initialSession.ExecutionPolicy = ExecutionPolicy.Default; break; } } // This loads the InitialStateSession for all instances // Note you can set the minimum and maximum number of runspaces as well // Note that without setting the minimum and maximum number of runspaces, it will use 1 as default for both: // https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.runspaces.runspacefactory.createrunspacepool?view=powershellsdk-1.1.0 // See here: https://stackoverflow.com/a/24358855 runspacePool = RunspaceFactory.CreateRunspacePool(initialSession); runspacePool.SetMinRunspaces(MIN_RUNSPACES); runspacePool.SetMaxRunspaces(int.MaxValue); runspacePool.ThreadOptions = PSThreadOptions.UseNewThread; runspacePool.Open(); }
static void Main() { //Box(new List<string> {"abc", " def", "this is something coo"}); var iss = InitialSessionState.CreateDefault2(); var rs = RunspaceFactory.CreateRunspace(iss); rs.Open(); Runspace.DefaultRunspace = rs; PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Emacs, HistoryNoDuplicates = true, }); PSConsoleReadLine.SetKeyHandler(new[] { "Ctrl+LeftArrow" }, PSConsoleReadLine.ShellBackwardWord, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "Ctrl+RightArrow" }, PSConsoleReadLine.ShellNextWord, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "F4" }, PSConsoleReadLine.HistorySearchBackward, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "F5" }, PSConsoleReadLine.HistorySearchForward, "", ""); //PSConsoleReadLine.SetKeyHandler(new[] {"Ctrl+D,Ctrl+E"}, PSConsoleReadLine.EnableDemoMode, "", ""); //PSConsoleReadLine.SetKeyHandler(new[] {"Ctrl+D,Ctrl+D"}, PSConsoleReadLine.DisableDemoMode, "", ""); // PSConsoleReadLine.SetKeyHandler(new[] {"Ctrl+D,Ctrl+C"}, PSConsoleReadLine.CaptureScreen, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "Ctrl+D,Ctrl+P" }, PSConsoleReadLine.InvokePrompt, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "Ctrl+D,Ctrl+X" }, CauseCrash, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "F6" }, PSConsoleReadLine.PreviousLine, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "F7" }, PSConsoleReadLine.NextLine, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "F2" }, PSConsoleReadLine.ValidateAndAcceptLine, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "Enter" }, PSConsoleReadLine.AcceptLine, "", ""); EngineIntrinsics executionContext; using (var ps = PowerShell.Create(RunspaceMode.CurrentRunspace)) { executionContext = ps.AddScript("$ExecutionContext").Invoke <EngineIntrinsics>().FirstOrDefault(); // This is a workaround to ensure the command analysis cache has been created before // we enter into ReadLine. It's a little slow and infrequently needed, so just // uncomment host stops responding, run it once, then comment it out again. //ps.Commands.Clear(); //ps.AddCommand("Get-Command").Invoke(); } while (true) { Console.Write("TestHostPS> "); var line = PSConsoleReadLine.ReadLine(null, executionContext); Console.WriteLine(line); line = line.Trim(); if (line.Equals("exit")) { Environment.Exit(0); } if (line.Equals("cmd")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Windows }); } if (line.Equals("emacs")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Emacs }); } if (line.Equals("vi")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Vi }); } if (line.Equals("nodupes")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { HistoryNoDuplicates = true }); } } }
/// <summary> /// Constructor. /// </summary> /// <param name="name"></param> /// <param name="command"></param> /// <param name="sb"></param> /// <param name="filePath"></param> /// <param name="initSb"></param> /// <param name="argumentList"></param> /// <param name="inputObject"></param> /// <param name="psCmdlet"></param> /// <param name="currentLocationPath"></param> /// <param name="streamingHost"></param> public ThreadJob( string name, string command, ScriptBlock sb, string filePath, ScriptBlock initSb, object[] argumentList, PSObject inputObject, PSCmdlet psCmdlet, string currentLocationPath, PSHost streamingHost) : base(command, name) { _sb = sb; _filePath = filePath; _initSb = initSb; _argumentList = argumentList; _input = new PSDataCollection <object>(); if (inputObject != null) { _input.Add(inputObject); } _output = new PSDataCollection <PSObject>(); _streamingHost = streamingHost; _currentLocationPath = currentLocationPath; this.PSJobTypeName = "ThreadJob"; // Get script block to run. if (!string.IsNullOrEmpty(_filePath)) { _sb = GetScriptBlockFromFile(_filePath, psCmdlet); if (_sb == null) { throw new InvalidOperationException(Properties.Resources.CannotParseScriptFile); } } else if (_sb == null) { throw new PSArgumentNullException(Properties.Resources.NoScriptToRun); } // Create Runspace/PowerShell object and state callback. // The job script/command will run in a separate thread associated with the Runspace. var iss = InitialSessionState.CreateDefault2(); // Determine session language mode for Windows platforms WarningRecord lockdownWarning = null; if (Environment.OSVersion.Platform.ToString().Equals("Win32NT", StringComparison.OrdinalIgnoreCase)) { bool enforceLockdown = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce); if (enforceLockdown && !string.IsNullOrEmpty(_filePath)) { // If script source is a file, check to see if it is trusted by the lock down policy enforceLockdown = (SystemPolicy.GetLockdownPolicy(_filePath, null) == SystemEnforcementMode.Enforce); if (!enforceLockdown && (_initSb != null)) { // Even if the script file is trusted, an initialization script cannot be trusted, so we have to enforce // lock down. Otherwise untrusted script could be run in FullLanguage mode along with the trusted file script. enforceLockdown = true; lockdownWarning = new WarningRecord( string.Format( CultureInfo.InvariantCulture, Properties.Resources.CannotRunTrustedFileInFL, _filePath)); } } iss.LanguageMode = enforceLockdown ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; } if (_streamingHost != null) { _rs = RunspaceFactory.CreateRunspace(_streamingHost, iss); } else { _rs = RunspaceFactory.CreateRunspace(iss); } _ps = PowerShell.Create(); _ps.Runspace = _rs; _ps.InvocationStateChanged += (sender, psStateChanged) => { var newStateInfo = psStateChanged.InvocationStateInfo; // Update Job state. switch (newStateInfo.State) { case PSInvocationState.Running: SetJobState(JobState.Running); break; case PSInvocationState.Stopped: SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Failed: SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Completed: if (_runningInitScript) { // Begin running main script. _runningInitScript = false; RunScript(); } else { SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true); } break; } }; // Get any using variables. var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>(); if (usingAsts != null && usingAsts.FirstOrDefault() != null) { // Get using variables as dictionary, since we now only support PowerShell version 5.1 and greater _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet); } // Hook up data streams. this.Output = _output; this.Output.EnumeratorNeverBlocks = true; this.Error = _ps.Streams.Error; this.Error.EnumeratorNeverBlocks = true; this.Progress = _ps.Streams.Progress; this.Progress.EnumeratorNeverBlocks = true; this.Verbose = _ps.Streams.Verbose; this.Verbose.EnumeratorNeverBlocks = true; this.Warning = _ps.Streams.Warning; this.Warning.EnumeratorNeverBlocks = true; if (lockdownWarning != null) { this.Warning.Add(lockdownWarning); } this.Debug = _ps.Streams.Debug; this.Debug.EnumeratorNeverBlocks = true; this.Information = _ps.Streams.Information; this.Information.EnumeratorNeverBlocks = true; // Create the JobManager job definition and job specification, and add to the JobManager. ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name); Dictionary <string, object> parameterCollection = new Dictionary <string, object>(); parameterCollection.Add("NewJob", this); var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection); var newJob = psCmdlet.JobManager.NewJob(jobSpecification); System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job"); }
void OpenRunspace() { Tracer.Enter("openrunspace"); try { if (runspace == null) { Tracer.TraceInformation("creating-runspace"); runspace = RunspaceFactory.CreateRunspace(); runspace.ApartmentState = System.Threading.ApartmentState.STA; runspace.ThreadOptions = PSThreadOptions.Default; runspace.StateChanged += Runspace_StateChanged; runspace.AvailabilityChanged += Runspace_AvailabilityChanged; Tracer.TraceInformation("created-runspace"); } else { Tracer.TraceInformation("existing-runspace-state '{0}'", runspace.RunspaceStateInfo.State); } if (runspace.RunspaceStateInfo.State == RunspaceState.BeforeOpen) { Tracer.TraceInformation("opening-runspace"); runspace.Open(); } else { Tracer.TraceInformation("runspace-already-open"); } Tracer.TraceInformation("runspace-state '{0}'", runspace.RunspaceStateInfo.State); if (runspace.RunspaceStateInfo.State == RunspaceState.Opened) { Tracer.TraceInformation("runspace-powershell-version {0}.{1}", runspace.Version.Major, runspace.Version.Minor); } if (powershell == null) { Tracer.TraceInformation("creating-powershell"); powershell = PowerShell.Create(); powershell.Runspace = runspace; Tracer.TraceInformation("powershell instanceid: {0}, runspace-id: {1}", powershell.InstanceId, powershell.Runspace.InstanceId); Tracer.TraceInformation("powershell apartmentstate: {0}, version: {1}", powershell.Runspace.ApartmentState, powershell.Runspace.Version); // the streams (Error, Debug, Progress, etc) are available on the PowerShell instance. // we can review them during or after execution. // we can also be notified when a new item is written to the stream (like this): powershell.Streams.ClearStreams(); powershell.Streams.Error.DataAdded += new EventHandler <DataAddedEventArgs>(Error_DataAdded); powershell.Streams.Verbose.DataAdded += new EventHandler <DataAddedEventArgs>(Verbose_DataAdded); powershell.Streams.Warning.DataAdded += new EventHandler <DataAddedEventArgs>(Warning_DataAdded); powershell.Streams.Debug.DataAdded += new EventHandler <DataAddedEventArgs>(Debug_DataAdded); powershell.Streams.Progress.DataAdded += new EventHandler <DataAddedEventArgs>(Progress_DataAdded); Tracer.TraceInformation("created-powershell"); } } catch (Exception ex) { Tracer.TraceError("openrunspace", ex); throw; } finally { Tracer.Exit("openrunspace"); } }
//更新地址列表的操作 public bool SetUserShow(string identity) { #region //RunspaceConfiguration runConf = RunspaceConfiguration.Create(); //PSSnapInException pssException = null; //Runspace runsp = null; //Pipeline pipeline = null; //try //{ // PSSnapInInfo info = runConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out pssException); // runsp = RunspaceFactory.CreateRunspace(runConf); // System.Threading.Thread.Sleep(20000); // runsp.Open(); // pipeline = runsp.CreatePipeline(); // Command command = new Command("Update-AddressList"); //powershell指令 // command.Parameters.Add("identity", @"\" + addresslistname2); // pipeline.Commands.Add(command); // pipeline.Invoke(); // return "人员调动成功!"; //} //catch (Exception ex) //{ // Debug.WriteLine(ex.Message); // return "人员调动失败!"; //} //finally //{ // pipeline.Dispose(); // runsp.Close(); //} #endregion try { // 生成一个连接类型,传入exchange服务器IP、将要使用的Scheme以及管理员凭据 var connectionInfo = ExchangeScriptInit(); using (var rs = RunspaceFactory.CreateRunspace(connectionInfo)) { var psh = PowerShell.Create(); psh.Runspace = rs; rs.Open(); var sScript = "Set -Mailbox -HiddenFromAddressListsEnabled $false - Identity '" + identity + "'"; //Set - Mailbox - HiddenFromAddressListsEnabled $true - Identity 'test.com/xd-ad/集团公司/办公室/小伙子' psh.Commands.AddScript(sScript); var arr = identity.Split('/'); var name = arr[arr.Length - 1]; var addresslistname = identity.Substring(0, identity.Length - name.Length - 1); var sScript1 = "Update-AddressList -identity '" + addresslistname + "'"; psh.Commands.AddScript(sScript1); psh.Invoke(); rs.Close(); psh.Runspace.Close(); return(true); } } catch (Exception) { return(false); } }
/// <summary> /// AD中修改OU后,需要在exchange地址列表中同步修改对应的OU,并更新 /// </summary> /// <param name="displayName">显示名称</param> /// <param name="name">名称</param> /// <param name="recipientContainer">容器的名称,需要写全OU所在的路径,eg:tets.com/xd-ad/集团公司/邮件公司</param> /// <returns>返回是否成功的布尔值</returns> public bool AddAddressList(string displayName, string name, string recipientContainer) { #region //RunspaceConfiguration runConf = RunspaceConfiguration.Create(); //PSSnapInException pssException = null; //Runspace runsp = null; //Pipeline pipeline = null; //try //{ // PSSnapInInfo info = runConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out pssException); // runsp = RunspaceFactory.CreateRunspace(runConf); // System.Threading.Thread.Sleep(20000); // runsp.Open(); // pipeline = runsp.CreatePipeline(); // Command command = new Command("Update-AddressList"); //powershell指令 // command.Parameters.Add("identity", @"\" + addresslistname2); // pipeline.Commands.Add(command); // pipeline.Invoke(); // return "人员调动成功!"; //} //catch (Exception ex) //{ // Debug.WriteLine(ex.Message); // return "人员调动失败!"; //} //finally //{ // pipeline.Dispose(); // runsp.Close(); //} #endregion try { // 生成一个连接类型,传入exchange服务器IP、将要使用的Scheme以及管理员凭据 var connectionInfo = ExchangeScriptInit(); var array = recipientContainer.Split('/'); string container = array[array.Length - 2]; string conditionnalName = array[array.Length - 1]; using (var rs = RunspaceFactory.CreateRunspace(connectionInfo)) { var psh = PowerShell.Create(); psh.Runspace = rs; rs.Open(); //var sScript = "new-AddressList -Name '" + name + "' -RecipientContainer '" + recipientContainer + "' -IncludedRecipients 'AllRecipients' -ConditionalDepartment '" + conditionnalName + "' -Container '\\"+conditionnalName+"' -DisplayName '"+displayName+"'"; var sScript = "new-AddressList -Name '" + name + "' -RecipientContainer '" + recipientContainer + "' -IncludedRecipients 'AllRecipients' -ConditionalDepartment '" + conditionnalName + "' -Container '\\" + container + "' -DisplayName '" + displayName + "'"; //new-AddressList -Name 'test5' -RecipientContainer 'test.com/xd-ad/集团公司/党委' -IncludedRecipients 'AllRecipients' -ConditionalDepartment '党委' -Container '\\集团公司' -DisplayName 'test5' psh.Commands.AddScript(sScript); var sScript1 = "update-AddressList -identity '\\" + name + "'"; psh.Commands.AddScript(sScript1); psh.Invoke(); rs.Close(); psh.Runspace.Close(); return(true); } } catch (Exception e) { return(false); } }
public string EnableMail(string identity) { var message = ""; var success = ""; #region 取得Exchange所需要的数据 var array = identity.Split('/'); var displayName = array[array.Length - 1]; if (!displayName.Contains(".") || !displayName.Contains("-")) { return("邮件开启失败!"); } var alias = displayName.Substring(0, displayName.IndexOf('.')); //var ouDeptPath = identity.Substring(0, identity.Length - displayName.Length); var updateName = identity.Substring(identity.IndexOf('/') + 1, identity.LastIndexOf('/') - identity.IndexOf('/') - 1).Replace('/', '\\'); var ouCompanyName = array[array.Length - 3]; //根据公司的名称,在数据库中找到该公司所对应的数据库名称,并赋值给dataBase变量 var emailData = (new AdmgrModel()).EmailDatas.FirstOrDefault(a => a.CompanyName == ouCompanyName); string dataBase = emailData.EmailStoreDb; #endregion var search = new DirectorySearcher(_root); search.Filter = "(name=" + displayName + ")"; //search.PropertiesToLoad.Add("cn"); var result = search.FindOne(); //确认AD使用者是否存在 if (result == null) { message = "该AD域用户不存在!"; } else { //判断使用者mail栏是否有值 var user = result.GetDirectoryEntry(); //工号(在域里字段是名) if (user.Properties.Contains("homeMDB") && user.Properties.Contains("homeMTA")) { message = "该AD域用户邮件已开启!"; } else if (dataBase == null) { message = "邮箱数据库未定义!"; } else { try { // 生成一个连接类型,传入exchange服务器IP、将要使用的Scheme以及管理员凭据 var connectionInfo = ExchangeScriptInit(); // 创建一个命令空间,创建管线通道,传入要运行的powershell命令,执行命令 using (var rs = RunspaceFactory.CreateRunspace(connectionInfo)) { var psh = PowerShell.Create(); psh.Runspace = rs; rs.Open(); var sScript = "Enable-Mailbox -identity '" + identity + "' -Alias '" + alias + "' -Database '" + dataBase + "'"; psh.Commands.AddScript(sScript); //var sScript2 = "update-AddressList -identity '" + updateName + "'"; //psh.Commands.AddScript(sScript2); var psresults = psh.Invoke(); if (psresults == null) { message = "邮件开启失败!"; } if (psh.Streams.Error.Count > 0) { var strbmessage = new StringBuilder(); foreach (var err in psh.Streams.Error) { strbmessage.AppendLine(err.ToString()); } message = strbmessage.ToString(); } else { success = "1"; } rs.Close(); psh.Runspace.Close(); } } catch (Exception e) { return(e.Message + ":邮件开启失败!"); } finally { } if (success == "1") { message = "邮件开启成功!"; } else { message = "邮件开启失败!" + message; } } } return(message); }
/// <summary> /// By default serialization preserves all public properties of an object. /// /// This sample looks at an existing .NET class and shows how to make sure that /// information from instance of this class is preserved across serialization/deserialization /// when the information is not available in public properties of the class /// </summary> static void Main() { string typesPs1XmlPath = Path.Combine(Environment.CurrentDirectory, "Serialization02.types.ps1xml"); if (!File.Exists(typesPs1XmlPath)) { Console.WriteLine("Building the project in Visual Studio should have created a types.ps1xml file at the following path:"); Console.WriteLine("{0}", typesPs1XmlPath); Console.WriteLine(); Console.WriteLine("Cannot continue without this file being present."); return; } // Create a default InitialSessionState InitialSessionState iss = InitialSessionState.CreateDefault(); // Add our types.ps1xml file to the InitialSessionState // (one alternative would be to associate the file with a module or with a snap-in) iss.Types.Add(new SessionStateTypeEntry(typesPs1XmlPath)); // // Demonstrate the effects of the types.ps1xml and DeserializingTypeConverter // using (Runspace myRunspace = RunspaceFactory.CreateRunspace(iss)) { myRunspace.Open(); // // Demonstrate that the deserializing an exception results in a live object // using (PowerShell powershell = PowerShell.Create()) { powershell.Runspace = myRunspace; powershell.AddScript(@" # Get an System.Drawing.Point object Add-Type -AssemblyName System.Drawing $point = New-Object System.Drawing.Point 12,34 # Verify that the extra property is hidden by default Write-Output 'Below are the results of running $point | Format-List * :' $point | Format-List * | Out-String Write-Output '----------------------------------------' # Serialize the object $point | Export-CliXml .\Serialization02.xml # Deserialize the object $deserializedPoint = Import-CliXml .\Serialization02.xml # Verify that the extra property got serialized Write-Output 'Below are the results of running $deserializedPoint | Get-Member :' $deserializedPoint | Get-Member | Out-String Write-Output '----------------------------------------' "); foreach (string s in powershell.Invoke <string>()) { System.Console.WriteLine(s); } } // Close the runspace and release any resources. myRunspace.Close(); } System.Console.WriteLine("Hit any key to exit..."); System.Console.ReadKey(); }
// .\WMIMon.exe "[-filter=regularexpression]" "[-stop=[start|end|none]]" [-log=all|filter] [-action=powershellpipeline]] static void Main(string[] args) { string filter = ""; StopCondition uStop = StopCondition.none; bool LogOnFilter = true; UInt64 IfStopStatus = 0; bool bAction = false; string PipeLine = ""; Runspace runSpace = RunspaceFactory.CreateRunspace(); runSpace.Open(); Dictionary <UInt64, string> PendingOp = new Dictionary <UInt64, string>(); foreach (string arg in args) { Match m; m = Regex.Match(arg, "-(f|fi|fil|filt|filt|filte|filter)=(.+)", RegexOptions.IgnoreCase); if (m.Success) { filter = m.Groups[2].ToString().ToLower(); Console.WriteLine("Parsing:\tfiltering on {0}", filter); if (!IsValidRegex(filter)) { Console.WriteLine("Parsing:\tInvalid regular expression {0}", filter); return; } continue; } m = Regex.Match(arg, "-(s|st|sto|stop)=(start|end|none)", RegexOptions.IgnoreCase); if (m.Success) { string stop = m.Groups[2].ToString().ToLower(); uStop = StopCondition.none; if (stop == "start") { uStop = StopCondition.start; } else if (stop == "end") { uStop = StopCondition.stop; } Console.WriteLine("Parsing:\twill stop if filter matches {0}", stop); continue; } m = Regex.Match(arg, "-(l|lo|log)=(all|filter)", RegexOptions.IgnoreCase); if (m.Success) { string log = m.Groups[2].ToString().ToLower(); Console.WriteLine("Parsing:\tlogging option : {0} ", log); if (log == "all") { LogOnFilter = false; } else { LogOnFilter = true; } continue; } m = Regex.Match(arg, "-(i|if|ifs|ifsto|ifstop|ifstops|ifstopst|ifstopstat|ifstopstatu|ifstopstatus)=(0x[0-9,a-f]+|[0-9,a-f]+)", RegexOptions.IgnoreCase); if (m.Success) { // bAction = true; IfStopStatus = Convert.ToUInt64(m.Groups[2].ToString(), 16); Console.WriteLine("Parsing:\tPowershell will end if status is : 0x{0:x} ", IfStopStatus); continue; } m = Regex.Match(arg, "-(a|ac|act|acti|actio|action)=(.+)", RegexOptions.IgnoreCase); if (m.Success) { bAction = true; PipeLine = m.Groups[2].ToString(); Console.WriteLine("Parsing:\tPowershell action when filter is found : {0} ", PipeLine); } else { Console.WriteLine("Parsing:\tInvalid argument {0}\n", arg); Console.WriteLine( @" Usage: WmiMon [-filter=regular_expression_string] [-stop=start|end|none] [-ifstopstatus=hexadecimal_value] [-log=all|filter] [action=pipeline] default WmiMon [-filter=.*] [-stop=none] [-log=all] will monitor WMI activity. By default all WMI activities are displayed. You can filter the output with the -filter switch. You can stop the application : - if the filtering is successfull. Stop will occur at activity startup if -stop=start is specified. If -stop=end is specified we will wait for the end of the activity to stop the monitoring Warning : if many records match the filtering pattern , memory usage may increase - if the filtering is successfull and _ifstopstatus condition is meet Warning : if many records match the filtering pattern , memory usage for this query may be hudge For all filtered items or if a stop condition is meet , the pipeline action will be executed Powershell variables WMIMON_* will be set in Powershell runspace to reflect the current WMI activity. Your Powershell actions may use these variables (client PID, client computer, client user, stop status, WMI query,...) N.B: WMIMon is based on RealTime ETL notification. ETL infrastructure doesn't guarantee that all events will be received. N.B: WMI Stop operation logging may occur after a delay based on client (get-cim* cmdlets cleanup occurs immediately This is not true with get-wmiobject cmdlet). Feel Free to report any bug or suggestion to [email protected] Example: " ); return; } } var exitEvent = new ManualResetEvent(false); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; exitEvent.Set(); }; NotifyCallback Notify = (string OutStr, bool bError) => { if (bError) { Console.WriteLine("******! Error {0}", OutStr); } else { Console.WriteLine("***** {0}", OutStr); } }; GetResultCallBack Result = (string OutStr, UInt32 GroupId, UInt32 OpId) => { bool bDisplay = true; bool bStopOperation = false; UInt64 StopStatus = 0; string ClientProcessId = ""; string Executable = ""; string Computer = ""; string User = ""; bool bFilter = (filter.Length != 0) ? true : false; bool bFilterMatch = false; bool bStop = false; string PendingQuery = ""; bool bDisplayStop = false; Match m; m = Regex.Match(OutStr, "^\\d\\d:\\d\\d:\\d\\d.\\d\\d\\d Stop Op=\\d+ 0x([0-9a-fA-F]+)", RegexOptions.IgnoreCase); if (m.Success) { bStopOperation = true; bDisplayStop = true; StopStatus = Convert.ToUInt64(m.Groups[1].ToString(), 16); if (bFilter) { bDisplayStop = false; //is this operation in the Pending list if (PendingOp.TryGetValue(OpId, out PendingQuery)) { m = Regex.Match(PendingQuery, "^\\d\\d:\\d\\d:\\d\\d.\\d\\d\\d .* _ClientProcessId=(\\d+) \\[(.*)\\] (.*) (.*) ", RegexOptions.IgnoreCase); if (m.Success) { ClientProcessId = m.Groups[1].ToString(); Executable = m.Groups[2].ToString(); Computer = m.Groups[3].ToString(); User = m.Groups[4].ToString(); bDisplayStop = true; } PendingOp.Remove(OpId); if ((IfStopStatus != 0) && (StopStatus == IfStopStatus)) { bStop = true; } else if (StopCondition.stop == uStop) { bStop = true; } // Console.WriteLine("==== Debug : Removing Pending Stop {0} \\ {1}\\ bStop {2} ", OutStr, PendingQuery , bStop ); } } } else { bStopOperation = false; m = Regex.Match(OutStr, "^\\d\\d:\\d\\d:\\d\\d.\\d\\d\\d .* _ClientProcessId=(\\d+) \\[(.*)\\] (.*) (.*) ", RegexOptions.IgnoreCase); if (m.Success) { ClientProcessId = m.Groups[1].ToString(); Executable = m.Groups[2].ToString(); Computer = m.Groups[3].ToString(); User = m.Groups[4].ToString(); } } if (!bStopOperation) { if (bFilter) { string outwithoutn = OutStr.Replace("\n", ""); MatchCollection mFilter = Regex.Matches(outwithoutn, filter, RegexOptions.IgnoreCase | RegexOptions.Multiline); if (mFilter.Count > 0) { bFilterMatch = true; } } } // at this point // bFilter ==> if filter // bFilterMatch ==> if filter match // bLogFilter ==> true -log=filter // ==> false -log=all // uStop ==> StopCondition.none , StopCondition.start , StopCondition.end // bAction == TRUE ==> pipeline bDisplay = false; if (bFilter) { bDisplay = false; if (bFilterMatch && LogOnFilter == true) { bDisplay = true; } else if (LogOnFilter == false) { bDisplay = true; } if (uStop == StopCondition.start && bFilterMatch) { bStop = true; } else if (uStop == StopCondition.stop && bFilterMatch) { // TODO : add to stoppending list } if (bFilter && bFilterMatch) { PendingOp.Add(OpId, OutStr); // Console.WriteLine("==== Debug Adding {0} in Pending list ", OpId); } } else { bDisplay = true; } if (bDisplay || bDisplayStop) { Console.WriteLine("***** {0}", OutStr); } if ((bAction && bFilter && bFilterMatch) | (bStop && bFilter)) { // TODO Execute Pipeline runSpace.SessionStateProxy.SetVariable("WMIMON_PID", ClientProcessId); runSpace.SessionStateProxy.SetVariable("WMIMON_EXECUTABLE", Executable); runSpace.SessionStateProxy.SetVariable("WMIMON_COMPUTER", Computer); runSpace.SessionStateProxy.SetVariable("WMIMON_USER", User); runSpace.SessionStateProxy.SetVariable("WMIMON_STOPSTATUS", StopStatus); runSpace.SessionStateProxy.SetVariable("WMIMON_ACTIVITY", OutStr); runSpace.SessionStateProxy.SetVariable("WMIMON_RELATEDACTIVITY", PendingQuery); Pipeline pipeline = runSpace.CreatePipeline(); String script = PipeLine + " | out-string "; pipeline.Commands.AddScript(script); Collection <PSObject> Results; try { Results = pipeline.Invoke(); foreach (PSObject PsObj in Results) { Console.WriteLine(PsObj.ToString()); } } catch (PSInvalidOperationException ioe) { Console.WriteLine("Powershell Error: " + ioe.Message); pipeline.Stop(); pipeline = null; } catch (System.Management.Automation.RuntimeException error) { ErrorRecord e = error.ErrorRecord; Console.WriteLine("Powershell Error: {0}{1} ", e.ToString(), e.InvocationInfo.PositionMessage); pipeline.Stop(); pipeline = null; } } if (bStop) { exitEvent.Set(); } }; IntPtr Context = (IntPtr)1; IntPtr Handle = exitEvent.SafeWaitHandle.DangerousGetHandle(); try { StartAndWait((IntPtr)Handle, Context, Notify, Result); // cf https://msdn.microsoft.com/en-us/library/7esfatk4(VS.71).aspx } catch (SystemException e) { Console.WriteLine("Unexpected error {0} ", e); } }
public void RunTests(IEnumerable <TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle) { _mCancelled = false; SetupExecutionPolicy(); foreach (var test in tests) { if (_mCancelled) { break; } var testFramework = test.FullyQualifiedName.Split(new[] { "||" }, StringSplitOptions.None)[0]; var executor = _testExecutors.FirstOrDefault( m => m.TestFramework.Equals(testFramework, StringComparison.OrdinalIgnoreCase)); if (executor == null) { frameworkHandle.SendMessage(TestMessageLevel.Error, String.Format("Unknown test executor: {0}", testFramework)); return; } var testResult = new TestResult(test); testResult.Outcome = TestOutcome.Failed; testResult.ErrorMessage = "Unexpected error! Failed to run tests!"; PowerShellTestResult testResultData = null; var testOutput = new StringBuilder(); try { var testAdapter = new TestAdapterHost(); testAdapter.HostUi.OutputString = s => testOutput.Append(s); var runpsace = RunspaceFactory.CreateRunspace(testAdapter); runpsace.Open(); using (var ps = PowerShell.Create()) { ps.Runspace = runpsace; testResultData = executor.RunTest(ps, test, runContext); } } catch (Exception ex) { testResult.Outcome = TestOutcome.Failed; testResult.ErrorMessage = ex.Message; testResult.ErrorStackTrace = ex.StackTrace; } if (testResultData != null) { testResult.Outcome = testResultData.Outcome; testResult.ErrorMessage = testResultData.ErrorMessage; testResult.ErrorStackTrace = testResultData.ErrorStacktrace; } if (testOutput.Length > 0) { frameworkHandle.SendMessage(TestMessageLevel.Informational, testOutput.ToString()); } frameworkHandle.RecordResult(testResult); } }
public MainWindow() { DateTime dstart = DateTime.Now; InitializeComponent(); CommandArgs.AddRange(Environment.GetCommandLineArgs()); CommandArgs.RemoveAt(0); //Disable SSL/TLS Errors System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; //Disable CRL Check System.Net.ServicePointManager.CheckCertificateRevocationList = false; //Get Proxy from IE WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy(); if (Properties.Settings.Default.UpgradeSettings) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpgradeSettings = false; Properties.Settings.Default.Save(); } //Get Version FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location); tbVersion.Text = string.Format(tbVersion.Text, fvi.FileVersion); lVersion.Content = "Version: " + fvi.FileVersion; //Hide Tabs Style s = new Style(); s.Setters.Add(new Setter(UIElement.VisibilityProperty, Visibility.Collapsed)); tabWizard.ItemContainerStyle = s; tbSVC.Text = RZRestAPIv2.sURL; if (RZRestAPIv2.DisableBroadcast) { cbRZCache.IsChecked = false; cbRZCache.IsEnabled = false; } else { RZRestAPIv2.DisableBroadcast = Properties.Settings.Default.DisableBroadcast; cbRZCache.IsChecked = !Properties.Settings.Default.DisableBroadcast; } if (string.IsNullOrEmpty(RZRestAPIv2.CustomerID)) { tbCustomerID.IsEnabled = true; RZRestAPIv2.CustomerID = Properties.Settings.Default.CustomerID; btSettingsSave.IsEnabled = true; } else { tbCustomerID.Text = RZRestAPIv2.CustomerID; tbCustomerID.IsEnabled = false; btSettingsSave.IsEnabled = false; } oInstPanel.onEdit += oInstPanel_onEdit; oUpdPanel.onEdit += oInstPanel_onEdit; //oInstPanel.OnSWUpdated += OUpdPanel_OnSWUpdated; oUpdPanel.OnSWUpdated += OUpdPanel_OnSWUpdated; double dSeconds = (DateTime.Now - dstart).TotalSeconds; dSeconds.ToString(); //Run PowerShell check in separate thread... Thread thread = new Thread(() => { try { Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); PowerShell powershell = PowerShell.Create(); powershell.AddScript("(get-Host).Version"); powershell.Runspace = runspace; Collection <PSObject> results = powershell.Invoke(); if (((System.Version)(results[0].BaseObject)).Major < 4) { if (MessageBox.Show("The current Version of PowerShell is not supported. Do you want to update ?", "Update Powershell", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.Yes) == MessageBoxResult.Yes) { //Update... Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=50395"); this.Close(); } } } catch { } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); FileVersionInfo FI = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location); oSCAN = new RZScan(false, true); oSCAN.StaticInstalledSoftware.Add(new AddSoftware() { ProductName = "RuckZuck", Manufacturer = FI.CompanyName, ProductVersion = FI.ProductVersion.ToString() }); oSCAN.OnSWScanCompleted += OSCAN_OnSWScanCompleted; oSCAN.OnUpdatesDetected += OSCAN_OnUpdatesDetected; oSCAN.OnSWRepoLoaded += OSCAN_OnSWRepoLoaded; oSCAN.OnUpdScanCompleted += OSCAN_OnUpdScanCompleted; oSCAN.OnInstalledSWAdded += OSCAN_OnInstalledSWAdded; oSCAN.bCheckUpdates = true; oSCAN.GetSWRepository().ConfigureAwait(false); //oSCAN.tRegCheck.Start(); if (CommandArgs.Count > 0) { } else { //Show About once... if (!Properties.Settings.Default.ShowAbout) { tabWizard.SelectedItem = tabMain; } else { tabWizard.SelectedItem = tabStart; Properties.Settings.Default.ShowAbout = false; Properties.Settings.Default.Save(); } } }
/// <summary> /// Collects Dart Logs by calling the jta2 launcher and placing them in the location defined by the framework server setting. /// </summary> /// <remarks> Be sure that Java SDK, SNMPGet and JTA3 @ C:\JTA are located on the server.</remarks> /// <param name="assetID"></param> /// <param name="sessionID"></param> /// <param name="email"></param> public void CollectLog(string assetID, string sessionID, string email) { string printerIP = string.Empty; string dartIP = string.Empty; bool collectDart = false; string script = string.Empty; string modelName = string.Empty; try { using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { var temp = context.Assets.OfType <Printer>().FirstOrDefault(n => n.AssetId == assetID); printerIP = temp.Address1; modelName = temp.Product.Split(' ').First(); if (string.IsNullOrEmpty(printerIP)) { TraceFactory.Logger.Debug($@"Printer IP Not found for asset: {assetID}"); return; } var dartBoard = context.DartBoards.FirstOrDefault(n => n.PrinterId == assetID); if (dartBoard == null) { TraceFactory.Logger.Debug($@"No DartBoard found for: {assetID}"); collectDart = false; } else { dartIP = dartBoard.Address; collectDart = true; } string serverType = ServerType.Dart.ToString(); FrameworkServer server = context.FrameworkServers.FirstOrDefault(n => n.ServerTypes.Any(m => m.Name == serverType) && n.Active); string dartLocation = server.ServerSettings.First(n => n.Name == "DartServiceLocation").Value; string jtaLocation = GlobalSettings.Items["JTALogCollectorDirectory"]; string inAddition = $@"\{sessionID}"; DirectoryInfo di = Directory.CreateDirectory(dartLocation + inAddition); bool pingResult = false; using (var ping = new Ping()) { var response = ping.Send(printerIP, (int)TimeSpan.FromSeconds(15).TotalMilliseconds); //DV: sometimes the device, being lazy as it is, will be in sleep mode and doesn't respond to the ping command //so we poke it few more times so that it wakes up from its slumber and responds. int retries = 0; while (response.Status != IPStatus.Success && retries < 4) { System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); response = ping.Send(printerIP, (int)TimeSpan.FromSeconds(15).TotalMilliseconds); retries++; } if (response.Status != IPStatus.Success) { TraceFactory.Logger.Debug($"Ping Unsuccessful: {printerIP.ToString()}:{response.Status}"); pingResult = false; } else { pingResult = true; } } //Extra check that the device is in dev mode for JTA. if (pingResult) { pingResult = CheckProd(temp.Address1, temp.Password); } //If JTA checks are not a success, use dart.exe, else use JTA --Don't use JTA for dart logs. It may fail before dart collection if (pingResult) { if (collectDart) { bool result = false; Task.Factory.StartNew(() => { //Get DARTLOCATION FROM Global Settings string timestamp = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = true; startInfo.FileName = @"dart.exe"; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.Arguments = $@"{dartIP} dl {dartLocation + inAddition}\{assetID}_{timestamp}.bin"; try { using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); } result = true; TraceFactory.Logger.Debug($@"Capture of {assetID} logs succeeded"); SendEmail(sessionID, assetID, result, email); } catch (Exception a) { TraceFactory.Logger.Error("Dart log collection failed."); TraceFactory.Logger.Error(a); } }); //TraceFactory.Logger.Info($@"Attempting to collect logs of {assetID} for Session ID: {sessionID}."); //script = $@"cd {jtaLocation} | java jta3.Launcher -p {modelName} -x {printerIP} -r {dartLocation + inAddition} -s false"; } TraceFactory.Logger.Info($@"Attempting to collect logs of {assetID} for Session ID: {sessionID}."); script = $@"cd {jtaLocation} | java jta3.Launcher -p {modelName} -x {printerIP} -r {dartLocation + inAddition} -s false"; Task.Factory.StartNew(() => { bool result = false; try { Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); TraceFactory.Logger.Debug(Environment.CurrentDirectory); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(string.Format("$user = \"{0}\"", "jawa")); pipeline.Commands.AddScript(script); Collection <PSObject> results = pipeline.Invoke(); bool hadErrors = pipeline.HadErrors; runspace.Close(); result = !hadErrors; TraceFactory.Logger.Debug($@"Capture of {assetID} logs succeeded, Error during collection? {hadErrors}"); if (hadErrors) { StringBuilder builder = new StringBuilder(); foreach (PSObject obj in results) { builder.AppendLine(obj.ToString()); } TraceFactory.Logger.Debug($@"{builder}"); } } catch (Exception a) { result = false; TraceFactory.Logger.Debug("JTA log collection failed."); TraceFactory.Logger.Debug(a); } SendEmail(sessionID, assetID, result, email); }); } else { if (collectDart) { bool result = false; Task.Factory.StartNew(() => { //Get DARTLOCATION FROM Global Settings string timestamp = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = true; startInfo.FileName = @"dart.exe"; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.Arguments = $@"{dartIP} dl {dartLocation + inAddition}\{assetID}_{timestamp}.bin"; try { using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); } result = true; TraceFactory.Logger.Debug($@"Capture of {assetID} logs succeeded"); SendEmail(sessionID, assetID, result, email); } catch (Exception a) { TraceFactory.Logger.Error("Dart log collection failed."); TraceFactory.Logger.Error(a); } } ); } } } } catch (Exception e) { TraceFactory.Logger.Error(e); } }
void saveButton_Click(object sender, EventArgs e) { if (SPFarm.Local.CurrentUserIsAdministrator() == false) { throw new SecurityException("Access Denied! Current user is not a farm administrator."); } if (scriptProperty == null) { scriptProperty = new SPFeatureProperty(propNameScript, scriptBox.Text); feature.Properties.Add(scriptProperty); } else { scriptProperty.Value = scriptBox.Text; } if (sequenceProperty == null) { sequenceProperty = new SPFeatureProperty(propNameSequence, sequenceNumber.Text); feature.Properties.Add(sequenceProperty); } else { sequenceProperty.Value = sequenceNumber.Text; } feature.Properties.Update(); //clean power event receivers List <SPEventReceiverDefinition> receiversToDelete = new List <SPEventReceiverDefinition>(); SPEventReceiverDefinitionCollection receivers = null; if (eventType == PowerEventType.Item || eventType == PowerEventType.List) { receivers = list.EventReceivers; } else { receivers = web.EventReceivers; } foreach (SPEventReceiverDefinition receiver in receivers) { if (receiver.Class == typeof(PowerItemEventReceiver).FullName) { receiversToDelete.Add(receiver); } } foreach (SPEventReceiverDefinition receiver in receiversToDelete) { receiver.Delete(); } if (!String.IsNullOrEmpty(sequenceNumber.Text)) { Runspace runspace = null; try { runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipe = runspace.CreatePipeline(scriptBox.Text); pipe.Invoke(); pipe = runspace.CreatePipeline("get-childitem function:\\"); Collection <PSObject> results = pipe.Invoke(); string[] receiverTypes = Enum.GetNames(typeof(SPEventReceiverType)); foreach (PSObject obj in results) { FunctionInfo func = (FunctionInfo)obj.BaseObject; if (receiverTypes.Contains(func.Name)) { SPEventReceiverDefinition eventReceiverDef = null; if (eventType == PowerEventType.Web) { eventReceiverDef = web.EventReceivers.Add(); } else { eventReceiverDef = list.EventReceivers.Add(); } eventReceiverDef.Assembly = Assembly.GetExecutingAssembly().FullName; eventReceiverDef.Class = eventDefinitionType; eventReceiverDef.Type = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), func.Name); eventReceiverDef.SequenceNumber = int.Parse(sequenceNumber.Text); eventReceiverDef.Update(); } } } catch (Exception ex) { throw ex; } finally { if (runspace != null && runspace.RunspaceStateInfo.State != RunspaceState.Closed) { runspace.Close(); runspace = null; } } } Response.Redirect(redirectUrl, true); }
private PowerShellExecutionResults run_host(ChocolateyConfiguration config, string chocoPowerShellScript) { // since we control output in the host, always set these true Environment.SetEnvironmentVariable("ChocolateyEnvironmentDebug", "true"); Environment.SetEnvironmentVariable("ChocolateyEnvironmentVerbose", "true"); var result = new PowerShellExecutionResults(); string commandToRun = wrap_script_with_module(chocoPowerShellScript, config); var host = new PoshHost(config); this.Log().Debug(() => "Calling built-in PowerShell host with ['{0}']".format_with(commandToRun.escape_curly_braces())); var initialSessionState = InitialSessionState.CreateDefault(); // override system execution policy without accidentally setting it initialSessionState.AuthorizationManager = new AuthorizationManager("choco"); using (var runspace = RunspaceFactory.CreateRunspace(host, initialSessionState)) { runspace.Open(); // this will affect actual execution policy //RunspaceInvoke invoker = new RunspaceInvoke(runspace); //invoker.Invoke("Set-ExecutionPolicy ByPass"); using (var pipeline = runspace.CreatePipeline()) { // The powershell host itself handles the following items: // * Write-Debug // * Write-Host // * Write-Verbose // * Write-Warning // // the two methods below will pick up Write-Output and Write-Error // Write-Output pipeline.Output.DataReady += (sender, args) => { PipelineReader <PSObject> reader = sender as PipelineReader <PSObject>; if (reader != null) { while (reader.Count > 0) { host.UI.WriteLine(reader.Read().to_string().escape_curly_braces()); } } }; // Write-Error pipeline.Error.DataReady += (sender, args) => { PipelineReader <object> reader = sender as PipelineReader <object>; if (reader != null) { while (reader.Count > 0) { host.UI.WriteErrorLine(reader.Read().to_string().escape_curly_braces()); } } }; var documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.DoNotVerify); var currentUserCurrentHostProfile = _fileSystem.combine_paths(documentsFolder, "WindowsPowerShell\\Microsoft.PowerShell_profile.ps1"); var recreateProfileScript = @" if ((Test-Path(""{0}"")) -and ($profile -eq $null -or $profile -eq '')) {{ $global:profile = ""{1}"" }} ".format_with(documentsFolder, currentUserCurrentHostProfile); pipeline.Commands.Add(new Command(recreateProfileScript, isScript: true, useLocalScope: false)); // The PowerShell Output Redirection bug affects System.Management.Automation // it appears with v3 more than others. It is already known to affect v2 // this implements the redirection fix from the post below, fixed up with some comments // http://www.leeholmes.com/blog/2008/07/30/workaround-the-os-handles-position-is-not-what-filestream-expected/ const string outputRedirectionFixScript = @" try { $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetField"" $objectRef = $host.GetType().GetField(""externalHostRef"", $bindingFlags).GetValue($host) $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetProperty"" $consoleHost = $objectRef.GetType().GetProperty(""Value"", $bindingFlags).GetValue($objectRef, @()) [void] $consoleHost.GetType().GetProperty(""IsStandardOutputRedirected"", $bindingFlags).GetValue($consoleHost, @()) $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetField"" $field = $consoleHost.GetType().GetField(""standardOutputWriter"", $bindingFlags) $field.SetValue($consoleHost, [Console]::Out) [void] $consoleHost.GetType().GetProperty(""IsStandardErrorRedirected"", $bindingFlags).GetValue($consoleHost, @()) $field2 = $consoleHost.GetType().GetField(""standardErrorWriter"", $bindingFlags) $field2.SetValue($consoleHost, [Console]::Error) } catch { Write-Output ""Unable to apply redirection fix"" } "; pipeline.Commands.Add(new Command(outputRedirectionFixScript, isScript: true, useLocalScope: false)); pipeline.Commands.Add(new Command(commandToRun, isScript: true, useLocalScope: false)); try { pipeline.Invoke(); } catch (RuntimeException ex) { var errorStackTrace = ex.StackTrace; var record = ex.ErrorRecord; if (record != null) { // not available in v1 //errorStackTrace = record.ScriptStackTrace; var scriptStackTrace = record.GetType().GetProperty("ScriptStackTrace"); if (scriptStackTrace != null) { var scriptError = scriptStackTrace.GetValue(record, null).to_string(); if (!string.IsNullOrWhiteSpace(scriptError)) { errorStackTrace = scriptError; } } } this.Log().Error("ERROR: {0}{1}".format_with(ex.Message.escape_curly_braces(), !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine, errorStackTrace.escape_curly_braces()))); } catch (Exception ex) { // Unfortunately this doesn't print line number and character. It might be nice to get back to those items unless it involves tons of work. this.Log().Error("ERROR: {0}{1}".format_with(ex.Message.escape_curly_braces(), !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine, ex.StackTrace.escape_curly_braces()))); } if (pipeline.PipelineStateInfo != null) { switch (pipeline.PipelineStateInfo.State) { // disconnected is not available unless the assembly version is at least v3 //case PipelineState.Disconnected: case PipelineState.Running: case PipelineState.NotStarted: case PipelineState.Failed: case PipelineState.Stopping: case PipelineState.Stopped: if (host.ExitCode == 0) { host.SetShouldExit(1); } host.HostException = pipeline.PipelineStateInfo.Reason; break; case PipelineState.Completed: if (host.ExitCode == -1) { host.SetShouldExit(0); } break; } } } } this.Log().Debug("Built-in PowerShell host called with ['{0}'] exited with '{1}'.".format_with(commandToRun.escape_curly_braces(), host.ExitCode)); result.ExitCode = host.ExitCode; result.StandardErrorWritten = host.StandardErrorWritten; return(result); }
protected override void BeginProcessing() { // Build the results ArrayList final = new ArrayList(); int c = 0; int count = InputObject.Count; if (MaxThreads < 20) { MaxThreads = 20; } using (RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(1, MaxThreads)) { try { runspacePool.Open(); ProgressRecord progressRecord = new ProgressRecord(1, "Action in progress...", "Processing..."); foreach (object obj in InputObject) { PowerShell powerShell = PowerShell.Create() .AddScript(ScriptBlock) .AddArgument(obj); try { powerShell.AddParameters(ArgumentList); } catch (Exception) { } powerShell.RunspacePool = runspacePool; IAsyncResult psAsyncResult = powerShell.BeginInvoke(); c++; int pVal = (c / count) * 100; string sVal = String.Format("{0:N0}", pVal); int perc = int.Parse(sVal); string activity = c + " of " + count + " threads completed"; if (NoProgress.IsPresent == false) { progressRecord.PercentComplete = perc; progressRecord.Activity = activity; progressRecord.StatusDescription = perc + "% complete"; WriteProgress(progressRecord); } PSDataCollection <PSObject> psOutput = powerShell.EndInvoke(psAsyncResult); final.Add(psOutput); powerShell.Dispose(); } // End foreach if (NoProgress.IsPresent == false) { progressRecord.PercentComplete = 100; progressRecord.StatusDescription = "100% complete"; WriteProgress(progressRecord); } } catch (Exception) { throw; } runspacePool.Close(); runspacePool.Dispose(); } // End using // Output to console WriteObject(final.ToArray(), true); } // End begin
public PS() { this.runspace = RunspaceFactory.CreateRunspace(); // open it this.runspace.Open(); }
protected void Initialize() { try { SPSecurity.RunWithElevatedPrivileges(() => { if (String.IsNullOrEmpty(Script) == false) { VerifySignature(); } if (Debug && PowerWebPartHelper.IsPowerUser) { debugHost = new PowerWebPartDebugHost(this); runspace = RunspaceFactory.CreateRunspace(debugHost); debugHost.StartDebugSession(); } else { runspace = RunspaceFactory.CreateRunspace(); } runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; runspace.Open(); }); eventHandlerDelegate = new EventHandler(EventDispatcher); SPContext ctx = SPContext.Current; runspace.SessionStateProxy.SetVariable("this", this); runspace.SessionStateProxy.SetVariable("viewState", this.ViewState); runspace.SessionStateProxy.SetVariable("spContext", ctx); runspace.SessionStateProxy.SetVariable("httpContext", HttpContext.Current); runspace.SessionStateProxy.SetVariable("site", ctx.Site); runspace.SessionStateProxy.SetVariable("web", ctx.Web); runspace.SessionStateProxy.SetVariable("list", ctx.List); runspace.SessionStateProxy.SetVariable("item", ctx.Item); runspace.SessionStateProxy.SetVariable("webpart", WebPart); runspace.SessionStateProxy.SetVariable("debug", Debug); if (this.Page != null) { runspace.SessionStateProxy.SetVariable("scriptManager", ScriptManager.GetCurrent(this.Page)); runspace.SessionStateProxy.SetVariable("isPostBack", this.Page.IsPostBack); runspace.SessionStateProxy.SetVariable("page", this.Page); runspace.SessionStateProxy.SetVariable("webPartManager", SPWebPartManager.GetCurrentWebPartManager(Page)); } if (String.IsNullOrEmpty(Script) == false) { string coreScript = PowerWebPartHelper.CoreScript; if (!String.IsNullOrEmpty(coreScript)) { Pipeline tmpPipe = CreatePipeline(); tmpPipe.Commands.AddScript(coreScript); if (Debug && PowerWebPartHelper.IsPowerUser && String.IsNullOrEmpty(DebugOptions) == false) { tmpPipe.Commands.AddScript("Set-PSDebug " + DebugOptions); } InvokePipeline(tmpPipe, false); } if (!String.IsNullOrEmpty(Script)) { LoadScriptFunctions(); } } } catch (Exception ex) { powerWebPartException = new PowerControlException("Initialization", ex); } }