public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(GetRelease)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create a project var project = new ProjectResource { Name = "Octopus" }; octoRepo.Setup(o => o.Projects.FindByName("Octopus")).Returns(project); octoRepo.Setup(o => o.Projects.Get("projects-1")).Returns(project); octoRepo.Setup(o => o.Projects.Get("Gibberish")).Throws(new OctopusResourceNotFoundException("Not Found")); var releases = new List<ReleaseResource> { new ReleaseResource {Version = "1.0.0"}, new ReleaseResource {Version = "1.0.1"}, new ReleaseResource {Version = "1.1.0"} }; octoRepo.Setup(o => o.Projects.GetReleases(project, 0)) .Returns(new ResourceCollection<ReleaseResource>(releases, new LinkCollection())); octoRepo.Setup(o => o.Projects.GetReleaseByVersion(project, "1.0.0")).Returns(releases[0]); octoRepo.Setup(o => o.Projects.GetReleaseByVersion(project, "Gibberish")).Throws(new OctopusResourceNotFoundException("Not found")); octoRepo.Setup(o => o.Releases.Get("releases-1")).Returns(releases[0]); octoRepo.Setup(o => o.Releases.Get("Gibberish")).Throws(new OctopusResourceNotFoundException("Not found")); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(AddVariable)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); _variableSet.Variables.Clear(); var project = new ProjectResource {DeploymentProcessId = "deploymentprocesses-1"}; project.Links.Add("Variables", "variablesets-1"); octoRepo.Setup(o => o.Projects.FindByName("Octopus")).Returns(project); octoRepo.Setup(o => o.Projects.FindByName("Gibberish")).Returns((ProjectResource) null); octoRepo.Setup(o => o.VariableSets.Get("variablesets-1")).Returns(_variableSet); var process = new DeploymentProcessResource(); process.Steps.Add(new DeploymentStepResource {Name = "Website", Id = "Step-1"}); octoRepo.Setup(o => o.DeploymentProcesses.Get("deploymentprocesses-1")).Returns(process); var envs = new List<EnvironmentResource> { new EnvironmentResource {Id = "Environments-1", Name = "DEV"} }; octoRepo.Setup(o => o.Environments.FindByNames(new[] {"DEV"})).Returns(envs); var machines = new List<MachineResource> { new MachineResource {Id = "Machines-1", Name = "web-01"} }; octoRepo.Setup(o => o.Machines.FindByNames(new[] { "web-01" })).Returns(machines); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(AddLibraryVariable)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); _variableSet.Variables.Clear(); var lib = new LibraryVariableSetResource { Name = "Octopus" }; var libs = new List<LibraryVariableSetResource> {lib}; lib.Links.Add("Variables", "variablesets-1"); octoRepo.Setup(o => o.LibraryVariableSets.FindOne(It.IsAny<Func<LibraryVariableSetResource, bool>>())) .Returns( (Func<LibraryVariableSetResource, bool> f) => (from l in libs where f(l) select l).FirstOrDefault()); octoRepo.Setup(o => o.Projects.FindByName("Gibberish")).Returns((ProjectResource)null); octoRepo.Setup(o => o.VariableSets.Get("variablesets-1")).Returns(_variableSet); var process = new DeploymentProcessResource(); process.Steps.Add(new DeploymentStepResource { Name = "Website", Id = "Step-1" }); octoRepo.Setup(o => o.DeploymentProcesses.Get("deploymentprocesses-1")).Returns(process); var envs = new List<EnvironmentResource> { new EnvironmentResource {Id = "Environments-1", Name = "DEV"} }; octoRepo.Setup(o => o.Environments.FindByNames(new[] { "DEV" })).Returns(envs); var machines = new List<MachineResource> { new MachineResource {Id = "Machines-1", Name = "web-01"} }; octoRepo.Setup(o => o.Machines.FindByNames(new[] { "web-01" })).Returns(machines); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof (RemoveVariableSet)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create some library variable sets _sets.Clear(); _sets.Add(new LibraryVariableSetResource {Id = "LibraryVariableSets-1", Name = "ConnectionStrings"}); _sets.Add(_set); _sets.Add(new LibraryVariableSetResource {Id = "LibraryVariableSets-3", Name = "Service Endpoints"}); octoRepo.Setup(o => o.LibraryVariableSets.Delete(It.IsAny<LibraryVariableSetResource>())).Returns( delegate(LibraryVariableSetResource set) { if (_sets.Contains(set)) _sets.Remove(set); else throw new KeyNotFoundException("The given key was not present in the dictionary."); return new TaskResource(); } ); octoRepo.Setup(o => o.LibraryVariableSets.Get("LibraryVariableSets-2")).Returns(_set); octoRepo.Setup(o => o.LibraryVariableSets.Get(It.IsNotIn(new[] {"LibraryVariableSets-2"}))) .Throws(new OctopusResourceNotFoundException("Not Found")); // Allow the FindOne predicate to operate on the collection octoRepo.Setup(o => o.LibraryVariableSets.FindOne(It.IsAny<Func<LibraryVariableSetResource, bool>>())) .Returns( (Func<LibraryVariableSetResource, bool> f) => (from l in _sets where f(l) select l).FirstOrDefault()); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(GetVariableSet)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create a library variable set const string vsId = "/api/variables/variableset-LibraryVariableSets-1"; var libraryResources = new List<LibraryVariableSetResource> { new LibraryVariableSetResource {Id = "LibraryVariableSets-1", Name = "Octopus"}, new LibraryVariableSetResource {Id = "LibraryVariableSets-2", Name = "Deploy"}, new LibraryVariableSetResource {Id = "LibraryVariableSets-3", Name = "Automation"} }; octoRepo.Setup(o => o.LibraryVariableSets.FindAll()).Returns(libraryResources); // Create a variableset var variableRepo = new Mock<IVariableSetRepository>(); var vsResource = new VariableSetResource { Variables = new List<VariableResource> { new VariableResource {Name = "Octopus"}, new VariableResource {Name = "Deploy"}, new VariableResource {Name = "Automation"}, } }; variableRepo.Setup(v => v.Get(vsId)).Returns(vsResource); octoRepo.Setup(o => o.VariableSets).Returns(variableRepo.Object); }
public void ExecuteScript(ScriptConfigElement e) { using (_instance = PowerShell.Create()) { _instance.AddScript(File.ReadAllText(e.PathToScript)); PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += outputCollection_DataAdded; _instance.Streams.Progress.DataAdded += Progress_DataAdded; _instance.Streams.Error.DataAdded += Error_DataAdded; _instance.Streams.Verbose.DataAdded += Verbose_DataAdded; _instance.Streams.Debug.DataAdded += Debug_DataAdded; _instance.Streams.Warning.DataAdded += Warning_DataAdded; IAsyncResult result = _instance.BeginInvoke<PSObject, PSObject>(null, outputCollection); while (result.IsCompleted == false) { Thread.Sleep(500); } foreach (PSObject o in outputCollection) { Console.WriteLine(o.GetType()); Console.WriteLine(o); } } }
/// <summary> /// Called to start the COM handler. /// </summary> /// <param name="data">Data string passed in from Task Scheduler action.</param> public override void Start(string data) { psInstance = PowerShell.Create(); psInstance.AddScript(data); result = psInstance.BeginInvoke(); psInstance.InvocationStateChanged += PowerShellInstance_InvocationStateChanged; }
protected void PrintPSCommand(PowerShell powershell) { StringBuilder command = new StringBuilder(); DateTime currentTime = DateTime.UtcNow; command.Append("[" + currentTime.ToShortDateString() + " " + currentTime.ToLongTimeString() + "] "); for (int i = 0; i < powershell.Commands.Commands.Count; i++) { command.Append(powershell.Commands.Commands[i].CommandText + " "); for (int j = 0; j < powershell.Commands.Commands[i].Parameters.Count; j++) { command.Append("-" + powershell.Commands.Commands[i].Parameters[j].Name + " "); var value = powershell.Commands.Commands[i].Parameters[j].Value; if (value != null) { command.Append("\"" + value.ToString() + "\" "); } command.Append("\n"); } } Console.WriteLine(command); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(AddProject)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create a project group var groupResource = new ProjectGroupResource {Name = "Octopus", Id = "projectgroups-1"}; octoRepo.Setup(o => o.ProjectGroups.FindByName("Octopus")).Returns(groupResource); octoRepo.Setup(o => o.ProjectGroups.Get(It.IsIn(new[] { "projectgroups-1" }))) .Returns(groupResource); octoRepo.Setup(o => o.ProjectGroups.Get(It.IsNotIn(new[] { "projectgroups-1" }))) .Throws(new OctopusResourceNotFoundException("Not Found")); _projects.Clear(); var repo = new Mock<IProjectRepository>(); repo.Setup(e => e.Create(It.IsAny<ProjectResource>())) .Returns(delegate(ProjectResource p) { _projects.Add(p); return p; }); octoRepo.Setup(o => o.Projects).Returns(repo.Object); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof (GetStep)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); const string deploymentProcessId = "deploymentprocess-projects-1"; // Create a project var projectResources = new List<ProjectResource> { new ProjectResource {Name = "Octopus", DeploymentProcessId = deploymentProcessId, Id = "projects-1"} }; octoRepo.Setup(o => o.Projects.FindByNames(new[] {"Octopus"})).Returns(projectResources); octoRepo.Setup(o => o.Projects.FindByNames(new[] {"Gibberish"})).Returns(new List<ProjectResource>()); octoRepo.Setup(o => o.Projects.Get("projects-1")).Returns(projectResources[0]); octoRepo.Setup(o => o.Projects.Get("Gibberish")).Throws(new OctopusResourceNotFoundException("Not Found")); var process = new DeploymentProcessResource(); //{ // Id = "deploymentprocess-projects-1" //}; process.Steps.Add(new DeploymentStepResource { Name = "Test Step" }); process.Steps.Add(new DeploymentStepResource { Name = "Test Step 2" }); octoRepo.Setup(o => o.DeploymentProcesses.Get(It.IsIn(new[] {deploymentProcessId}))) .Returns(process); octoRepo.Setup(o => o.DeploymentProcesses.Get(It.IsNotIn(new[] {deploymentProcessId}))) .Throws(new OctopusResourceNotFoundException("Not Found")); }
internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, System.Management.Automation.RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection<object> powershellInput) { this.localPowerShell = powershell; this.clientPowerShellId = clientPowerShellId; this.clientRunspacePoolId = clientRunspacePoolId; this.remoteStreamOptions = streamOptions; this.apartmentState = apartmentState; this.noInput = noInput; this.addToHistory = addToHistory; this.eventSubscriber = eventSubscriber; this.powershellInput = powershellInput; this.input = new PSDataCollection<object>(); this.inputEnumerator = this.input.GetEnumerator(); this.input.ReleaseOnEnumeration = true; this.dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, this.remoteStreamOptions, null); this.remoteHost = this.dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); this.dsHandler.InputEndReceived += new EventHandler(this.HandleInputEndReceived); this.dsHandler.InputReceived += new EventHandler<RemoteDataEventArgs<object>>(this.HandleInputReceived); this.dsHandler.StopPowerShellReceived += new EventHandler(this.HandleStopReceived); this.dsHandler.HostResponseReceived += new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(this.HandleHostResponseReceived); this.dsHandler.OnSessionConnected += new EventHandler(this.HandleSessionConnected); if (rsToUse == null) { throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", "NestedPipelineMissingRunspace", new object[0]); } this.localPowerShell.Runspace = rsToUse; eventSubscriber.SubscribeEvents(this); this.stateOfSteppablePipeline = PSInvocationState.NotStarted; }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(RemoveProjectGroup)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create some library variable sets _groups.Clear(); _groups.Add(new ProjectGroupResource { Id = "ProjectGroups-1", Name = "Octopus" }); _groups.Add(_group); _groups.Add(new ProjectGroupResource { Id = "ProjectGroups-3", Name = "Automation" }); octoRepo.Setup(o => o.ProjectGroups.Delete(It.IsAny<ProjectGroupResource>())).Returns( delegate(ProjectGroupResource set) { if (_groups.Contains(set)) _groups.Remove(set); else throw new KeyNotFoundException("The given key was not present in the dictionary."); return new TaskResource(); } ); octoRepo.Setup(o => o.ProjectGroups.Get("ProjectGroups-2")).Returns(_group); octoRepo.Setup(o => o.ProjectGroups.Get(It.IsNotIn(new[] { "ProjectGroups-2" }))) .Throws(new OctopusResourceNotFoundException("Not Found")); octoRepo.Setup(o => o.ProjectGroups.FindByName("Test")).Returns(_group); octoRepo.Setup(o => o.ProjectGroups.FindByName("Gibberish")).Returns((ProjectGroupResource)null); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(GetDeployment)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create a project var projectResource = new ProjectResource {Name = "Octopus"}; octoRepo.Setup(o => o.Projects.FindByName("Octopus")).Returns(projectResource); octoRepo.Setup(o => o.Projects.FindByName("Gibberish")).Returns((ProjectResource) null); // Create a Release var release = new ReleaseResource { Id = "Releases-1", Links = new LinkCollection()}; release.Links.Add("Deployments", "/api/releases/releases-1/deployments"); octoRepo.Setup(o => o.Projects.GetReleaseByVersion(projectResource, "1.0.0")).Returns(release); octoRepo.Setup(o => o.Projects.GetReleaseByVersion(projectResource, "Gibberish")).Returns((ReleaseResource) null); // Create Deployments var deployments = new ResourceCollection<DeploymentResource>(new List<DeploymentResource> { new DeploymentResource {Id = "deployments-1"} }, new LinkCollection()); octoRepo.Setup(o => o.Releases.GetDeployments(release, 0)).Returns(deployments); octoRepo.Setup(o => o.Releases.Get("Releases-1")).Returns(release); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof (GetProjectGroup)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create some project groups var groupRepo = new Mock<IProjectGroupRepository>(); var groupResources = new List<ProjectGroupResource> { new ProjectGroupResource {Name = "Octopus", Id = "projectgroups-1"}, new ProjectGroupResource {Name = "Deploy", Id = "projectgroups-2"} }; groupRepo.Setup(p => p.FindAll()).Returns(groupResources); groupRepo.Setup(p => p.FindByNames(It.IsAny<string[]>())).Returns( (string[] names) => (from n in names from g in groupResources where g.Name.Equals(n, StringComparison.InvariantCultureIgnoreCase) select g).ToList()); groupRepo.Setup(p => p.Get(It.IsAny<string>())).Returns(CreateGet(groupResources)); octoRepo.Setup(o => o.ProjectGroups).Returns(groupRepo.Object); }
internal CompletionExecutionHelper(PowerShell powershell) { if (powershell == null) { throw PSTraceSource.NewArgumentNullException("powershell"); } this.CurrentPowerShell = powershell; }
private IRSPDriverInvoke _psDriverInvoker; // Handles nested invocation of PS drivers. #endregion Private Members #region Constructors #if !CORECLR /// <summary> /// Default constructor for creating ServerPowerShellDrivers /// </summary> /// <param name="powershell">decoded powershell object</param> /// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes</param> /// <param name="noInput">whether there is input for this powershell</param> /// <param name="clientPowerShellId">the client powershell id</param> /// <param name="clientRunspacePoolId">the client runspacepool id</param> /// <param name="runspacePoolDriver">runspace pool driver /// which is creating this powershell driver</param> /// <param name="apartmentState">apartment state for this powershell</param> /// <param name="hostInfo">host info using which the host for /// this powershell will be constructed</param> /// <param name="streamOptions">serialization options for the streams in this powershell</param> /// <param name="addToHistory"> /// true if the command is to be added to history list of the runspace. false, otherwise. /// </param> /// <param name="rsToUse"> /// If not null, this Runspace will be used to invoke Powershell. /// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used. /// </param> internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse) : this(powershell, extraPowerShell, noInput, clientPowerShellId, clientRunspacePoolId, runspacePoolDriver, apartmentState, hostInfo, streamOptions, addToHistory, rsToUse, null) { }
public AsyncJob(ScriptBlock Script) : base(Script.ToString()) { this.Pipeline = PSRunspace.Instance.NewPipeline(); this.Pipeline.AddCommand(Script.ToString()); this.Pipeline.InvocationStateChanged += Pipeline_InvocationStateChanged; this.PSJobTypeName = "RunspaceJob"; this.Name = string.Format("Async{0}", this.Id); }
public void SetupPowerShellEnvironment(PowerShell powerShell, string credentials) { powerShell.RemoveCredentials(); string credentialFile = Path.Combine(this.downloadDirectoryPath, credentials); Assert.IsTrue(File.Exists(credentialFile), string.Format("Did not download file {0}", credentialFile)); powerShell.ImportCredentials(credentialFile); foreach (string key in this.environment.Keys) powerShell.AddEnvironmentVariable(key, environment[key]); foreach (string key in this.PowerShellVariables.Keys) powerShell.SetVariable(key, PowerShellVariables[key]); }
/// <summary> /// Creates the $credential object in the given <paramref name="powershell"/> instance with /// user name "testuser" and password "testpass". /// </summary> /// <param name="powershell">An instance of the <see cref="PowerShell"/> object.</param> public static void CreateTestCredential(PowerShell powershell) { // Create the test credential powershell.InvokeBatchScript( @"$user = ""testuser""", @"$pass = ""testp@ss1"" | ConvertTo-SecureString -asPlainText -Force", @"$credential = New-Object System.Management.Automation.PSCredential($user, $pass)"); Assert.IsTrue(powershell.Streams.Error.Count == 0); }
public MsPowerShellHost(string[] modules) { InitialSessionState initial = InitialSessionState.CreateDefault(); initial.ImportPSModule(modules); _space = RunspaceFactory.CreateRunspace(initial); _space.Open(); _ps = PowerShell.Create(); _ps.Runspace = _space; Init(); }
/// <summary> /// This is the primary method for executing powershell scripts /// </summary> /// <param name="script"></param> /// <param name="args"></param>(optional) /// <returns>ICollection<PSObject></returns> public ICollection<PSObject> executeScript(string script, IDictionary<string, object> args = null) { try { // create runspace if it is null if (_runspace == null) { _runspace = createRunspace(); } // The PowerShell class implements a Factory Pattern, offering a Create() method that returns a new PowerShell object _ps = PowerShell.Create(); // assign the runspace to the Powershell object _ps.Runspace = _runspace; // create a Command object, initializing it with the script path Command psCommand = new Command(script); // if the args Dictionary is not null, add them to the Command.Parameters collection if (args != null) { foreach (var arg in args) { psCommand.Parameters.Add(arg.Key, arg.Value); } } // add the psCommands object to the Commands property of our PowerShell object _ps.Commands.Commands.Add(psCommand); // Invoke PowerShell asynchronously var asyncResult = _ps.BeginInvoke(); // Could perform other tasks here while waiting for script to complete, if needed // this is analogous to the "await" keyword in an async method asyncResult.AsyncWaitHandle.WaitOne(); // get the result from PowerShell execution var result = _ps.EndInvoke(asyncResult); // release the resources used by the WaitHandle asyncResult.AsyncWaitHandle.Close(); // return the collection of PSObjects return result; } catch (Exception ex) { Debug.WriteLine(ex); return null; } }
// empty constructor? private PowerShellInstance() { // set output to blank string output = ""; // instansiate powershell instance powerShell = PowerShell.Create(); // instantiate our stringbuilder stringBuilder = new StringBuilder(); }
public ExchPowershell() { string uri = string.Format("https://{0}/powershell", ServiceSettings.ExchangeServer); this._connection = GetConnection(uri, ServiceSettings.Username, ServiceSettings.Password, ServiceSettings.ExchangeConnection == "Kerberos" ? true : false); _runspace = RunspaceFactory.CreateRunspace(_connection); _runspace.Open(); _powershell = PowerShell.Create(); _powershell.Runspace = _runspace; }
public void Init() { _executor = new PesterTestExecutor(); _runContext = new Mock<IRunContext>(); _runspace = RunspaceFactory.CreateRunspace(new TestAdapterHost()); _runspace.Open(); _powerShell = PowerShell.Create(); _powerShell.Runspace = _runspace; }
public PowershellAdminModuleFixture() { _powerShell = PowerShell.Create(); _powerShell.AddCommand("Import-Module").AddParameter("Name", typeof(CreateScope).Assembly.Location); _database = Guid.NewGuid().ToString("N"); var client = new MongoClient("mongodb://localhost"); _server = client.GetServer(); var settings = StoreSettings.DefaultSettings(); settings.Database = _database; _factory = new Factory(new ServiceFactory(null, settings), new AdminServiceRegistry()); }
public void SetupTest() { powershell = PowerShell.Create(); MockHttpServer.SetupCertificates(); UnitTestHelper.SetupUnitTestSubscription(powershell); serverName = SqlDatabaseTestSettings.Instance.ServerName; powershell.Runspace.SessionStateProxy.SetVariable("serverName", serverName); }
/// <summary> /// Constructor which creates a client remote powershell /// </summary> /// <param name="shell">powershell instance </param> /// <param name="runspacePool">The runspace pool associated with /// this shell</param> internal ClientRemotePowerShell(PowerShell shell, RemoteRunspacePoolInternal runspacePool) { this.shell = shell; clientRunspacePoolId = runspacePool.InstanceId; this.runspacePool = runspacePool; // retrieve the computer name from the runspacepool // information so that it can be used in adding // warning to host messages computerName = runspacePool.ConnectionInfo.ComputerName; }
internal ServerPowerShellDataStructureHandler(Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions, AbstractServerTransportManager transportManager, PowerShell localPowerShell) { this.clientPowerShellId = instanceId; this.clientRunspacePoolId = runspacePoolId; this.transportManager = transportManager; this.streamSerializationOptions = remoteStreamOptions; transportManager.Closing += new EventHandler(this.HandleTransportClosing); if (localPowerShell != null) { localPowerShell.RunspaceAssigned += new EventHandler<PSEventArgs<Runspace>>(this.LocalPowerShell_RunspaceAssigned); } }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(UpdateVariable)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); var variable = new VariableResource { Id = "variables-1", Name = "Test", Value = "Test Value", IsSensitive = false }; variable.Scope.Add(ScopeField.Action, "actions-1"); variable.Scope.Add(ScopeField.Environment, "environments-1"); variable.Scope.Add(ScopeField.Role, "DB"); _variableSet.Variables.Add(variable); var project = new ProjectResource { DeploymentProcessId = "deploymentprocesses-1" }; project.Links.Add("Variables", "variablesets-1"); octoRepo.Setup(o => o.Projects.FindByName("Octopus")).Returns(project); octoRepo.Setup(o => o.Projects.FindByName("Gibberish")).Returns((ProjectResource)null); octoRepo.Setup(o => o.VariableSets.Get("variablesets-1")).Returns(_variableSet); var process = new DeploymentProcessResource(); process.Steps.Add(new DeploymentStepResource { Name = "Website", Id = "Step-1" }); octoRepo.Setup(o => o.DeploymentProcesses.Get("deploymentprocesses-1")).Returns(process); var envs = new List<EnvironmentResource> { new EnvironmentResource {Id = "environments-1", Name = "DEV"}, new EnvironmentResource {Id = "environments-2", Name = "TEST"} }; octoRepo.Setup(o => o.Environments.FindByNames(It.IsAny<string[]>())) .Returns((string[] names) => (from n in names from e in envs where e.Name.Equals(n, StringComparison.InvariantCultureIgnoreCase) select e).ToList()); var machines = new List<MachineResource> { new MachineResource {Id = "machines-1", Name = "db-01"}, new MachineResource {Id = "machines-2", Name = "web-01"} }; octoRepo.Setup(o => o.Machines.FindByNames(It.IsAny<string[]>())).Returns( (string[] names) => (from n in names from m in machines where m.Name.Equals(n, StringComparison.InvariantCultureIgnoreCase) select m).ToList()); }
public virtual void TestSetup() { powershell = PowerShell.Create(); foreach (string moduleName in modules) { powershell.AddScript(string.Format("Import-Module \"{0}\"", Testing.GetTestResourcePath(moduleName))); } powershell.AddScript("$VerbosePreference='Continue'"); powershell.AddScript("$DebugPreference='Continue'"); powershell.AddScript("$ErrorActionPreference='Stop'"); }
protected void SetWorkingDirectory(PowerShell powerShell, string folder) { powerShell.Runspace.SessionStateProxy.Path.SetLocation(folder); }
/// <summary> /// 원격파일 복사 /// </summary> private void ExPs_CopyShape(string path, string destination) { // Username and Password for the remote machine. var userName = User; string pw = PW; // Creates a secure string for the password SecureString securePassword = new SecureString(); foreach (char c in pw) { securePassword.AppendChar(c); } securePassword.MakeReadOnly(); // Creates a PSCredential object PSCredential creds = new PSCredential(userName, securePassword); // Creates the runspace for PowerShell Runspace runspace = RunspaceFactory.CreateRunspace(); // Create the PSSession connection to the remote machine. //ComputerName string computerName = IP; PowerShell powershell = PowerShell.Create(); PSCommand command = new PSCommand(); command.AddCommand("New-PSSession"); command.AddParameter("ComputerName", computerName); command.AddParameter("Credential", creds); powershell.Commands = command; runspace.Open(); powershell.Runspace = runspace; Collection <PSObject> result = powershell.Invoke(); // Takes the PSSession object and places it into a PowerShell variable powershell = PowerShell.Create(); command = new PSCommand(); command.AddCommand("Set-Variable"); command.AddParameter("Name", "session"); command.AddParameter("Value", result[0]); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); // Calls the Copy-Item cmdlet as a script and passes the PSSession, Path and destination parameters to it powershell = PowerShell.Create(); command = new PSCommand(); command.AddScript("Copy-Item -Path " + path + " -Destination " + destination + " -ToSession $session"); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); // 세션종료 powershell = PowerShell.Create(); powershell.Runspace = runspace; powershell.AddScript("Remove-PSSession $session"); powershell.Invoke(); }
/// <summary> /// Wraps command execution into system process call. /// </summary> /// <returns></returns> /// <exception cref="Exception"></exception> public RepeatStatus Execute(StepContribution contribution, ChunkContext chunkContext) { if (Logger.IsTraceEnabled) { Logger.Trace("*** Executing PowerShell Script File: {0}", ScriptResource.GetFullPath()); } //=> PowerShell will throw an error if we do not Suppress ambient transaction... // see https://msdn.microsoft.com/en-us/library/system.transactions.transaction.current(v=vs.110).aspx#NotExistJustToMakeTheAElementVisible using (var transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) { /* //=> Runspace configuration information includes the assemblies, commands, format and type files, * // providers, and scripts that are available within the runspace. * RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();*/ //Creates a single runspace that uses the default host and runspace configuration using (Runspace runSpace = RunspaceFactory.CreateRunspace()) { //=> When this runspace is opened, the default host and runspace configuration // that are defined by Windows PowerShell will be used. runSpace.Open(); //=> Set Variables so they are available to user script... if (Variables != null && Variables.Any()) { foreach (KeyValuePair <string, object> variable in Variables) { runSpace.SessionStateProxy.SetVariable(variable.Key, variable.Value); } } //=> this is exit status variables to be tested on exit from power shell script... // it is defined in PwerShell global scope...and must be set by scipt writer on exit... runSpace.SessionStateProxy.SetVariable("ScriptExitStatus", _scriptExitStatus); //=> Allows the execution of commands from a CLR //RunspaceInvoke scriptInvoker = new RunspaceInvoke(runSpace); //scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); using (PowerShell psInstance = PowerShell.Create()) { try { // prepare a new collection to store output stream objects PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>(); outputCollection.DataAdded += AllStreams_DataAdded; psInstance.Streams.Error.DataAdded += AllStreams_DataAdded; psInstance.Streams.Verbose.DataAdded += AllStreams_DataAdded; psInstance.Streams.Warning.DataAdded += AllStreams_DataAdded; psInstance.Streams.Debug.DataAdded += AllStreams_DataAdded; psInstance.Runspace = runSpace; //=> This tasklet should be in the same dll as ExitStatus, i.e. Summer.Batch.Core.dll // we need to get the path to loaded Summer.Batch.Core.dll so we can load it in PowerShell var assemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location; //=> need to load Summer.Batch.Core into runspace so we can reference ExitStatus psInstance.AddScript("[System.Reflection.Assembly]::LoadFrom(\"" + assemblyLocation + "\")").AddStatement(); //=> add user command and its parameters... psInstance.AddCommand(ScriptResource.GetFullPath()); if (Parameters != null && Parameters.Any()) { foreach (KeyValuePair <string, object> variable in Parameters) { psInstance.AddParameter(variable.Key, variable.Value); } } //=> Invoke Asynchronously... IAsyncResult asyncResult = psInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection); // do something else until execution has completed. long t0 = DateTime.Now.Ticks; while (!asyncResult.IsCompleted) { //=> take a nap and let script do its job... Thread.Sleep(new TimeSpan(_checkInterval)); //=> to check if job was told to stop... CheckStoppingState(chunkContext); //=> lets make sure we did not exceed alloted time... long timeFromT0 = (long)(new TimeSpan(DateTime.Now.Ticks - t0)).TotalMilliseconds; if (timeFromT0 > _timeout) { //=> Stop PowerShell... psInstance.Stop(); //=> behave based on TimeoutBehaviorOption if (_timeoutBehavior.Equals(TimeoutBehaviorOption.SetExitStatusToFailed)) { contribution.ExitStatus = ExitStatus.Failed; break; } else if (_timeoutBehavior.Equals(TimeoutBehaviorOption.ThrowException)) { //=> lets dump what we got before throwing an error... LogStreams(); throw new FatalStepExecutionException("Execution of PowerShell script exceeded allotted time.", null); } } else if (_execution.TerminateOnly) { //=> Stop PowerShell... psInstance.Stop(); //=> lets dump what we got before throwing an error... LogStreams(); throw new JobInterruptedException( string.Format("Job interrupted while executing PowerShell script '{0}'", ScriptResource.GetFilename())); } else if (_stopped) { psInstance.Stop(); contribution.ExitStatus = ExitStatus.Stopped; break; } } // end while scope //=> Wait to the end of execution... //psInstance.EndInvoke(_asyncResult); //NOTE: asyncResult.IsCompleted will be set to true if PowerShell.Stop was called or // PowerShell completed its work //=> if status not yet set (script completed)...handle completion... if (contribution.ExitStatus.IsRunning()) { //=> script needs to set exit code...if exit code not set we assume 0 var lastExitCode = (int)runSpace.SessionStateProxy.PSVariable.GetValue("LastExitCode", 0); _scriptExitStatus = runSpace.SessionStateProxy.GetVariable("ScriptExitStatus") as ExitStatus; //=> set exit status... if (_scriptExitStatus != null && !_scriptExitStatus.IsRunning()) { if (Logger.IsTraceEnabled) { Logger.Trace("***> ScriptExitStatus returned by script => {0}", _scriptExitStatus); } contribution.ExitStatus = _scriptExitStatus; } else //=> let user decide on ExitStatus { if (Logger.IsTraceEnabled) { if (_scriptExitStatus == null) { Logger.Trace("***> ScriptExitStatus is null. Using PowerShellExitCodeMapper to determine ExitStatus."); } else if (_scriptExitStatus.IsRunning()) { Logger.Trace("***> ScriptExitStatus is EXECUTING or UNKNOWN. Using PowerShellExitCodeMapper to determine ExitStatus."); } } if (PowerShellExitCodeMapper != null) { //=> determine exit status using User Provided PowerShellExitCodeMapper contribution.ExitStatus = PowerShellExitCodeMapper.GetExitStatus(lastExitCode); } else //at this point we are not able to determine exit status, user needs to fix this... { //=> lets dump what we got before throwing an error... LogStreams(); throw new FatalStepExecutionException( "PowerShellTasklet is not able to determine ExitStatus. ScriptExitStatus is null or (is EXECUTING or UNKNOWN) and " + "PowerShellExitCodeMapper is NOT defined. Please set $global:ScriptExitStatus or define PowerShellExitCodeMapper.", null); } } } if (Logger.IsInfoEnabled) { Logger.Info("PowerShell execution exit status [{0}]", contribution.ExitStatus); } //=> output captured stream data to Log... LogStreams(); } catch (RuntimeException ex) { Logger.Error(ex.Message); throw; } } // end PowerShell Scope //=> close Runspace... runSpace.Close(); //=> we are done... return(RepeatStatus.Finished); } // end of Runspace Scope } // end of TransactionScope }
private void AnalyzeMarkdownHelp( IEnumerable <string> scopes, string directory, ReportLogger <HelpIssue> helpLogger, List <string> processedHelpFiles, string savedDirectory) { var helpFolder = Directory.EnumerateDirectories(directory, "help").FirstOrDefault(); var service = Path.GetFileName(directory); if (helpFolder == null) { helpLogger.LogRecord(new HelpIssue() { Assembly = service, Description = string.Format("{0} has no matching help folder", service), Severity = 0, Remediation = string.Format("Make sure a help folder for {0} exists and it is " + "being copied to the output directory.", service), Target = service, HelpFile = service + "/folder", ProblemId = MissingHelpFile }); return; } var helpFiles = Directory.EnumerateFiles(helpFolder, "*.md").Select(Path.GetFileNameWithoutExtension).ToList(); if (!helpFiles.Any()) { return; } Directory.SetCurrentDirectory(directory); var manifestFiles = Directory.EnumerateFiles(directory, "*.psd1").ToList(); if (manifestFiles.Count > 1) { manifestFiles = manifestFiles.Where(f => Path.GetFileName(f).IndexOf(service) >= 0).ToList(); } if (manifestFiles.Count == 0) { return; } var psd1 = manifestFiles.FirstOrDefault(); var parentDirectory = Directory.GetParent(psd1).FullName; var psd1FileName = Path.GetFileName(psd1); var powershell = PowerShell.Create(); powershell.AddScript("Import-LocalizedData -BaseDirectory " + parentDirectory + " -FileName " + psd1FileName + " -BindingVariable ModuleMetadata; $ModuleMetadata.NestedModules; $ModuleMetadata.RequiredModules | % { $_[\"ModuleName\"] };"); var cmdletResult = powershell.Invoke(); var nestedModules = cmdletResult.Where(c => c.ToString().StartsWith(".")).Select(c => c.ToString().Substring(2)); var requiredModules = cmdletResult.Where(c => !c.ToString().StartsWith(".")).Select(c => c.ToString()).ToList(); if (nestedModules.Any()) { Directory.SetCurrentDirectory(directory); requiredModules = requiredModules.Join(scopes, module => 1, dir => 1, (module, dir) => Path.Combine(dir, module)) .Where(Directory.Exists) .ToList(); requiredModules.Add(directory); var allCmdlets = new List <CmdletMetadata>(); foreach (var nestedModule in nestedModules) { var assemblyFile = Directory.GetFiles(parentDirectory, nestedModule, SearchOption.AllDirectories).FirstOrDefault(); if (!File.Exists(assemblyFile)) { continue; } var assemblyFileName = Path.GetFileName(assemblyFile); helpLogger.Decorator.AddDecorator(h => { h.HelpFile = assemblyFileName; h.Assembly = assemblyFileName; }, "Cmdlet"); processedHelpFiles.Add(assemblyFileName); // TODO: Remove IfDef #if NETSTANDARD var proxy = new CmdletLoader(); #else var proxy = EnvironmentHelpers.CreateProxy <CmdletLoader>(directory, out _appDomain); #endif var module = proxy.GetModuleMetadata(assemblyFile, requiredModules); var cmdlets = module.Cmdlets; allCmdlets.AddRange(cmdlets); helpLogger.Decorator.Remove("Cmdlet"); // TODO: Remove IfDef code #if !NETSTANDARD AppDomain.Unload(_appDomain); #endif } ValidateHelpRecords(allCmdlets, helpFiles, helpLogger); } Directory.SetCurrentDirectory(savedDirectory); }
public void Execute(SetEventActionTrigger setEventActionTrigger, EventActionContext context) { var script = string.Empty; script = this.ScriptFile != string.Empty ? File.ReadAllText(this.ScriptFile) : this.Script; var powerShellScript = PowerShell.Create(); powerShellScript.AddScript(script); // foreach (var prop in MessageProperties) // { // powerShellScript.AddParameter(prop.Key, prop.Value); // } powerShellScript.AddParameter("DataContext", this.DataContext); powerShellScript.Invoke(); if (powerShellScript.HadErrors) { var sb = new StringBuilder(); foreach (var error in powerShellScript.Streams.Error) { sb.AppendLine(error.Exception.Message); } throw new Exception(sb.ToString()); } var outVar = powerShellScript.Runspace.SessionStateProxy.PSVariable.GetValue("DataContext"); if (outVar != null && outVar.ToString() != string.Empty) { try { var po = (PSObject)outVar; var logEntry = po.BaseObject as EventLogEntry; if (logEntry != null) { var ev = logEntry; this.DataContext = Encoding.UTF8.GetBytes(ev.Message); } else { this.DataContext = Encoding.UTF8.GetBytes(outVar.ToString()); } if (this.DataContext.Length != 0) { setEventActionTrigger(this, context); } } catch { // if multiple pso var results = (object[])outVar; foreach (var pos in results) { var po = (PSObject)pos; var logEntry = po.BaseObject as EventLogEntry; if (logEntry != null) { var ev = logEntry; this.DataContext = Encoding.UTF8.GetBytes(ev.Message); } else { this.DataContext = Encoding.UTF8.GetBytes(outVar.ToString()); } if (this.DataContext.Length != 0) { setEventActionTrigger(this, context); } } } } }
/// <summary> /// Создать пользователя в домене AD, подключившись к контроллеру по WinRM:Powershell /// </summary> /// <param name="user"></param> // /// <param name="server">Имя контроллера домена к которому нужно подключиться</param> /// <param name="creds"></param> /// <param name="path">Путь к OU</param> public static void AddUser(AdUser user, PSCredential creds, Splash splash) { if (splash != null) { splash.Status = "Генерим скрипт."; } string Script = $"import-module activedirectory;" + $"$sec_pass = ConvertTo-SecureString {user.Password} -AsPlainText -Force;" + $"New-ADUser -Name '{user.FullName}'" + $" -AccountPassword $sec_pass" + $" -DisplayName '{user.DisplayName}'" + $" -GivenName '{user.FirstName}'" + $" -Surname '{user.SurName}'" + $" -Path '{user.Domain.LoginOU}'" + $" -SamAccountName '{user.Login}'" + $" -UserPrincipalName '{user.UPN}'" + $" -enabled $true;"; Debug.WriteLine(Script); if (splash != null) { splash.Status = "Создаём ранспейс."; } WSManConnectionInfo connInfo = new WSManConnectionInfo(new Uri($"http://{user.Domain.DC}:5985"), "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", creds); Runspace runspace = RunspaceFactory.CreateRunspace(connInfo); PowerShell shell = PowerShell.Create(RunspaceMode.NewRunspace); if (splash != null) { splash.Status = $"Открываем ранспейс на сервере {user.Domain.DC}"; } runspace.Open(); shell.Runspace = runspace; if (splash != null) { splash.Status = $"Добавляем скрипт в пайплайн."; } shell.AddScript(Script); try { if (splash != null) { splash.Status = $"Выполняем скрипт."; } Collection <PSObject> result = shell.Invoke(); if (shell.HadErrors) { foreach (ErrorRecord errorRecord in shell.Streams.Error) { Debug.WriteLine(errorRecord.Exception); throw errorRecord.Exception; } } foreach (PSObject psObject in result) { Debug.WriteLine(psObject.ToString()); } } catch (Exception e) { Debug.WriteLine(e); //throw; } runspace.CloseAsync(); shell.Dispose(); }
public object ExecuteEndpoint(ExecutionContext context, Endpoint endpoint) { var script = endpoint.ScriptBlock.ToString(); var scriptBlockAst = endpoint.ScriptBlock.Ast as ScriptBlockAst; if (scriptBlockAst.ParamBlock == null && context.Parameters.Any()) { if (Log.IsDebugEnabled) { Log.Debug("Parameters--------------"); foreach (var variable in context.Parameters) { Log.Debug($"{variable.Key} = {variable.Value}"); } } var paramBlockBuilder = new StringBuilder(); paramBlockBuilder.Append("param("); foreach (var parameter in context.Parameters) { paramBlockBuilder.Append($"${parameter.Key},"); } paramBlockBuilder.Remove(paramBlockBuilder.Length - 1, 1); paramBlockBuilder.Append(")"); paramBlockBuilder.AppendLine(); script = paramBlockBuilder.ToString() + script; } Collection <PSObject> output; string json; using (var ps = PowerShell.Create()) { using (var runspaceRef = _runspace.GetRunspace()) { Runspace.DefaultRunspace = runspaceRef.Runspace; ps.Runspace = runspaceRef.Runspace; if (endpoint.Variables != null) { Log.Debug("Scope variables--------------"); SetVariables(ps.Runspace, endpoint.Variables); } if (context.Variables != null) { Log.Debug("Context variables--------------"); SetVariables(ps.Runspace, context.Variables); } SetVariable(ps.Runspace, "DashboardHub", _hubContext); SetVariable(ps.Runspace, "Cache", MemoryCache); SetVariable(ps.Runspace, "StateRequestService", _stateRequestService); SetVariable(ps.Runspace, "ConnectionId", context.ConnectionId); SetVariable(ps.Runspace, Constants.SessionId, context.SessionId); if (context.User != null) { SetVariable(ps.Runspace, "ClaimsPrinciple", context.User); } ps.AddStatement().AddScript(script); foreach (var parameter in context.Parameters) { ps.AddParameter(parameter.Key, parameter.Value); } try { output = ps.Invoke(); if (ps.HadErrors) { if (ps.Streams.Error.Any()) { var error = ps.Streams.Error[0].Exception.Message; Log.Warn($"Error executing endpoint script. {error}"); return(new { Error = new Error { Message = error } }); } } } catch (Exception ex) { Log.Warn(ex, "Error executing endpoint script."); return(new { Error = new Error { Message = ex.Message, Location = ex.StackTrace } }); } } } if (context.NoSerialization) { return(output.Select(m => m.BaseObject).ToArray()); } json = output.FirstOrDefault()?.BaseObject as string; if (json != null) { return(json); } if (!output.Where(m => m != null).Select(m => m.BaseObject).OfType <InputAction>().Any() && !output.Where(m => m != null).Select(m => m.BaseObject).OfType <Component>().Any()) { return(output.Where(m => m != null).Select(m => m.BaseObject)); } return(FindComponents(output)); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(UpdateLibraryVariable)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create some library variable sets _sets.Clear(); _sets.Add(new LibraryVariableSetResource { Id = "LibraryVariableSets-1", Name = "ConnectionStrings", VariableSetId = "variables-1" }); _sets.Add(new LibraryVariableSetResource { Id = "LibraryVariableSets-3", Name = "Service Endpoints", VariableSetId = "variables-3" }); var variable = new VariableResource { Id = "variables-1", Name = "Test", Value = "Test Value", IsSensitive = false }; variable.Scope.Add(ScopeField.Action, "actions-1"); variable.Scope.Add(ScopeField.Environment, "environments-1"); variable.Scope.Add(ScopeField.Role, "DB"); _variableSet.Variables.Add(variable); _sets[0].Links.Add("Variables", "variablesets-1"); octoRepo.Setup(o => o.LibraryVariableSets.FindOne(It.IsAny <Func <LibraryVariableSetResource, bool> >())) .Returns( (Func <LibraryVariableSetResource, bool> f) => (from l in _sets where f(l) select l).FirstOrDefault()); octoRepo.Setup(o => o.Projects.FindByName("Gibberish")).Returns((ProjectResource)null); octoRepo.Setup(o => o.VariableSets.Get("variablesets-1")).Returns(_variableSet); var process = new DeploymentProcessResource(); process.Steps.Add(new DeploymentStepResource { Name = "Website", Id = "Step-1" }); octoRepo.Setup(o => o.DeploymentProcesses.Get("deploymentprocesses-1")).Returns(process); var envs = new List <EnvironmentResource> { new EnvironmentResource { Id = "environments-1", Name = "DEV" }, new EnvironmentResource { Id = "environments-2", Name = "TEST" } }; octoRepo.Setup(o => o.Environments.FindByNames(It.IsAny <string[]>())) .Returns((string[] names) => (from n in names from e in envs where e.Name.Equals(n, StringComparison.InvariantCultureIgnoreCase) select e).ToList()); var machines = new List <MachineResource> { new MachineResource { Id = "machines-1", Name = "db-01" }, new MachineResource { Id = "machines-2", Name = "web-01" } }; octoRepo.Setup(o => o.Machines.FindByNames(It.IsAny <string[]>())).Returns( (string[] names) => (from n in names from m in machines where m.Name.Equals(n, StringComparison.InvariantCultureIgnoreCase) select m).ToList()); }
public void Analyze(IEnumerable <string> cmdletProbingDirs, Func <IEnumerable <string>, IEnumerable <string> > directoryFilter, Func <string, bool> cmdletFilter, IEnumerable <string> modulesToAnalyze) { var savedDirectory = Directory.GetCurrentDirectory(); var processedHelpFiles = new List <string>(); var issueLogger = Logger.CreateLogger <SignatureIssue>(signatureIssueReportLoggerName); List <string> probingDirectories = new List <string>(); if (directoryFilter != null) { cmdletProbingDirs = directoryFilter(cmdletProbingDirs); } foreach (var baseDirectory in cmdletProbingDirs.Where(s => !s.Contains("ServiceManagement") && !s.Contains("Stack") && Directory.Exists(Path.GetFullPath(s)))) { //Add current directory for probing probingDirectories.Add(baseDirectory); probingDirectories.AddRange(Directory.EnumerateDirectories(Path.GetFullPath(baseDirectory))); foreach (var directory in probingDirectories) { if (modulesToAnalyze != null && modulesToAnalyze.Any() && !modulesToAnalyze.Where(m => directory.EndsWith(m)).Any()) { continue; } var service = Path.GetFileName(directory); var manifestFiles = Directory.EnumerateFiles(directory, "*.psd1").ToList(); if (manifestFiles.Count > 1) { manifestFiles = manifestFiles.Where(f => Path.GetFileName(f).IndexOf(service) >= 0).ToList(); } if (!manifestFiles.Any()) { continue; } var psd1 = manifestFiles.FirstOrDefault(); var parentDirectory = Directory.GetParent(psd1).FullName; var psd1FileName = Path.GetFileName(psd1); IEnumerable <string> nestedModules = null; List <string> requiredModules = null; PowerShell powershell = PowerShell.Create(); powershell.AddScript("Import-LocalizedData -BaseDirectory " + parentDirectory + " -FileName " + psd1FileName + " -BindingVariable ModuleMetadata; $ModuleMetadata.NestedModules; $ModuleMetadata.RequiredModules | % { $_[\"ModuleName\"] };"); var cmdletResult = powershell.Invoke(); nestedModules = cmdletResult.Where(c => c.ToString().StartsWith(".")).Select(c => c.ToString().Substring(2)); requiredModules = cmdletResult.Where(c => !c.ToString().StartsWith(".")).Select(c => c.ToString()).ToList(); if (nestedModules.Any()) { Directory.SetCurrentDirectory(directory); requiredModules = requiredModules.Join(cmdletProbingDirs, module => 1, dir => 1, (module, dir) => Path.Combine(dir, module)) .Where(f => Directory.Exists(f)) .ToList(); requiredModules.Add(directory); foreach (var nestedModule in nestedModules) { var assemblyFile = Directory.GetFiles(parentDirectory, nestedModule, SearchOption.AllDirectories).FirstOrDefault(); if (File.Exists(assemblyFile)) { issueLogger.Decorator.AddDecorator(a => a.AssemblyFileName = assemblyFile, "AssemblyFileName"); processedHelpFiles.Add(assemblyFile); var proxy = #if !NETSTANDARD EnvironmentHelpers.CreateProxy <CmdletLoader>(directory, out _appDomain); #else new CmdletLoader(); #endif var module = proxy.GetModuleMetadata(assemblyFile, requiredModules); var cmdlets = module.Cmdlets; if (cmdletFilter != null) { cmdlets = cmdlets.Where <CmdletMetadata>((cmdlet) => cmdletFilter(cmdlet.Name)).ToList <CmdletMetadata>(); } foreach (var cmdlet in cmdlets) { Logger.WriteMessage("Processing cmdlet '{0}'", cmdlet.ClassName); string defaultRemediation = "Determine if the cmdlet should implement ShouldProcess and " + "if so determine if it should implement Force / ShouldContinue"; if (!cmdlet.SupportsShouldProcess && cmdlet.HasForceSwitch) { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 0, problemId: SignatureProblemId.ForceWithoutShouldProcessAttribute, description: string.Format("{0} Has -Force parameter but does not set the SupportsShouldProcess " + "property to true in the Cmdlet attribute.", cmdlet.Name), remediation: defaultRemediation); } if (!cmdlet.SupportsShouldProcess && cmdlet.ConfirmImpact != ConfirmImpact.Medium) { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 2, problemId: SignatureProblemId.ConfirmLeveleWithNoShouldProcess, description: string.Format("{0} Changes the ConfirmImpact but does not set the " + "SupportsShouldProcess property to true in the cmdlet attribute.", cmdlet.Name), remediation: defaultRemediation); } if (!cmdlet.SupportsShouldProcess && cmdlet.IsShouldProcessVerb) { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 1, problemId: SignatureProblemId.ActionIndicatesShouldProcess, description: string.Format( "{0} Does not support ShouldProcess but the cmdlet verb {1} indicates that it should.", cmdlet.Name, cmdlet.VerbName), remediation: defaultRemediation); } if (cmdlet.ConfirmImpact != ConfirmImpact.Medium) { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 2, problemId: SignatureProblemId.ConfirmLevelChange, description: string.Format("{0} changes the confirm impact. Please ensure that the " + "change in ConfirmImpact is justified", cmdlet.Name), remediation: "Verify that ConfirmImpact is changed appropriately by the cmdlet. " + "It is very rare for a cmdlet to change the ConfirmImpact."); } if (!cmdlet.IsApprovedVerb) { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 1, problemId: SignatureProblemId.CmdletWithUnapprovedVerb, description: string.Format( "{0} uses the verb '{1}', which is not on the list of approved " + "verbs for PowerShell commands. Use the cmdlet 'Get-Verb' to see " + "the full list of approved verbs and consider renaming the cmdlet.", cmdlet.Name, cmdlet.VerbName), remediation: "Consider renaming the cmdlet to use an approved verb for PowerShell."); } if (!cmdlet.HasSingularNoun) { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 1, problemId: SignatureProblemId.CmdletWithPluralNoun, description: string.Format( "{0} uses the noun '{1}', which does not follow the enforced " + "naming convention of using a singular noun for a cmdlet name.", cmdlet.Name, cmdlet.NounName), remediation: "Consider using a singular noun for the cmdlet name."); } if (!cmdlet.OutputTypes.Any()) { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 1, problemId: SignatureProblemId.CmdletWithNoOutputType, description: string.Format( "Cmdlet '{0}' has no defined output type.", cmdlet.Name), remediation: "Add an OutputType attribute that declares the type of the object(s) returned " + "by this cmdlet. If this cmdlet returns no output, please set the output " + "type to 'bool' and make sure to implement the 'PassThru' parameter."); } foreach (var parameter in cmdlet.GetParametersWithPluralNoun()) { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 1, problemId: SignatureProblemId.ParameterWithPluralNoun, description: string.Format( "Parameter {0} of cmdlet {1} does not follow the enforced " + "naming convention of using a singular noun for a parameter name.", parameter.Name, cmdlet.Name), remediation: "Consider using a singular noun for the parameter name."); } foreach (var parameterSet in cmdlet.ParameterSets) { if (parameterSet.Name.Contains(" ")) { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 1, problemId: SignatureProblemId.ParameterSetWithSpace, description: string.Format( "Parameter set '{0}' of cmdlet '{1}' contains a space, which " + "is discouraged for PowerShell parameter sets.", parameterSet.Name, cmdlet.Name), remediation: "Remove the space(s) in the parameter set name."); } if (parameterSet.Parameters.Any(p => p.Position >= 4)) { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 1, problemId: SignatureProblemId.ParameterWithOutOfRangePosition, description: string.Format( "Parameter set '{0}' of cmdlet '{1}' contains at least one parameter " + "with a position larger than four, which is discouraged.", parameterSet.Name, cmdlet.Name), remediation: "Limit the number of positional parameters in a single parameter set to " + "four or fewer."); } } if (cmdlet.ParameterSets.Count() > 2 && cmdlet.DefaultParameterSetName == "__AllParameterSets") { issueLogger.LogSignatureIssue( cmdlet: cmdlet, severity: 1, problemId: SignatureProblemId.MultipleParameterSetsWithNoDefault, description: string.Format( "Cmdlet '{0}' has multiple parameter sets, but no defined default parameter set.", cmdlet.Name), remediation: "Define a default parameter set in the cmdlet attribute."); } } #if !NETSTANDARD AppDomain.Unload(_appDomain); #endif issueLogger.Decorator.Remove("AssemblyFileName"); } } Directory.SetCurrentDirectory(savedDirectory); } } } }
public void SaveOnlyMarkedPropertiesInSpecifiedViews() { var initialSessionState = InitialSessionState.CreateDefault(); initialSessionState.Commands.Add( new SessionStateCmdletEntry( CmdletName, typeof(NewFormatPs1XmlCommand), null)); using (var runspace = RunspaceFactory.CreateRunspace(initialSessionState)) { runspace.Open(); using (var powershell = PowerShell.Create()) { powershell.Runspace = runspace; var cmdlet = new Command(CmdletName); powershell.Commands.AddCommand(cmdlet); cmdlet.Parameters.Add("ModulePath", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Dummy.psd1")); cmdlet.Parameters.Add("OnlyMarkedProperties"); cmdlet.Parameters.Add("OutputPath", AppDomain.CurrentDomain.BaseDirectory); var results = powershell.Invoke <string>(); var es = powershell.Streams.Error; Assert.True(es.Count == 0, string.Join("\n,", es)); Assert.True(results.Count > 0); var ws = powershell.Streams.Warning; Assert.True(ws.Count == 2); string filepath = null; try { filepath = results.First(); Assert.NotNull(filepath); Assert.True(File.Exists(filepath)); var xelement = XElement.Load(filepath); var config = xelement.Elements().ToList(); TestXmlMarked(config, // entrytype (1), prop-name or script-block (2), target (3), label (4), table-column-width (5), position (6), group-by-this-param (7) new List <Tuple <EntryType, string, View, string, uint?, uint?, bool> > { Tuple.Create <EntryType, string, View, string, uint?, uint?, bool>(EntryType.ScriptBlock, "$_.Foo", View.List, "PsDummyOutput1 Id", 0, null, false), Tuple.Create <EntryType, string, View, string, uint?, uint?, bool>(EntryType.PropertyName, "RequestId", View.Both, "RequestId", null, 1, false), Tuple.Create <EntryType, string, View, string, uint?, uint?, bool>(EntryType.PropertyName, "Name", View.Both, null, 16, null, false), Tuple.Create <EntryType, string, View, string, uint?, uint?, bool>(EntryType.PropertyName, "Type", View.Both, "PsDummyOutput1 Type", null, 3, false), Tuple.Create <EntryType, string, View, string, uint?, uint?, bool>(EntryType.ScriptBlock, "$_.PsDummyOutput2.Name", View.Both, "PsDummyOutput2 Name", null, null, true), Tuple.Create <EntryType, string, View, string, uint?, uint?, bool>(EntryType.ScriptBlock, "$_.PsDummyOutput2.Location", View.Both, "PsDummyOutput2 Location", null, 0, false), Tuple.Create <EntryType, string, View, string, uint?, uint?, bool>(EntryType.PropertyName, "StatusCode", View.None, null, null, null, false), Tuple.Create <EntryType, string, View, string, uint?, uint?, bool>(EntryType.ScriptBlock, "S_.Foo", View.List, null, null, null, false), }, $"{ExpectedAssemblyName}.Models.PsDummyOutput1"); TestXmlGroupBy(config, new List <Tuple <GroupBy, View> > { new Tuple <GroupBy, View> (new GroupBy { ScriptBlock = "$_.PsDummyOutput2.Name", Label = "PsDummyOutput2 Name" }, View.Both), }, $"{ExpectedAssemblyName}.Models.PsDummyOutput1"); } finally { if (filepath != null) { File.Delete(filepath); } } } } }
public static DscBreakpointCapability CheckForCapability( RunspaceDetails runspaceDetails, PowerShellContext powerShellContext, ILogger logger) { DscBreakpointCapability capability = null; // DSC support is enabled only for Windows PowerShell. if ((runspaceDetails.PowerShellVersion.Version.Major < 6) && (runspaceDetails.Context != RunspaceContext.DebuggedRunspace)) { using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = runspaceDetails.Runspace; // Attempt to import the updated DSC module powerShell.AddCommand("Import-Module"); powerShell.AddArgument(@"C:\Program Files\DesiredStateConfiguration\1.0.0.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psd1"); powerShell.AddParameter("PassThru"); powerShell.AddParameter("ErrorAction", "Ignore"); PSObject moduleInfo = null; try { moduleInfo = powerShell.Invoke().FirstOrDefault(); } catch (RuntimeException e) { logger.WriteException("Could not load the DSC module!", e); } if (moduleInfo != null) { logger.Write(LogLevel.Verbose, "Side-by-side DSC module found, gathering DSC resource paths..."); // The module was loaded, add the breakpoint capability capability = new DscBreakpointCapability(); runspaceDetails.AddCapability(capability); powerShell.Commands.Clear(); powerShell.AddScript("Write-Host \"Gathering DSC resource paths, this may take a while...\""); powerShell.Invoke(); // Get the list of DSC resource paths powerShell.Commands.Clear(); powerShell.AddCommand("Get-DscResource"); powerShell.AddCommand("Select-Object"); powerShell.AddParameter("ExpandProperty", "ParentPath"); Collection <PSObject> resourcePaths = null; try { resourcePaths = powerShell.Invoke(); } catch (CmdletInvocationException e) { logger.WriteException("Get-DscResource failed!", e); } if (resourcePaths != null) { capability.dscResourceRootPaths = resourcePaths .Select(o => (string)o.BaseObject) .ToArray(); logger.Write(LogLevel.Verbose, $"DSC resources found: {resourcePaths.Count}"); } else { logger.Write(LogLevel.Verbose, $"No DSC resources found."); } } else { logger.Write(LogLevel.Verbose, $"Side-by-side DSC module was not found."); } } } return(capability); }
public async Task <ExOResult> GetExoMailbox(bool invokeAsync = true) { var sw = System.Diagnostics.Stopwatch.StartNew(); long elapsedConnect = 0, elapsedCmds = 0, elapsedTotal = 0; // Stage #1 InitialSessionState iss = InitialSessionState.CreateDefault(); iss.ImportPSModule(new string[] { "ExchangeOnlineManagement" }); using var exchangeRunspace = RunspaceFactory.CreateRunspace(iss); exchangeRunspace.Open(); using (var pipeLine = exchangeRunspace.CreatePipeline()) { var connectCmd = new Command("Connect-ExchangeOnline"); connectCmd.Parameters.Add("AppId", AppId); connectCmd.Parameters.Add("Organization", Organization); connectCmd.Parameters.Add("Certificate", Certificate); pipeLine.Commands.Add(connectCmd); try { pipeLine.Invoke(); } catch (Exception e) { return(new ExOResult(e.ToString(), "", 0, 0, 0)); } elapsedConnect = sw.ElapsedMilliseconds; if (pipeLine.Error != null && pipeLine.Error.Count > 0) { throw new NotImplementedException(); // Error handing code below is not tested #pragma warning disable CS0162 // Unreachable code detected var errors = pipeLine.Error.ReadToEnd(); var errStringified = "!Errors! " + String.Join(" :: ", errors.Select(error => error.ToString()).ToList()); return(new ExOResult(errStringified, "", elapsedConnect, 0, 0)); #pragma warning restore CS0162 // Unreachable code detected } } // Stage #2 using var ps = PowerShell.Create(); ps.Runspace = exchangeRunspace; ps.Commands.AddCommand("Get-EXOMailBox").AddParameter("ResultSize", "unlimited"); List <PSObject> results = await ps.InvokeAsyncConditionally(invokeAsync); elapsedCmds = sw.ElapsedMilliseconds; var err = ps.StreamsErrorToString(); var result = ResultsToSimpleString(results); // https://docs.microsoft.com/en-us/powershell/module/exchange/disconnect-exchangeonline?view=exchange-ps ps.Commands.Clear(); ps.Commands.AddCommand("Disconnect-ExchangeOnline").AddParameter("Confirm", false); var disconnectResult = await ps.InvokeAsyncConditionally(invokeAsync); var disconnectErr = ps.StreamsErrorToString(); sw.Stop(); elapsedTotal = sw.ElapsedMilliseconds; return(new ExOResult(err, result, elapsedConnect, elapsedCmds, elapsedTotal)); }
public static void InvokeCommand(this PowerShell pwsh, PSCommand psCommand, PSInvocationSettings invocationSettings = null) { pwsh.Commands = psCommand; pwsh.InvokeAndClear(invocationSettings); }
private bool TryInvokeUserDefinedReadLine(out string input, bool useUserDefinedCustomReadLine) { // We're using GetCommands instead of GetCommand so we don't auto-load a module should the command exist, but isn't loaded. // The idea is that if someone hasn't defined the command (say because they started -noprofile), we shouldn't auto-load // this function. input = null; if (!useUserDefinedCustomReadLine) { return(false); } // If we need to look for user defined custom readline command, then we need to wait for Runspace to be created. // [danthom] TODO: What to do about this? //var runspace = this.parent.LocalRunspace; //if (runspace != null // && runspace.Engine.Context.EngineIntrinsics.InvokeCommand.GetCommands(CustomReadlineCommand, CommandTypes.All, nameIsPattern: false).Any()) //{ // PowerShell ps; // if (runspace.ExecutionContext.EngineHostInterface.NestedPromptCount > 0) // { // ps = PowerShell.Create(RunspaceMode.CurrentRunspace); // } // else // { // ps = PowerShell.Create(); // ps.Runspace = runspace; // } // try // { // var result = ps.AddCommand(CustomReadlineCommand).Invoke(); // if (result.Count == 1) // { // input = PSObject.Base(result[0]) as string; // return true; // } // } // catch (Exception e) // { // // TODO: what // //CommandProcessorBase.CheckForSevereException(e); // Util.FailFast( "Exception in TryInvokeUserDefinedReadLine.", e ); // } //} // Here's my attempt at duplicating the functionality of the above code, // without having access to PowerShell-internal stuff (which requires me to // turn some of the logic inside-out because I can't access the session state // when we are nested). PowerShell ps = null; try { var runspace = _parent.Runspace; if (null == runspace) { return(false); } if (runspace.RunspaceAvailability == RunspaceAvailability.AvailableForNestedCommand) { // Nested // We don't have an easy way to check if we have a readline command // defined-- we can't access the SessionState directly when nested (else // we get an error complaining "A pipeline is already running. Concurrent // SessionStateProxy method call is not allowed."). We could run some // script, but we don't want readline commands to cause any auto-loading, // so we have to save the old $PSModuleAutoloadingPreference, set it to // "none", then check for the command (using a wildcard to make sure we // don't generate errors if it doesn't exist), then restore the // $PSModuleAutoloadingPreference... which seems like a pain. So instead, // if we are nested, I'm just going to remember what we had in the // outer-most (non-nested) shell. This means that you won't be able to // change the readline function when nested, but I think that's a fairly // corner-case scenario. // parent._ExecScriptNoExceptionHandling( ps, // Util.Sprintf( ... // false, // false ); if (m_customReadlineFuncExists) { ps = PowerShell.Create(RunspaceMode.CurrentRunspace); } } else { // Not Nested if (runspace.SessionStateProxy.InvokeCommand.GetCommands(CustomReadlineCommand, CommandTypes.All, nameIsPattern: false).Any()) { m_customReadlineFuncExists = true; ps = PowerShell.Create(); ps.Runspace = runspace; } else { m_customReadlineFuncExists = false; } } if (null == ps) { return(false); } var result = ps.AddCommand(CustomReadlineCommand).Invoke(); if (result.Count == 1) { //input = PSObject.Base(result[0]) as string; [danthom] input = PSObjectSubstitute.Base(result[0]) as string; return(true); } else if (result.Count > 1) { var msg = Util.Sprintf("Custom readline function returned multiple results ({0}).", result.Count); LogManager.Trace(msg); Util.Fail(msg); // not a true invariant; just want to stop in the debugger if this ever happens try { ps.Commands.Clear(); ps.AddCommand("Write-Warning").AddParameter("Message", msg); ps.Invoke(); } catch (Exception e2) { Util.Fail(Util.Sprintf("Could not write warning about multi-result readline! {0}", Util.GetExceptionMessages(e2))); } } } catch (Exception e) { // I've seen us get into this situation when running "rmo psreadline" from // within a nested prompt. It seems the prompt function doesn't want to // get reset until we exit the nested prompt. LogManager.Trace("Custom readline function failed: {0}", e.ToString()); try { ps.Commands.Clear(); ps.AddCommand("Write-Warning").AddParameter("Message", Util.Sprintf("Custom readline function failed: {0}", Util.GetExceptionMessages(e))); ps.Invoke(); } catch (Exception e2) { Util.Fail(Util.Sprintf("Could not write warning about failed readline! {0}", Util.GetExceptionMessages(e2))); } } input = null; return(false); }
public CommandCompletion CompleteInput(string input, int cursorIndex, Hashtable options, PowerShell powershell) { return(ReadLine.MockedCompleteInput(input, cursorIndex, options, powershell)); }
public void LaunchCleanup(string connectionString) { TimeSpan timeout = new TimeSpan(0, 10, 0); // max run time string cleanUpScript = string.Empty; string cleanUpScriptPath = string.Empty; string commandText = string.Empty; string scriptName = "CleanUpAfterTests.ps1"; string rootPath = UpNLevels(Environment.CurrentDirectory, 4); string sqlScript = Path.Combine(rootPath, "_PowerShellScripts", scriptName); if (File.Exists(sqlScript)) { commandText = File.ReadAllText(sqlScript); } else { //Check alternative location (for HM deployed as a Web Job) rootPath = Environment.CurrentDirectory; sqlScript = Path.Combine(rootPath, scriptName); if (File.Exists(sqlScript)) { commandText = File.ReadAllText(sqlScript); } else { throw new FileNotFoundException($"The PowerShell script is not found in this location: {sqlScript}"); } } Console.WriteLine("Running clean-up script..."); using (PowerShell ps = PowerShell.Create()) { // 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): ps.Streams.Error.DataAdded += error_DataAdded; ps.Streams.Debug.DataAdded += debug_DataAdded; ps.AddCommand("Set-ExecutionPolicy").AddParameter("ExecutionPolicy", "RemoteSigned").AddParameter("Scope", "Process").Invoke(); Pipeline pipeLine = ps.Runspace.CreatePipeline(); Command cleanCommand = new Command(cleanUpScript, true); cleanCommand.Parameters.Add("connectionString", connectionString); cleanCommand.Parameters.Add("dbName", ""); pipeLine.Commands.Add(cleanCommand); pipeLine.Commands.Add("Out-String"); DateTime startTime = DateTime.UtcNow; pipeLine.InvokeAsync(); while (pipeLine.PipelineStateInfo.State == PipelineState.Running || pipeLine.PipelineStateInfo.State == PipelineState.Stopping) { if (startTime + timeout < DateTime.UtcNow) { //Timeout condition Console.WriteLine("Operation timeout, exiting"); break; } Thread.Sleep(500); } var output = pipeLine.Output.ReadToEnd(); foreach (PSObject outputItem in output) { Console.WriteLine(outputItem.BaseObject?.ToString()); } if (pipeLine.PipelineStateInfo.State == PipelineState.Failed) { Console.WriteLine("Execution completed with error. Reason: " + pipeLine.PipelineStateInfo.Reason.Message); } else { Console.WriteLine("Execution has finished. The pipeline state: " + pipeLine.PipelineStateInfo.State); } } }
public static void AddMailUser(AdUser user, PSCredential creds, Splash splash, string server = "fbi-exch01.fbi.local") { if (splash != null) { splash.Status = $"Генерим скрипт."; } string Script = $"New-Mailbox -Name '{user.FullName}'" + $" -Alias '{user.Login}'" + $" -OrganizationalUnit '{user.Domain.MailboxOU}'" + $" -UserPrincipalName '{user.Login}@fbi.local'" + $" -SamAccountName '{user.Login}'" + $" -FirstName '{user.FirstName}'" + $" -Initials ''" + $" -LastName '{user.SurName}'" + $" -LinkedMasterAccount '{user.Domain.AD}\\{user.Login}'" + $" -LinkedDomainController '{user.Domain.DC}'"; Debug.WriteLine(Script); if (splash != null) { splash.Status = $"Создаём подключение к {server}."; } WSManConnectionInfo connInfo = new WSManConnectionInfo(new Uri($"https://{server}/Powershell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", creds); Runspace runspace = RunspaceFactory.CreateRunspace(connInfo); PowerShell shell = PowerShell.Create(RunspaceMode.NewRunspace); if (splash != null) { splash.Status = $"Открываем подключение к {server}."; } runspace.Open(); shell.Runspace = runspace; shell.AddScript(Script); try { if (splash != null) { splash.Status = $"Выполняем скрипт."; } Collection <PSObject> result = shell.Invoke(); if (shell.HadErrors) { foreach (ErrorRecord errorRecord in shell.Streams.Error) { Debug.WriteLine(errorRecord.Exception); throw errorRecord.Exception; } } foreach (PSObject psObject in result) { Debug.WriteLine(psObject.ToString()); } } catch (Exception e) { Debug.WriteLine(e); //throw; } runspace.CloseAsync(); shell.Dispose(); }
/// <summary> /// Sets up the PowerShell shell stream event handlers. /// </summary> /// <param name="shell">The PowerShell shell.</param> private static void SetupStreamEventHandlers(PowerShell shell) { Logger.Instance.WriteMethodEntry(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers); try { shell.Streams.ClearStreams(); shell.Streams.Error.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <ErrorRecord> errorStream = (PSDataCollection <ErrorRecord>)sender; ErrorRecord record = errorStream[e.Index]; if (record == null) { return; } StringBuilder builder = new StringBuilder(); builder.AppendLine(record.ToString()); if (record.InvocationInfo != null) { builder.AppendLine(); builder.AppendLine(record.InvocationInfo.PositionMessage); } Logger.Instance.WriteError(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersErrorEvents, builder.ToString()); }; shell.Streams.Warning.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <WarningRecord> warningStream = (PSDataCollection <WarningRecord>)sender; WarningRecord record = warningStream[e.Index]; if (record != null) { Logger.Instance.WriteWarning(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersWarningEvents, record.ToString()); } }; shell.Streams.Debug.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <DebugRecord> debugStream = (PSDataCollection <DebugRecord>)sender; DebugRecord record = debugStream[e.Index]; if (record != null) { Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersDebugEvents, record.ToString()); } }; shell.Streams.Verbose.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <VerboseRecord> versboseStream = (PSDataCollection <VerboseRecord>)sender; VerboseRecord record = versboseStream[e.Index]; if (record != null) { Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersEvents, record.ToString()); } }; shell.Streams.Progress.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <ProgressRecord> progressStream = (PSDataCollection <ProgressRecord>)sender; ProgressRecord record = progressStream[e.Index]; if (record != null) { Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersProgressEvents, record.ToString()); } }; } finally { Logger.Instance.WriteMethodExit(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers); } }
static void Main(string[] args) { var handle = GetStdHandle((uint)StandardHandleId.Output); GetConsoleMode(handle, out var mode); var vtEnabled = SetConsoleMode(handle, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING); var iss = InitialSessionState.CreateDefault2(); if (args.Any()) { iss.ImportPSModule(args[0]); } iss.ExecutionPolicy = ExecutionPolicy.Bypass; var rs = RunspaceFactory.CreateRunspace(iss); rs.Open(); Runspace.DefaultRunspace = rs; PSConsoleReadLine.SetOptions(new SetPSReadLineOption { HistoryNoDuplicates = false, PredictionViewStyle = PredictionViewStyle.ListView, PredictionSource = PredictionSource.HistoryAndPlugin, }); if (vtEnabled) { var options = PSConsoleReadLine.GetOptions(); options.CommandColor = "#8181f7"; options.StringColor = "\x1b[38;5;100m"; } using (var ps = PowerShell.Create(rs)) { var executionContext = ps.AddScript("$ExecutionContext").Invoke <EngineIntrinsics>().First(); // Detect if the read loop will enter VT input mode. var vtInputEnvVar = Environment.GetEnvironmentVariable("PSREADLINE_VTINPUT"); var stdin = GetStdHandle((uint)StandardHandleId.Input); GetConsoleMode(stdin, out var inputMode); if (vtInputEnvVar == "1" || (inputMode & ENABLE_VIRTUAL_TERMINAL_INPUT) != 0) { Console.WriteLine("\x1b[33mDefault input mode = virtual terminal\x1b[m"); } else { Console.WriteLine("\x1b[33mDefault input mode = Windows\x1b[m"); } // 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 if you hit a hang, run it once, then comment it out again. //ps.Commands.Clear(); //ps.AddCommand("Get-Command").Invoke(); executionContext.InvokeProvider.Item.Set("function:prompt", ScriptBlock.Create("'TestHostPS> '")); while (true) { ps.Commands.Clear(); Console.Write(string.Join("", ps.AddCommand("prompt").Invoke <string>())); var line = PSConsoleReadLine.ReadLine(rs, executionContext, true); Console.WriteLine(line); line = line.Trim().ToLower(); 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 }); } if (line.Equals("vtinput")) { Environment.SetEnvironmentVariable("PSREADLINE_VTINPUT", "1"); } if (line.Equals("novtinput")) { Environment.SetEnvironmentVariable("PSREADLINE_VTINPUT", "0"); } if (line.Equals("listview")) { PSConsoleReadLine.SetOptions(new SetPSReadLineOption { PredictionViewStyle = PredictionViewStyle.ListView }); } if (line.Equals("inlineview")) { PSConsoleReadLine.SetOptions(new SetPSReadLineOption { PredictionViewStyle = PredictionViewStyle.InlineView }); } if (line.Equals("history")) { PSConsoleReadLine.SetOptions(new SetPSReadLineOption { PredictionSource = PredictionSource.History }); } if (line.Equals("plugin")) { PSConsoleReadLine.SetOptions(new SetPSReadLineOption { PredictionSource = PredictionSource.Plugin }); } if (line.Equals("historyplugin")) { PSConsoleReadLine.SetOptions(new SetPSReadLineOption { PredictionSource = PredictionSource.HistoryAndPlugin }); } if (line.StartsWith("import-module")) { ps.AddScript(line).Invoke(); } if (line.StartsWith("get-module")) { var modules = ps.AddScript(line).Invoke().ToList(); foreach (var m in modules) { Console.WriteLine(((PSModuleInfo)m.BaseObject).Name); } } } } }
/// <summary> /// Installs function app dependencies specified in functionAppRoot\requirements.psd1. /// </summary> internal void InstallFunctionAppDependencies(PowerShell pwsh, ILogger logger) { try { if (Dependencies.Count == 0) { // If there are no dependencies to install, log and return. logger.Log(LogLevel.Trace, PowerShellWorkerStrings.FunctionAppDoesNotHaveDependentModulesToInstall, isUserLog: true); return; } if (!_shouldUpdateFunctionAppDependencies) { // The function app already has the latest dependencies installed. logger.Log(LogLevel.Trace, PowerShellWorkerStrings.LatestFunctionAppDependenciesAlreadyInstalled, isUserLog: true); return; } // Install the function dependencies. logger.Log(LogLevel.Trace, PowerShellWorkerStrings.InstallingFunctionAppDependentModules, isUserLog: true); if (Directory.Exists(DependenciesPath)) { // Save-Module supports downloading side-by-size module versions. However, we only want to keep one version at the time. // If the ManagedDependencies folder exits, remove all its contents. DependencyManagementUtils.EmptyDirectory(DependenciesPath); } else { // If the destination path does not exist, create it. Directory.CreateDirectory(DependenciesPath); } try { foreach (DependencyInfo module in Dependencies) { string moduleName = module.Name; string latestVersion = module.LatestVersion; // Save the module to the given path pwsh.AddCommand("PowerShellGet\\Save-Module") .AddParameter("Repository", Repository) .AddParameter("Name", moduleName) .AddParameter("RequiredVersion", latestVersion) .AddParameter("Path", DependenciesPath) .AddParameter("Force", true) .AddParameter("ErrorAction", "Stop") .InvokeAndClearCommands(); var message = string.Format(PowerShellWorkerStrings.ModuleHasBeenInstalled, moduleName, latestVersion); logger.Log(LogLevel.Trace, message, isUserLog: true); } } finally { // Clean up pwsh.AddCommand(Utils.RemoveModuleCmdletInfo) .AddParameter("Name", "PackageManagement, PowerShellGet") .AddParameter("Force", true) .AddParameter("ErrorAction", "SilentlyContinue") .InvokeAndClearCommands(); } } catch (Exception e) { var errorMsg = string.Format(PowerShellWorkerStrings.FailToInstallFuncAppDependencies, e.Message); throw new DependencyInstallationException(errorMsg, e); } }
public IActionResult ExtractPs() { var res = PowerShell.InvokeFile(@"scripts\test.ps1"); return(StatusCode(res.Ok ? 200 : 500, res)); }
/// <summary> /// 원격서버스크립트수행 /// </summary> private void ExPs_GisTbloader() { // Username and Password for the remote machine. var userName = User; string pw = PW; // Creates a secure string for the password SecureString securePassword = new SecureString(); foreach (char c in pw) { securePassword.AppendChar(c); } securePassword.MakeReadOnly(); // Creates a PSCredential object PSCredential creds = new PSCredential(userName, securePassword); // Creates the runspace for PowerShell Runspace runspace = RunspaceFactory.CreateRunspace(); // Create the PSSession connection to the remote machine. //ComputerName string computerName = IP; PowerShell powershell = PowerShell.Create(); PSCommand command = new PSCommand(); command.AddCommand("New-PSSession"); command.AddParameter("ComputerName", computerName); command.AddParameter("Credential", creds); powershell.Commands = command; runspace.Open(); powershell.Runspace = runspace; Collection <PSObject> result = powershell.Invoke(); // Takes the PSSession object and places it into a PowerShell variable powershell = PowerShell.Create(); command = new PSCommand(); command.AddCommand("Set-Variable"); command.AddParameter("Name", "session"); command.AddParameter("Value", result[0]); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); // Calls the Copy-Item cmdlet as a script and passes the PSSession, Path and destination parameters to it // 1.gisLoader 실행 powershell = PowerShell.Create(); command = new PSCommand(); command.AddScript(@"Invoke-Command -Session $session -ScriptBlock {Invoke-Expression -Command:'cmd /c gisLoader d:\shape\WTL_SPLY_LS.shp infofms.WTL_SPLY_LS' }"); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); // 2.tbloader 실행 powershell = PowerShell.Create(); command = new PSCommand(); command.AddScript(@"Invoke-Command -Session $session -ScriptBlock {Invoke-Expression -Command:'cmd /c tbloader userid=infouser/infouser control=d:\shape\WTL_SPLY_LS.ctl' } "); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); // 세션종료 powershell = PowerShell.Create(); powershell.Runspace = runspace; powershell.AddScript("Remove-PSSession $session"); powershell.Invoke(); }
public void GetRestorableDroppedDatabaseWithSqlAuth() { using (var powershell = PowerShell.Create()) { // Create a context NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(powershell, "$context"); var testSession = MockServerHelper.DefaultSessionCollection.GetSession( "UnitTests.GetRestorableDroppedDatabaseWithSqlAuth"); DatabaseTestHelper.SetDefaultTestSessionSettings(testSession); testSession.RequestValidator = new Action <HttpMessage, HttpMessage.Request>( (expected, actual) => { Assert.AreEqual(expected.RequestInfo.Method, actual.Method); Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent); if (expected.Index < 3) { DatabaseTestHelper.ValidateHeadersForODataRequest(expected.RequestInfo, actual); } else { Assert.Fail("No more requests expected."); } }); using (var exceptionManager = new AsyncExceptionManager()) { Collection <PSObject> databases, database1, database2; using (new MockHttpServer(exceptionManager, MockHttpServer.DefaultServerPrefixUri, testSession)) { databases = powershell.InvokeBatchScript( @"Get-AzureSqlDatabase -RestorableDropped " + @"-Context $context"); } Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!"); Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!"); powershell.Streams.ClearStreams(); // Expecting testdb1, testdb2, possibly dropped databases from previous runs Assert.IsTrue( databases.Count >= 2, "Expecting at-least two RestorableDroppedDatabase objects"); Assert.IsTrue( databases[0].BaseObject is RestorableDroppedDatabase, "Expecting a RestorableDroppedDatabase object"); Assert.IsTrue( databases[1].BaseObject is RestorableDroppedDatabase, "Expecting a RestorableDroppedDatabase object"); var database1Object = (RestorableDroppedDatabase)databases[0].BaseObject; var database1DeletionDate = database1Object.DeletionDate.ToUniversalTime().ToString(deletionDateStringFormat); var database2Object = (RestorableDroppedDatabase)databases[1].BaseObject; var database2DeletionDate = database2Object.DeletionDate.ToUniversalTime().ToString(deletionDateStringFormat); using (new MockHttpServer( exceptionManager, MockHttpServer.DefaultServerPrefixUri, testSession)) { database1 = powershell.InvokeBatchScript( @"Get-AzureSqlDatabase -RestorableDropped " + @"-Context $context " + @"-DatabaseName " + database1Object.Name + @" " + @"-DatabaseDeletionDate " + database1DeletionDate); database2 = powershell.InvokeBatchScript( @"Get-AzureSqlDatabase -RestorableDropped " + @"-Context $context " + @"-DatabaseName " + database2Object.Name + @" " + @"-DatabaseDeletionDate " + database2DeletionDate); } Assert.IsTrue( database1.Single().BaseObject is RestorableDroppedDatabase, "Expecting a RestorableDroppedDatabase object"); var refreshedDatabase1Object = (RestorableDroppedDatabase)database1.Single().BaseObject; Assert.AreEqual( database1Object.Name, refreshedDatabase1Object.Name, "Expected db name to be " + database1Object.Name); Assert.IsTrue( database2.Single().BaseObject is RestorableDroppedDatabase, "Expecting a RestorableDroppedDatabase object"); var refreshedDatabase2Object = (RestorableDroppedDatabase)database2.Single().BaseObject; Assert.AreEqual( database2Object.Name, refreshedDatabase2Object.Name, "Expected db name to be " + database2Object.Name); Assert.AreEqual( database2Object.Edition, refreshedDatabase2Object.Edition, "Expected edition to be " + database2Object.Edition); Assert.AreEqual( database2Object.MaxSizeBytes, refreshedDatabase2Object.MaxSizeBytes, "Expected max size to be " + database2Object.MaxSizeBytes); } } }
/// <summary> /// Create pipeline. /// </summary> internal Pipeline CreatePipeline(string line, bool addToHistory, bool useNestedPipelines) { // This method allows input commands to work against no-language runspaces. If a runspace // is pushed, it tries to parse the line using a ScriptBlock object. If a runspace is not // pushed, or if the parsing fails, in these cases it reverts to calling CreatePipeline // using the unparsed line. Pipeline pipeline = null; // In Start-PSSession scenario try to create a pipeline by parsing the line as a script block. if (this.IsRunspaceOverridden) { // Win8: exit should work to escape from the restrictive session if ((_runspaceRef.Value is RemoteRunspace) && (!string.IsNullOrEmpty(line) && string.Equals(line.Trim(), "exit", StringComparison.OrdinalIgnoreCase))) { line = "Exit-PSSession"; } PSCommand psCommand = ParsePsCommandUsingScriptBlock(line, null); if (psCommand != null) { pipeline = useNestedPipelines ? _runspaceRef.Value.CreateNestedPipeline(psCommand.Commands[0].CommandText, addToHistory) : _runspaceRef.Value.CreatePipeline(psCommand.Commands[0].CommandText, addToHistory); pipeline.Commands.Clear(); foreach (Command command in psCommand.Commands) { pipeline.Commands.Add(command); } } } // If that didn't work out fall-back to the traditional approach. if (pipeline == null) { pipeline = useNestedPipelines ? _runspaceRef.Value.CreateNestedPipeline(line, addToHistory) : _runspaceRef.Value.CreatePipeline(line, addToHistory); } // Add robust connection callback if this is a pushed runspace. RemotePipeline remotePipeline = pipeline as RemotePipeline; if (this.IsRunspaceOverridden && remotePipeline != null) { PowerShell shell = remotePipeline.PowerShell; if (shell.RemotePowerShell != null) { shell.RemotePowerShell.RCConnectionNotification += new EventHandler <PSConnectionRetryStatusEventArgs>(HandleRCConnectionNotification); } // Add callback to write robust connection errors from stream. shell.ErrorBuffer.DataAdded += (sender, eventArgs) => { RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace; PSDataCollection <ErrorRecord> erBuffer = sender as PSDataCollection <ErrorRecord>; if (remoteRunspace != null && erBuffer != null && remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host != null) { Collection <ErrorRecord> erRecords = erBuffer.ReadAll(); foreach (var er in erRecords) { remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host.UI.WriteErrorLine(er.ToString()); } } }; } pipeline.SetHistoryString(line); return(pipeline); }
public void GetRestorableDroppedDatabaseWithSqlAuthNonExistentDb() { using (var powershell = PowerShell.Create()) { // Create a context NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(powershell, "$context"); var testSession = MockServerHelper.DefaultSessionCollection.GetSession( "UnitTests.GetRestorableDroppedDatabaseWithSqlAuthNonExistentDb"); DatabaseTestHelper.SetDefaultTestSessionSettings(testSession); testSession.RequestValidator = new Action <HttpMessage, HttpMessage.Request>( (expected, actual) => { Assert.AreEqual(expected.RequestInfo.Method, actual.Method); Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent); if (expected.Index < 1) { DatabaseTestHelper.ValidateHeadersForODataRequest(expected.RequestInfo, actual); } else { Assert.Fail("No more requests expected."); } }); using (var exceptionManager = new AsyncExceptionManager()) { using (new MockHttpServer( exceptionManager, MockHttpServer.DefaultServerPrefixUri, testSession)) { powershell.InvokeBatchScript( @"Get-AzureSqlDatabase -RestorableDropped " + @"-Context $context " + @"-DatabaseName testdbnonexistent " + @"-DatabaseDeletionDate '10/01/2013 12:00:00 AM'"); } Assert.AreEqual( 1, powershell.Streams.Error.Count, "Expecting errors"); Assert.AreEqual( 2, powershell.Streams.Warning.Count, "Expecting tracing IDs"); Assert.AreEqual( string.Format( CultureInfo.InvariantCulture, "Database '{0}' with deletion date '{1}' not found.", testSession.SessionProperties["Servername"] + ".testdbnonexistent", new DateTime(2013, 10, 01, 0, 0, 0, DateTimeKind.Utc)), powershell.Streams.Error.First().Exception.Message, "Unexpected error message"); Assert.IsTrue( powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Session Id")), "Expecting Client Session Id"); Assert.IsTrue( powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Request Id")), "Expecting Client Request Id"); } } }
/// <summary> /// Runs the PowerShell script. /// </summary> /// <param name="script">The script.</param> /// <param name="scriptArguments">The PowerShell script arguments.</param> /// <param name="scriptParameters">The PowerShell script parameters.</param> /// <returns>The output of the script.</returns> private object RunScript(string script, IEnumerable scriptArguments, Dictionary <string, object> scriptParameters) { Logger.Instance.WriteMethodEntry(EventIdentifier.RunPowerShellScriptRunScript); WindowsImpersonationContext context = null; LogOnUser logOnUser = null; try { PSCredential credential = this.GetPowerShellCredential(); logOnUser = this.LogOnUser(credential); if (logOnUser != null) { context = logOnUser.Impersonate(); } // Establish a new runspace for the Powershell script InitialSessionState initialSessionState = InitialSessionState.CreateDefault(); bool progressPreference = Logger.Instance.ShouldTrace(TraceEventType.Information); bool debugPreference = Logger.Instance.ShouldTrace(TraceEventType.Information); bool verbosePreference = Logger.Instance.ShouldTrace(TraceEventType.Verbose); initialSessionState.Variables.Add(new SessionStateVariableEntry("ProgressPreference", progressPreference ? "Continue" : "SilentlyContinue", string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("DebugPreference", debugPreference ? "Continue" : "SilentlyContinue", string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("VerbosePreference", verbosePreference ? "Continue" : "SilentlyContinue", string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("AECWorkflowInstanceId", Logger.GetContextItem("WorkflowInstanceId"), string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("AECRequestId", Logger.GetContextItem("RequestId"), string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("AECActorId", Logger.GetContextItem("ActorId"), string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("AECTargetId", Logger.GetContextItem("TargetId"), string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("AECWorkflowDefinitionId", Logger.GetContextItem("WorkflowDefinitionId"), string.Empty)); initialSessionState.Variables.Add(new SessionStateVariableEntry("Credential", credential, null)); using (Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState)) { runspace.Open(); using (PowerShell shell = PowerShell.Create()) { shell.Runspace = runspace; SetupStreamEventHandlers(shell); // Add the script to the PowerShell instance to prepare for execution shell.AddScript(script); StringBuilder scriptParams = new StringBuilder(); if (scriptParameters != null) { foreach (string s in scriptParameters.Keys) { shell.AddParameter(s, scriptParameters[s]); scriptParams.AppendFormat(CultureInfo.InvariantCulture, "-{0} '{1}' ", s, scriptParameters[s]); } } else if (scriptArguments != null) { foreach (object o in scriptArguments) { shell.AddArgument(o); scriptParams.AppendFormat(CultureInfo.InvariantCulture, "'{0}' ", o); } } if (this.InputType != PowerShellInputType.None) { Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptRunScript, "The PowerShell script parameters are: '{0}'.", scriptParams); } // Execute the script and identify if any errors occurred // In most circumstances, errors will not be raised as exceptions but will instead // be presented in the Error collection for the PowerShell instance Collection <PSObject> results; try { results = shell.Invoke(); } catch (Exception ex) { throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptInvocationError, new WorkflowActivityLibraryException(Messages.RunPowerShellScript_ScriptInvocationError, ex, ex.Message)); } // Let's go soft on the the non-terminating errors and trapped exceptions. // We'll just log the error streams. // If script wants to kill the activity, it should throw an exception. if (shell.Streams.Error.Count != 0) { StringBuilder message = new StringBuilder(); message.AppendFormat(Messages.RunPowerShellScript_ScriptExecutionFailedError, shell.Streams.Error.Count); foreach (ErrorRecord error in shell.Streams.Error) { message.AppendFormat("{0}\n", error); } Logger.Instance.WriteError(EventIdentifier.RunPowerShellScriptRunScriptExecutionFailedError, message.ToString()); } if (this.ReturnType == PowerShellReturnType.None) { return(null); } if (results != null && results.Count == 1) { return(results[0].BaseObject); } if (results == null || results.Count < 1) { return(null); } // If multiple values were found for the lookup, verify that they are of a consistent type Type type = null; bool consistentType = true; foreach (PSObject pso in results) { if (type == null) { type = pso.BaseObject.GetType(); Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptRunScript, "The PowerShell script returned type: '{0}'.", type); } else if (pso.BaseObject.GetType() != type) { consistentType = false; Logger.Instance.WriteError(EventIdentifier.RunPowerShellScriptRunScriptInconsistentScriptReturnTypeError, Messages.RunPowerShellScript_InconsistentScriptReturnTypeError, pso.BaseObject.GetType(), type); } } // If we have multiple values of an inconsistent type, there is a problem // which needs to be addressed by the administrator if (!consistentType) { throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptInconsistentScriptReturnTypeError, new WorkflowActivityLibraryException(Messages.RunPowerShellScript_InvalidReturnTypeError)); } // Because we have multiple values returned for the PowerShell script, // we want to return them in the form of a strongly-typed list // For example: List<string> instead of List<object> // Use reflection to create a new strongly-typed list Type listType = typeof(List <>).MakeGenericType(new Type[] { type }); var typedList = Activator.CreateInstance(listType); // Using reflection, fetch the add method for the new list // and invoke it to add each value from the original PSobject collection to the new collection // Return the strongly-typed list MethodInfo add = listType.GetMethod("Add"); foreach (PSObject pso in results) { add.Invoke(typedList, new object[] { pso.BaseObject }); } return(typedList); } } } catch (Exception ex) { throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptExecutionFailedError, ex); } finally { if (context != null) { context.Undo(); } if (logOnUser != null) { logOnUser.Dispose(); } Logger.Instance.WriteMethodExit(EventIdentifier.RunPowerShellScriptRunScript); } }
public static void ImportModule(this PowerShell pwsh, string moduleNameOrPath) { pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module") .AddParameter("-Name", moduleNameOrPath) .InvokeAndClear(); }
/// <summary> /// Override inside a safe lock. /// </summary> /// <param name="remoteRunspace">Runspace to override.</param> /// <param name="syncObject">Object to use in synchronization.</param> /// <param name="isRunspacePushed">Set is runspace pushed.</param> internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed) { lock (_localSyncObject) { _stopInvoke = false; } try { if (syncObject != null) { lock (syncObject) { _runspaceRef.Override(remoteRunspace); isRunspacePushed = true; } } else { _runspaceRef.Override(remoteRunspace); isRunspacePushed = true; } if ((remoteRunspace.GetCurrentlyRunningPipeline() != null)) { // Don't execute command if pushed runspace is already running one. return; } using (PowerShell powerShell = PowerShell.Create()) { powerShell.AddCommand("Get-Command"); powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" }); powerShell.Runspace = _runspaceRef.Value; bool isReleaseCandidateBackcompatibilityMode = _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode; int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3; powerShell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(HandleHostCall); IAsyncResult asyncResult = powerShell.BeginInvoke(); PSDataCollection <PSObject> results = new PSDataCollection <PSObject>(); while (!_stopInvoke) { asyncResult.AsyncWaitHandle.WaitOne(1000); if (asyncResult.IsCompleted) { results = powerShell.EndInvoke(asyncResult); break; } } if (powerShell.Streams.Error.Count > 0 || results.Count < expectedNumberOfResults) { throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException(); } } } catch (Exception) { _runspaceRef.Revert(); isRunspacePushed = false; throw; } }
// Have a single place to get a PowerShellManager for testing. // This is to guarantee that the well known paths are setup before calling the constructor of PowerShellManager. internal static PowerShellManager NewTestPowerShellManager(ConsoleLogger logger, PowerShell pwsh = null) { return(pwsh != null ? new PowerShellManager(logger, pwsh) : new PowerShellManager(logger, id: 2)); }
public static Collection <TResult> InvokeCommand <TResult>(this PowerShell pwsh, PSCommand psCommand, PSInvocationSettings invocationSettings = null) { pwsh.Commands = psCommand; return(pwsh.InvokeAndClear <TResult>(invocationSettings)); }