internal virtual Runspace OpenRunspace() { if (runspaceConfiguration == null) { runspaceConfiguration = RunspaceConfiguration.Create(); PSSnapInException exception = null; if (exception != null) { //todo exception } } Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration); // runSpace.Open(); // runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none"); return(runSpace); }
public static void Demo4() { RunspaceConfiguration rconfig = RunspaceConfiguration.Create(); PSSnapInException pwarn = new PSSnapInException(); string test = "Import-Module VirtualMachineManager\r\n"; var runspace = RunspaceFactory.CreateRunspace(rconfig); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(test); pipeline.Invoke(); using (Pipeline pipe = runspace.CreatePipeline()) { //Get-VM -Name vm001 Command cmd = new Command("Get-VM"); cmd.Parameters.Add("Name", "vm001"); pipe.Commands.Add(cmd); pipe.Invoke(); } }
private IEnumerable <harddisk> runCommand() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String preCommand = "Get-HardDisk -VM + \"" + VMName + "\" | ? {$_.Name -eq \"" + DiskName + "\"}"; String command = "Remove-HardDisk"; Script += preCommand + " | " + command + " -Confirm:$False"; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("DiskImpl")) { yield return(new harddisk(obj)); } } runspace.Close(); }
private static bool RunScript(string cmd) { // create Powershell runspace try { RunspaceConfiguration rsConfig = RunspaceConfiguration.Create(); PSSnapInException snapInException = null; PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException); Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig); myRunSpace.Open(); Pipeline pipeLine = myRunSpace.CreatePipeline(); Command myCommand = new Command(cmd, true); pipeLine.Commands.Add(myCommand); Collection <PSObject> commandResults = pipeLine.Invoke(); foreach (PSObject obj in commandResults) { Console.WriteLine(obj.ToString()); } return(true); } catch (Exception ex) { return(false); } }
public static string ExecPowerShellCommand(string sCommand, bool bRemoveEmptyLines) { if (runspace == null) { PSSnapInInfo info = null; PSSnapInException ex = null; bool error = false; try { runspace = RunspaceFactory.CreateRunspace(RunspaceConfiguration.Create()); runspace.Open(); foreach (string pssnapin in ExchangePsSnapin) { if (Execute("$(Get-PSSnapin -Registered | Select-String " + pssnapin + ") -ne $null", true).Trim() == "True") { info = runspace.RunspaceConfiguration.AddPSSnapIn(pssnapin, out ex); } } } catch (Exception) { error = true; } if (ex != null || info == null || error) { if (runspace != null) { runspace.Dispose(); runspace = null; } throw new ExchangeServerException("Couldn't initialize PowerShell runspace."); } } return(Execute(sCommand, bRemoveEmptyLines)); }
private void loadCitrixCmdlets() { PSSnapInException psEx = null; //load all the citrix powershell snapins rsc.AddPSSnapIn("Citrix.ADIdentity.Admin.V2", out psEx); rsc.AddPSSnapIn("Citrix.Analytics.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.AppLibrary.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.AppV.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.Broker.Admin.V2", out psEx); rsc.AddPSSnapIn("Citrix.Configuration.Admin.V2", out psEx); rsc.AddPSSnapIn("Citrix.ConfigurationLogging.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.DelegatedAdmin.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.EnvTest.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.Host.Admin.V2", out psEx); rsc.AddPSSnapIn("Citrix.Licensing.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.MachineCreation.Admin.V2", out psEx); rsc.AddPSSnapIn("Citrix.Monitor.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.Orchestration.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.Storefront.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.Trust.Admin.V1", out psEx); rsc.AddPSSnapIn("Citrix.UserProfileManager.Admin.V1", out psEx); }
public Runspace DefaultRunspaceCreateMethod() { LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Creating runspace configuration"); RunspaceConfiguration runSpaceConfig = RunspaceConfiguration.Create(); if (_localSnapinNames != null) { foreach (string snapinName in _localSnapinNames) { LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Adding snap-in {0}", snapinName); PSSnapInException snapOutput = null; runSpaceConfig.AddPSSnapIn(snapinName, out snapOutput); if (snapOutput != null) { throw snapOutput; } } } LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Creating the runspace"); var runspace = RunspaceFactory.CreateRunspace(runSpaceConfig); LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Runspace created"); return(runspace); }
public Runspace DefaultRunspaceCreateMethod() { LOG.Trace("Creating runspace configuration"); RunspaceConfiguration runSpaceConfig = RunspaceConfiguration.Create(); if (_localSnapinNames != null) { foreach (string snapinName in _localSnapinNames) { LOG.Debug("Adding snap-in {0}", snapinName); PSSnapInException snapOutput = null; runSpaceConfig.AddPSSnapIn(snapinName, out snapOutput); if (snapOutput != null) { throw snapOutput; } } } LOG.Trace("Creating the runspace"); var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0])); LOG.Trace("Runspace created"); return(runspace); }
private IEnumerable <snapshot> runCommand() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String preCommand = "Get-Snapshot"; if (!(VM == String.Empty)) { preCommand += " -VM \"" + VM + "\""; } if (!(Snapshot == String.Empty)) { preCommand += " -Name \"" + Snapshot + "\""; } String command = "Remove-Snapshot"; if (RemoveChildren.Equals("true")) { command += " -RemoveChildren"; } Script += preCommand + " | " + command + " -Confirm:$False"; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("VMware.VimAutomation.ViCore.Impl.V1.VM.SnapshotImpl")) { String Created = obj.Members["Created"].Value.ToString(); String Quiesced = obj.Members["Quiesced"].Value.ToString(); String PowerState = obj.Members["PowerState"].Value.ToString(); String VMId = obj.Members["VMId"].Value.ToString(); String SizeMB = obj.Members["SizeMB"].Value.ToString(); String IsCurrent = obj.Members["IsCurrent"].Value.ToString(); String IsReplaySupported = obj.Members["IsReplaySupported"].Value.ToString(); String Id = obj.Members["Id"].Value.ToString(); String name = obj.Members["Name"].Value.ToString(); String Snapshot_Description = String.Empty; try { Snapshot_Description = obj.Members["Description"].Value.ToString(); } catch { } yield return(new snapshot(Created, Quiesced, PowerState, VMId, SizeMB, IsCurrent, IsReplaySupported, Id, name, Snapshot_Description)); } } runspace.Close(); }
private IEnumerable <harddisk> runCommand() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String command = "Get-HardDisk"; if (!(Path == String.Empty)) { command += " -Path \"" + Path + "\""; } if (!(DiskType == String.Empty)) { command += " -DiskType \"" + DiskType + "\""; } if (!(Datastore == String.Empty)) { command += " -Datastore \"" + Datastore + "\""; } if (!(DatastorePath == String.Empty)) { command += " -DatastorePath \"" + DatastorePath + "\""; } if (!(VM == String.Empty)) { command += " -VM \"" + VM + "\""; } if (!(Template == String.Empty)) { command += " -Template \"" + Template + "\""; } if (!(Snapshot == String.Empty)) { command += " -Snapshot \"" + Snapshot + "\""; } Script += command; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("DiskImpl")) { yield return(new harddisk(obj)); } } runspace.Close(); }
private IEnumerable <ResourcePool> getResourcePool() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String command = "Get-ResourcePool"; if (!(VM == String.Empty)) { command += " -VM " + VM; } if (!(Location == String.Empty)) { command += " -Location " + Location; } if (!(Name == String.Empty)) { command += " -Name " + Name; } if (!(Id == String.Empty)) { command += " -Id " + Id; } Script += command; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("VMware.VimAutomation.ViCore.Impl.V1.Inventory.ResourcePoolImpl")) { String NumCpuShares = obj.Members["NumCpuShares"].Value.ToString(); String CpuReservationMHz = obj.Members["CpuReservationMHz"].Value.ToString(); String CpuExpandableReservation = obj.Members["CpuExpandableReservation"].Value.ToString(); String CpuLimitMHz = obj.Members["CpuLimitMHz"].Value.ToString(); String NumMemShares = obj.Members["NumMemShares"].Value.ToString(); String MemReservationMB = obj.Members["MemReservationMB"].Value.ToString(); String MemExpandableReservation = obj.Members["MemExpandableReservation"].Value.ToString(); String MemLimitMB = obj.Members["MemLimitMB"].Value.ToString(); String id = obj.Members["Id"].Value.ToString(); String name = obj.Members["Name"].Value.ToString(); yield return(new ResourcePool(NumCpuShares, CpuReservationMHz, CpuExpandableReservation, CpuLimitMHz, NumMemShares, MemReservationMB, MemExpandableReservation, MemLimitMB, id, name)); } } runspace.Close(); }
private IEnumerable <harddisk> runCommand() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String command = "New-HardDisk"; if (!(Persistence == String.Empty)) { command += " -Persistence \"" + Persistence + "\""; } if (!(DiskType == String.Empty)) { command += " -DiskType \"" + DiskType + "\""; } if (!(CapacityKB == String.Empty)) { command += " -CapacityKB \"" + CapacityKB + "\""; } if (Split.Equals("true")) { command += " -Split"; } if (ThinProvisioned.Equals("true")) { command += " -ThinProvisioned"; } if (!(DeviceName == String.Empty)) { command += " -DeviceName \"" + DeviceName + "\""; } if (!(Datastore == String.Empty)) { command += " -Datastore \"" + Datastore + "\""; } if (!(VM == String.Empty)) { command += " -VM \"" + VM + "\""; } if (!(DiskPath == String.Empty)) { command += " -DiskPath \"" + DiskPath + "\""; } Script += command + " -Confirm:$False"; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("DiskImpl")) { yield return(new harddisk(obj)); } } runspace.Close(); }
private void AddPSSnapIns(Collection <string> snapInList) { if (snapInList != null) { if (base.Context.RunspaceConfiguration == null) { Collection <PSSnapInInfo> snapIns = base.GetSnapIns(null); InitialSessionState state = InitialSessionState.Create(); bool flag = false; foreach (string str in snapInList) { if (InitialSessionState.IsEngineModule(str)) { base.WriteNonTerminatingError(str, "LoadSystemSnapinAsModule", PSTraceSource.NewArgumentException(str, "MshSnapInCmdletResources", "LoadSystemSnapinAsModule", new object[] { str }), ErrorCategory.InvalidArgument); } else { try { PSSnapInInfo psSnapInInfo = PSSnapInReader.Read(Utils.GetCurrentMajorVersion(), str); PSSnapInInfo info2 = PSSnapInCommandBase.IsSnapInLoaded(snapIns, psSnapInInfo); if (info2 == null) { PSSnapInException exception; info2 = state.ImportPSSnapIn(str, out exception); flag = true; base.Context.InitialSessionState.ImportedSnapins.Add(info2.Name, info2); } if (this._passThru) { info2.LoadIndirectResources(base.ResourceReader); base.WriteObject(info2); } } catch (PSSnapInException exception2) { base.WriteNonTerminatingError(str, "AddPSSnapInRead", exception2, ErrorCategory.InvalidData); } } } if (flag) { state.Bind(base.Context, true); } } else { foreach (string str2 in snapInList) { Exception innerException = null; try { PSSnapInException warning = null; PSSnapInInfo sendToPipeline = base.Runspace.AddPSSnapIn(str2, out warning); if (warning != null) { base.WriteNonTerminatingError(str2, "AddPSSnapInRead", warning, ErrorCategory.InvalidData); } if (this._passThru) { sendToPipeline.LoadIndirectResources(base.ResourceReader); base.WriteObject(sendToPipeline); } } catch (PSArgumentException exception5) { innerException = exception5; } catch (PSSnapInException exception6) { innerException = exception6; } catch (SecurityException exception7) { innerException = exception7; } if (innerException != null) { base.WriteNonTerminatingError(str2, "AddPSSnapInRead", innerException, ErrorCategory.InvalidArgument); } } } } }
private IEnumerable <vmHost> getVMHost() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String getVMHost = "Get-VMHost"; if (!(Datastore == String.Empty)) { getVMHost += " -Datastore " + Datastore; } if (!(State == String.Empty)) { getVMHost += " -State " + State; } if (!(Location == String.Empty)) { getVMHost += " -Location " + Location; } if (!(Name == String.Empty)) { getVMHost += " -Name " + Name; } if (!(Id == String.Empty)) { getVMHost += " -Id " + Id; } if (!(VM == String.Empty)) { getVMHost += " -VM " + VM; } if (!(ResourcePool == String.Empty)) { getVMHost += " -ResourcePool " + ResourcePool; } Script += getVMHost; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl")) { String ConnectionState = obj.Members["ConnectionState"].Value.ToString(); String PowerState = obj.Members["PowerState"].Value.ToString(); String isStandalone = obj.Members["isStandalone"].Value.ToString(); String Manufacturer = obj.Members["Manufacturer"].Value.ToString(); String Model = obj.Members["Model"].Value.ToString(); String NumCpu = obj.Members["NumCpu"].Value.ToString(); String MemoryTotalMB = obj.Members["MemoryTotalMB"].Value.ToString(); String MemoryUsageMB = obj.Members["MemoryUsageMB"].Value.ToString(); String ProcessorType = obj.Members["ProcessorType"].Value.ToString(); String HyperthreadingActive = obj.Members["HyperthreadingActive"].Value.ToString(); String TimeZone = obj.Members["TimeZone"].Value.ToString(); String Version = obj.Members["Version"].Value.ToString(); String Build = obj.Members["Build"].Value.ToString(); String id = obj.Members["Id"].Value.ToString(); String name = obj.Members["Name"].Value.ToString(); yield return(new vmHost(ConnectionState, PowerState, isStandalone, Manufacturer, Model, NumCpu, MemoryTotalMB, MemoryUsageMB, ProcessorType, HyperthreadingActive, TimeZone, Version, Build, id, name)); } } runspace.Close(); }
/// <summary> /// Removes pssnapins from the current console file. /// </summary> /// <remarks> /// The pssnapin is not unloaded from the current engine. So all the cmdlets that are /// represented by this pssnapin will continue to work. /// </remarks> protected override void ProcessRecord() { foreach (string psSnapIn in _pssnapins) { Collection <PSSnapInInfo> snapIns = GetSnapIns(psSnapIn); // snapIns won't be null.. Diagnostics.Assert(snapIns != null, "GetSnapIns() returned null"); if (snapIns.Count == 0) { WriteNonTerminatingError(psSnapIn, "NoPSSnapInsFound", PSTraceSource.NewArgumentException(psSnapIn, MshSnapInCmdletResources.NoPSSnapInsFound, psSnapIn), ErrorCategory.InvalidArgument); continue; } foreach (PSSnapInInfo snapIn in snapIns) { // confirm the operation first // this is always false if WhatIf is set if (ShouldProcess(snapIn.Name)) { Exception exception = null; if (this.Runspace == null && this.Context.InitialSessionState != null) { try { // Check if this snapin can be removed // Monad has specific restrictions on the mshsnapinid like // mshsnapinid should be A-Za-z0-9.-_ etc. PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(snapIn.Name); if (MshConsoleInfo.IsDefaultPSSnapIn(snapIn.Name, this.Context.InitialSessionState.defaultSnapins)) { throw PSTraceSource.NewArgumentException(snapIn.Name, ConsoleInfoErrorStrings.CannotRemoveDefault, snapIn.Name); } // Handle the initial session state case... InitialSessionState iss = InitialSessionState.Create(); PSSnapInException warning; // Get the snapin information... iss.ImportPSSnapIn(snapIn, out warning); iss.Unbind(Context); Context.InitialSessionState.ImportedSnapins.Remove(snapIn.Name); } catch (PSArgumentException ae) { exception = ae; } if (exception != null) { WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument); } } else { try { PSSnapInException warning = null; PSSnapInInfo psSnapInInfo = this.Runspace.RemovePSSnapIn(snapIn.Name, out warning); if (warning != null) { WriteNonTerminatingError(snapIn.Name, "RemovePSSnapInRead", warning, ErrorCategory.InvalidData); } if (_passThru) { // Load the pssnapin info properties that are localizable and redirected in the registry psSnapInInfo.LoadIndirectResources(ResourceReader); WriteObject(psSnapInInfo); } } catch (PSArgumentException ae) { exception = ae; } if (exception != null) { WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument); } } } // ShouldContinue } } }
private IEnumerable <vm> startVM() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String command = "Restart-VM"; if (GuestCommand.Equals("true")) { command = "Restart-VMGuest"; } if (!(VM == String.Empty)) { command += " -VM " + VM; } Script += command + " -Confirm:$False"; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl")) { String PowerState = obj.Members["PowerState"].Value.ToString(); String VMVersion = obj.Members["Version"].Value.ToString(); String Description = obj.Members["Description"].Value.ToString(); String Notes = obj.Members["Notes"].Value.ToString(); String NumCpu = obj.Members["NumCpu"].Value.ToString(); String MemoryMB = obj.Members["MemoryMB"].Value.ToString(); String HostId = obj.Members["HostId"].Value.ToString(); String FolderId = obj.Members["FolderId"].Value.ToString(); String ResourcePoolId = obj.Members["ResourcePoolId"].Value.ToString(); String UsedSpaceGB = obj.Members["UsedSpaceGB"].Value.ToString(); String ProvisionedSpaceGB = obj.Members["ProvisionedSpaceGB"].Value.ToString(); String id = obj.Members["Id"].Value.ToString(); String name = obj.Members["Name"].Value.ToString(); yield return(new vm(PowerState, VMVersion, Description, Notes, NumCpu, MemoryMB, HostId, FolderId, ResourcePoolId, UsedSpaceGB, ProvisionedSpaceGB, id, name)); } } runspace.Close(); }
public void Execute(IActivityRequest request, IActivityResponse response) { userName = settings.UserName; password = settings.Password; domain = settings.Domain; port = settings.Port; virtualCenter = settings.VirtualCenter; OSType = request.Inputs["OSType"].AsString(); Name = request.Inputs["Name"].AsString(); Type = request.Inputs["Type"].AsString(); DnsServer = request.Inputs["DnsServer"].AsString(); DnsSuffix = request.Inputs["DnsSuffix"].AsString(); Domain = request.Inputs["Domain"].AsString(); NamingScheme = request.Inputs["NamingScheme"].AsString(); NamingPrefix = request.Inputs["NamingPrefix"].AsString(); Description = request.Inputs["Description"].AsString(); FullName = request.Inputs["FullName"].AsString(); OrgName = request.Inputs["OrgName"].AsString(); ChangeSid = request.Inputs["ChangeSid"].AsString(); DeleteAccounts = request.Inputs["DeleteAccounts"].AsString(); GuiRunOnce = request.Inputs["GuiRunOnce"].AsString(); AdminPassword = request.Inputs["AdminPassword"].AsString(); TimeZone = request.Inputs["TimeZone"].AsString(); AutoLogonCount = request.Inputs["AutoLogonCount"].AsString(); Workgroup = request.Inputs["Workgroup"].AsString(); DomainUsername = request.Inputs["DomainUsername"].AsString(); DomainPassword = request.Inputs["DomainPassword"].AsString(); Product = request.Inputs["Product"].AsString(); LicenseMode = request.Inputs["LicenseMode"].AsString(); LicenseMaxConnections = request.Inputs["LicenseMaxConnections"].AsString(); PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String command = "New-OSCustomizationSpec"; if (!(OSType == String.Empty)) { command += " -OSType \"" + OSType + "\""; } if (!(Name == String.Empty)) { command += " -Name \"" + Name + "\""; } if (!(DnsServer == String.Empty)) { command += " -DnsServer \"" + DnsServer + "\""; } if (!(DnsSuffix == String.Empty)) { command += " -DnsSuffix \"" + DnsSuffix + "\""; } if (!(Domain == String.Empty)) { command += " -Domain \"" + Domain + "\""; } if (!(NamingScheme == String.Empty)) { command += " -NamingScheme \"" + NamingScheme + "\""; } if (!(Description == String.Empty)) { command += " -Description \"" + Description + "\""; } if (!(NamingPrefix == String.Empty)) { command += " -NamingPrefix \"" + NamingPrefix + "\""; } if (!(FullName == String.Empty)) { command += " -FullName \"" + FullName + "\""; } if (!(OrgName == String.Empty)) { command += " -OrgName \"" + OrgName + "\""; } if (!(ChangeSid.Equals("true"))) { command += " -ChangeSid:$True"; } else { command += " -ChangeSid:$False"; } if (!(DeleteAccounts == String.Empty)) { command += " -DeleteAccounts \"" + DeleteAccounts + "\""; } if (!(GuiRunOnce == String.Empty)) { command += " -GuiRunOnce \"" + GuiRunOnce + "\""; } if (!(AdminPassword == String.Empty)) { command += " -AdminPassword \"" + AdminPassword + "\""; } if (!(TimeZone == String.Empty)) { command += " -TimeZone \"" + TimeZone + "\""; } if (!(AutoLogonCount == String.Empty)) { command += " -AutoLogonCount \"" + AutoLogonCount + "\""; } if (!(Workgroup == String.Empty)) { command += " -Workgroup \"" + Workgroup + "\""; } if (!(DomainUsername == String.Empty)) { command += " -DomainUsername \"" + DomainUsername + "\""; } if (!(DomainPassword == String.Empty)) { command += " -DomainPassword \"" + DomainPassword + "\""; } if (!(Product == String.Empty)) { command += " -Product \"" + Product + "\""; } if (!(LicenseMode == String.Empty)) { command += " -LicenseMode \"" + LicenseMode + "\""; } if (!(LicenseMaxConnections == String.Empty)) { command += " -LicenseMaxConnections \"" + LicenseMaxConnections + "\""; } Script += command + " -Confirm:$False"; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } runspace.Close(); response.Publish("Customization Spec Name", Name); }
/// <summary> /// Adds one or more snapins /// </summary> /// <param name="snapInList">List of snapin IDs</param> /// <remarks> /// This is a helper method and should not throw any /// exceptions. All exceptions are caught and displayed /// to the user using write* methods /// </remarks> private void AddPSSnapIns(Collection <string> snapInList) { if (snapInList == null) { // nothing to add return; } //BUGBUG TODO - brucepay - this is a workaround for not being able to dynamically update // the set of cmdlets in a runspace if there is no RunspaceConfiguration object. // This is a temporary fix to unblock remoting tests and need to be corrected/completed // before we can ship... // If there is no RunspaceConfig object, then // use an InitialSessionState object to gather and // bind the cmdlets from the snapins... if (Context.RunspaceConfiguration == null) { Collection <PSSnapInInfo> loadedSnapins = base.GetSnapIns(null); InitialSessionState iss = InitialSessionState.Create(); bool isAtleastOneSnapinLoaded = false; foreach (string snapIn in snapInList) { if (InitialSessionState.IsEngineModule(snapIn)) { WriteNonTerminatingError(snapIn, "LoadSystemSnapinAsModule", PSTraceSource.NewArgumentException(snapIn, MshSnapInCmdletResources.LoadSystemSnapinAsModule, snapIn), ErrorCategory.InvalidArgument); } else { PSSnapInException warning; try { // Read snapin data PSSnapInInfo newPSSnapIn = PSSnapInReader.Read(Utils.GetCurrentMajorVersion(), snapIn); PSSnapInInfo psSnapInInfo = IsSnapInLoaded(loadedSnapins, newPSSnapIn); // that means snapin is not already loaded ..so load the snapin // now. if (null == psSnapInInfo) { psSnapInInfo = iss.ImportPSSnapIn(snapIn, out warning); isAtleastOneSnapinLoaded = true; Context.InitialSessionState.ImportedSnapins.Add(psSnapInInfo.Name, psSnapInInfo); } // Write psSnapInInfo object only if passthru is specified. if (_passThru) { // Load the pssnapin info properties that are localizable and redirected in the registry psSnapInInfo.LoadIndirectResources(ResourceReader); WriteObject(psSnapInInfo); } } catch (PSSnapInException pse) { WriteNonTerminatingError(snapIn, "AddPSSnapInRead", pse, ErrorCategory.InvalidData); } } } if (isAtleastOneSnapinLoaded) { // Now update the session state with the new stuff... iss.Bind(Context, /*updateOnly*/ true); } return; } foreach (string psSnapIn in snapInList) { Exception exception = null; try { PSSnapInException warning = null; PSSnapInInfo psSnapInInfo = this.Runspace.AddPSSnapIn(psSnapIn, out warning); if (warning != null) { WriteNonTerminatingError(psSnapIn, "AddPSSnapInRead", warning, ErrorCategory.InvalidData); } // Write psSnapInInfo object only if passthru is specified. if (_passThru) { // Load the pssnapin info properties that are localizable and redirected in the registry psSnapInInfo.LoadIndirectResources(ResourceReader); WriteObject(psSnapInInfo); } } catch (PSArgumentException ae) { exception = ae; } catch (PSSnapInException sle) { exception = sle; } catch (System.Security.SecurityException se) { exception = se; } if (exception != null) { WriteNonTerminatingError(psSnapIn, "AddPSSnapInRead", exception, ErrorCategory.InvalidArgument); } } }
private IEnumerable <datastore> runCommand() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String command = "Get-Datastore"; if (!(VMHost == String.Empty)) { command += " -VMHost " + VMHost; } if (!(VM == String.Empty)) { command += " -VM " + VM; } if (!(Entity == String.Empty)) { command += " -Entity " + Entity; } if (!(Name == String.Empty)) { command += " -Name " + Name; } Script += command; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("DatastoreImpl")) { String id = obj.Members["id"].Value.ToString(); String name = obj.Members["name"].Value.ToString(); String capacityMB = obj.Members["capacityMB"].Value.ToString(); String FreeSpaceMB = obj.Members["FreeSpaceMB"].Value.ToString(); String ParentFolderId = obj.Members["ParentFolderId"].Value.ToString(); String DatacenterId = obj.Members["DatacenterId"].Value.ToString(); yield return(new datastore(capacityMB, FreeSpaceMB, ParentFolderId, DatacenterId, id, name)); } } runspace.Close(); }
protected override void ProcessRecord() { foreach (string str in this._pssnapins) { Collection <PSSnapInInfo> snapIns = base.GetSnapIns(str); if (snapIns.Count == 0) { base.WriteNonTerminatingError(str, "NoPSSnapInsFound", PSTraceSource.NewArgumentException(str, "MshSnapInCmdletResources", "NoPSSnapInsFound", new object[] { str }), ErrorCategory.InvalidArgument); } else { foreach (PSSnapInInfo info in snapIns) { if (base.ShouldProcess(info.Name)) { Exception innerException = null; if ((base.Runspace == null) && (base.Context.InitialSessionState != null)) { try { PSSnapInException exception2; PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(info.Name); if (MshConsoleInfo.IsDefaultPSSnapIn(info.Name, base.Context.InitialSessionState.defaultSnapins)) { throw PSTraceSource.NewArgumentException(info.Name, "ConsoleInfoErrorStrings", "CannotRemoveDefault", new object[] { info.Name }); } InitialSessionState state = InitialSessionState.Create(); state.ImportPSSnapIn(info, out exception2); state.Unbind(base.Context); base.Context.InitialSessionState.ImportedSnapins.Remove(info.Name); } catch (PSArgumentException exception3) { innerException = exception3; } if (innerException != null) { base.WriteNonTerminatingError(str, "RemovePSSnapIn", innerException, ErrorCategory.InvalidArgument); } } else { try { PSSnapInException warning = null; PSSnapInInfo sendToPipeline = base.Runspace.RemovePSSnapIn(info.Name, out warning); if (warning != null) { base.WriteNonTerminatingError(info.Name, "RemovePSSnapInRead", warning, ErrorCategory.InvalidData); } if (this._passThru) { sendToPipeline.LoadIndirectResources(base.ResourceReader); base.WriteObject(sendToPipeline); } } catch (PSArgumentException exception5) { innerException = exception5; } if (innerException != null) { base.WriteNonTerminatingError(str, "RemovePSSnapIn", innerException, ErrorCategory.InvalidArgument); } } } } } } }
private IEnumerable <networkAdapter> runCommand() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String preCommand = "Get-NetworkAdapter"; if (!(VM == String.Empty)) { preCommand += " -VM \"" + VM + "\" | ? {$_.Name -eq \"" + NetworkAdapter + "\"}"; } String command = "Set-NetworkAdapter"; if (!(MacAddress == String.Empty)) { command += " -MacAddress \"" + MacAddress + "\""; } if (!(NetworkName == String.Empty)) { command += " -NetworkName \"" + NetworkName + "\""; } if (StartConnected.Equals("true")) { command += " -StartConnected:$True"; } else { command += " -StartConnected:$False"; } if (Connected.Equals("true")) { command += " -Connected:$True"; } else { command += " -Connected $False"; } if (WakeOnLan.Equals("true")) { command += " -WakeOnLan"; } Script += preCommand + " | " + command + " -confirm:$False"; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("NetworkAdapterImpl")) { String Mac_Address = obj.Members["MacAddress"].Value.ToString(); String WakeOnLanEnabled = obj.Members["WakeOnLanEnabled"].Value.ToString(); String Network_Name = obj.Members["NetworkName"].Value.ToString(); String ParentId = obj.Members["ParentId"].Value.ToString(); String Id = obj.Members["Id"].Value.ToString(); String Name = obj.Members["Name"].Value.ToString(); yield return(new networkAdapter(Mac_Address, WakeOnLanEnabled, Network_Name, ParentId, Id, Name)); } } runspace.Close(); }
private IEnumerable <vm> getVM() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String command = "New-VM"; String preCommand = ""; if (!(Name == String.Empty)) { command += " -Name \"" + Name + "\""; } if (!(VMHost == String.Empty)) { preCommand += "$VMHost = Get-VMHost \"" + VMHost + "\"\n"; command += " -VMHost $VMHost"; } if (!(VMFilePath == String.Empty)) { command += " -VMFilePath \"" + VMFilePath + "\""; } if (!(Folder == String.Empty)) { command += " -Location \"" + Folder + "\""; } if (!(ResourcePool == String.Empty)) { preCommand += "$ResourcePool = Get-ResourcePool \"" + ResourcePool + "\"\n"; command += " -ResourcePool $ResourcePool"; } if (!(VApp == String.Empty)) { preCommand += "$VApp = Get-VApp \"" + VApp + "\"\n"; command += " -VApp $VApp"; } if (!(Datastore == String.Empty)) { preCommand += "$Datastore = Get-Datastore \"" + Datastore + "\"\n"; command += " -Datastore $Datastore"; } if (!(DiskMB == String.Empty)) { command += " -DiskMB \"" + DiskMB + "\""; } if (!(DiskPath == String.Empty)) { command += " -DiskPath \"" + DiskPath + "\""; } if (!(DiskStorageFormat == String.Empty)) { command += " -DiskStorageFormat \"" + DiskStorageFormat + "\""; } if (!(MemoryMB == String.Empty)) { command += " -MemoryMB \"" + MemoryMB + "\""; } if (!(NumCpu == String.Empty)) { command += " -NumCpu \"" + NumCpu + "\""; } if (!(AlternateGuestName == String.Empty)) { command += " -AlternateGuestName \"" + AlternateGuestName + "\""; } if (!(NetworkName == String.Empty)) { command += " -NetworkName \"" + NetworkName + "\""; } if (!(HARestartPriority == String.Empty)) { command += " -HARestartPriority \"" + HARestartPriority + "\""; } if (!(HAIsolationResponse == String.Empty)) { command += " -HAIsolationResponse \"" + HAIsolationResponse + "\""; } if (!(DRSAutomationLevel == String.Empty)) { command += " -DRSAutomationLevel \"" + DRSAutomationLevel + "\""; } if (!(VMSwapfilePolicy == String.Empty)) { command += " -VMSwapfilePolicy \"" + VMSwapfilePolicy + "\""; } if (!(Description == String.Empty)) { command += " -Description \"" + Description + "\""; } if (!(OSCustomizationSpec == String.Empty)) { command += " -OSCustomizationSpec \"" + OSCustomizationSpec + "\""; } if (!(VM == String.Empty)) { preCommand += "$VM = Get-VM \"" + VM + "\"\n"; command += " -VM $VM"; } if (!(Template == String.Empty)) { preCommand += "$Template = Get-Template \"" + Template + "\"\n"; command += " -Template $Template"; } if (floppy.Equals("true")) { command += " -floppy"; } if (CD.Equals("true")) { command += " -CD"; } if (!(GuestId == String.Empty)) { switch (GuestId) { case "Asianux Server 3 64 bit": command += " -GuestId asianux3_64Guest"; break; case "Asianux Server 3": command += " -GuestId asianux3Guest"; break; case "Asianux Server 4 64 bit": command += " -GuestId asianux4_64Guest"; break; case "Asianux Server 4": command += " -GuestId asianux4Guest"; break; case "Darwin 64 bit": command += " -GuestId darwin64Guest"; break; case "Darwin": command += " -GuestId darwinGuest"; break; case "Debian GNU/Linux 4 64 bit": command += " -GuestId debian4_64Guest"; break; case "Debian GNU/Linux 4": command += " -GuestId debian4Guest"; break; case "Debian GNU/Linux 5 64 bit": command += " -GuestId debian5_64Guest"; break; case "Debian GNU/Linux 5": command += " -GuestId debian5Guest"; break; case "MS-DOS": command += " -GuestId dosGuest"; break; case "FreeBSD x64": command += " -GuestId freebsd64Guest"; break; case "FreeBSD": command += " -GuestId freebsdGuest"; break; case "Mandriva Linux": command += " -GuestId mandrivaGuest"; break; case "Novell NetWare 4": command += " -GuestId netware4Guest"; break; case "Novell NetWare 5.1": command += " -GuestId netware5Guest"; break; case "Novell NetWare 6.x": command += " -GuestId netware6Guest"; break; case "Novell Linux Desktop 9": command += " -GuestId nld9Guest"; break; case "Open Enterprise Server": command += " -GuestId oesGuest"; break; case "SCO OpenServer 5": command += " -GuestId openServer5Guest"; break; case "SCO OpenServer 6": command += " -GuestId openServer6Guest"; break; case "OS/2": command += " -GuestId os2Guest"; break; case "Linux 2.4x Kernel (64 bit) (experimental)": command += " -GuestId other24xLinux64Guest"; break; case "Linux 2.4x Kernel": command += " -GuestId other24xLinuxGuest"; break; case "Linux 2.6x Kernel (64 bit) (experimental)": command += " -GuestId other26xLinux64Guest"; break; case "Linux 2.6x Kernel": command += " -GuestId other26xLinuxGuest"; break; case "Other Operating System": command += " -GuestId otherGuest"; break; case "Other Operating System (64 bit) (experimental)": command += " -GuestId otherGuest64"; break; case "Linux (64 bit) (experimental)": command += " -GuestId otherLinux64Guest "; break; case "Other Linux": command += " -GuestId otherLinuxGuest"; break; case "Red Hat Linux 2.1": command += " -GuestId redhatGuest"; break; case "Red Hat Enterprise Linux 2": command += " -GuestId rhel2Guest"; break; case "Red Hat Enterprise Linux 3 (64 bit)": command += " -GuestId rhel3_64Guest"; break; case "Red Hat Enterprise Linux 3": command += " -GuestId rhel3Guest"; break; case "Red Hat Enterprise Linux 4 (64 bit)": command += " -GuestId rhel4_64Guest"; break; case "Red Hat Enterprise Linux 4": command += " -GuestId rhel4Guest"; break; case "Red Hat Enterprise Linux 5 (64 bit) (experimental)": command += " -GuestId rhel5_64Guest"; break; case "Red Hat Enterprise Linux 5": command += " -GuestId rhel5Guest"; break; case "Red Hat Enterprise Linux 6 (64 bit)": command += " -GuestId rhel6_64Guest"; break; case "Red Hat Enterprise Linux 6": command += " -GuestId rhel6Guest"; break; case "Sun Java Desktop System": command += " -GuestId sjdsGuest"; break; case "Suse Linux Enterprise Server 10 (64 bit) (experimental)": command += " -GuestId sles10_64Guest"; break; case "Suse linux Enterprise Server 10": command += " -GuestId sles10Guest"; break; case "Suse Linux Enterprise Server 11 (64 bit)": command += " -GuestId sles11_64Guest"; break; case "Suse linux Enterprise Server 11": command += " -GuestId sles11Guest"; break; case "Suse Linux Enterprise Server 9 (64 bit)": command += " -GuestId sles64Guest"; break; case "Suse Linux Enterprise Server 9": command += " -GuestId slesGuest"; break; case "Solaris 10 (64 bit) (experimental)": command += " -GuestId solaris10_64Guest"; break; case "Solaris 10 (32 bit) (experimental)": command += " -GuestId solaris10Guest"; break; case "Solaris 6": command += " -GuestId solaris6Guest"; break; case "Solaris 7": command += " -GuestId solaris7Guest"; break; case "Solaris 8": command += " -GuestId solaris8Guest"; break; case "solaris 9": command += " -GuestId solaris9Guest"; break; case "Suse Linux (64 bit)": command += " -GuestId suse64Guest"; break; case "Suse Linux": command += " -GuestId suseGuest"; break; case "Turbolinux (64 bit)": command += " -GuestId turboLinux64Guest"; break; case "Turbolinux": command += " -GuestId turboLinuxGuest"; break; case "Ubuntu Linux (64 bit)": command += " -GuestId ubuntu64Guest"; break; case "Ubuntu Linux": command += " -GuestId ubuntuGuest"; break; case "SCO UnixWare 7": command += " -GuestId unixWare7Guest"; break; case "Windows 2000 Advanced Server": command += " -GuestId win2000AdvServGuest"; break; case "Windows 2000 Professional": command += " -GuestId win2000ProGuest"; break; case "Windows 2000 Server": command += " -GuestId win2000ServGuest"; break; case "Windows 3.1": command += " -GuestId win31Guest"; break; case "Windows 95": command += " -GuestId win95Guest"; break; case "Windows 98": command += " -GuestId win98Guest"; break; case "Windows 7 (64 bit)": command += " -GuestId windows7_64Guest"; break; case "Windows 7": command += " -GuestId windows7Guest"; break; case "Windows Server 2008 R2 (64 bit)": command += " -GuestId windows7Server64Guest"; break; case "Windows Longhorn (64 bit) (experimental)": command += " -GuestId winLonghorn64Guest"; break; case "Windows Longhorn (experimental)": command += " -GuestId winLonghornGuest"; break; case "Windows Millenium Edition": command += " -GuestId winMeGuest"; break; case "Windows Small Business Server 2003": command += " -GuestId winNetBusinessGuest"; break; case "Windows Server 2003, Datacenter Edition (64 bit) (experimental)": command += " -GuestId winNetDatacenter64Guest"; break; case "Windows Server 2003, Datacenter Edition": command += " -GuestId winNetDatacenterGuest"; break; case "Windows Server 2003, Enterprise Edition (64 bit)": command += " -GuestId winNetEnterprise64Guest"; break; case "Windows Server 2003, Enterprise Edition": command += " -GuestId winNetEnterpriseGuest"; break; case "Windows Server 2003, Standard Edition (64 bit)": command += " -GuestId winNetStandard64Guest"; break; case "Windows Server 2003, Standard Edition": command += " -GuestId winNetStandardGuest"; break; case "Windows Server 2003, Web Edition": command += " -GuestId winNetWebGuest"; break; case "Windows NT 4": command += " -GuestId winNTGuest"; break; case "Windows Vista (64 bit)": command += " -GuestId winVista64Guest"; break; case "Windows Vista": command += " -GuestId winVistaGuest"; break; case "Windows XP Home Edition": command += " -GuestId winXPHomeGuest"; break; case "Windows XP Professional Edition (64 bit)": command += " -GuestId winXPPro64Guest"; break; case "Windows XP Professional": command += " -GuestId winXPProGuest"; break; } } Script += preCommand + command + " -Confirm:$False"; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl")) { String PowerState = obj.Members["PowerState"].Value.ToString(); String VMVersion = obj.Members["Version"].Value.ToString(); String Number_Cpu = obj.Members["NumCpu"].Value.ToString(); String Memory_MB = obj.Members["MemoryMB"].Value.ToString(); String HostId = obj.Members["HostId"].Value.ToString(); String FolderId = obj.Members["FolderId"].Value.ToString(); String ResourcePoolId = obj.Members["ResourcePoolId"].Value.ToString(); String UsedSpaceGB = obj.Members["UsedSpaceGB"].Value.ToString(); String ProvisionedSpaceGB = obj.Members["ProvisionedSpaceGB"].Value.ToString(); String id = obj.Members["Id"].Value.ToString(); String name = obj.Members["Name"].Value.ToString(); String VM_Description = String.Empty; String Notes = String.Empty; try { VM_Description = obj.Members["Description"].Value.ToString(); } catch { } try { Notes = obj.Members["Notes"].Value.ToString(); } catch { } yield return(new vm(PowerState, VMVersion, VM_Description, Notes, Number_Cpu, Memory_MB, HostId, FolderId, ResourcePoolId, UsedSpaceGB, ProvisionedSpaceGB, id, name)); } } runspace.Close(); }
public void Execute(IActivityRequest request, IActivityResponse response) { userName = settings.UserName; password = settings.Password; domain = settings.Domain; port = settings.Port; virtualCenter = settings.VirtualCenter; ScriptText = request.Inputs["ScriptText"].AsString(); VM = request.Inputs["VM"].AsString(); VM = request.Inputs["HostUser"].AsString(); VM = request.Inputs["HostPassword"].AsString(); VM = request.Inputs["GuestUser"].AsString(); VM = request.Inputs["GuestPassword"].AsString(); VM = request.Inputs["ToolsWaitSecs"].AsString(); VM = request.Inputs["ScriptType"].AsString(); PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String command = "Invoke-VMScript"; if (!(ScriptText == String.Empty)) { command += " -ScriptText '" + ScriptText + "'"; } if (!(VM == String.Empty)) { command += " -VM " + VM; } if (!(HostUser == String.Empty)) { command += " -HostUser " + HostUser; } if (!(HostPassword == String.Empty)) { command += " -HostPassword " + HostPassword; } if (!(GuestUser == String.Empty)) { command += " -GuestUser " + GuestUser; } if (!(ToolsWaitSecs == String.Empty)) { command += " -ToolsWaitSecs " + ToolsWaitSecs; } if (!(ScriptType == String.Empty)) { command += " -ScriptType " + ScriptType; } Script += command + " -confirm:$False"; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } response.Publish("ScriptResult", results.ToString()); }
private IEnumerable <vm> runCommand() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String command = "Move-VM"; String preCommand = ""; if (!(VM == String.Empty)) { command += " -VM \"" + VM + "\""; } if (!(Folder == String.Empty)) { preCommand += "$Folder = Get-Folder \"" + Folder + "\"\n"; command += " -Destination $Folder"; } if (!(Host == String.Empty)) { preCommand += "$Host = Get-VMHost \"" + Host + "\"\n"; command += " -Destination $Host"; } if (!(ResourcePool == String.Empty)) { preCommand += "$Folder = Get-ResourcePool \"" + ResourcePool + "\"\n"; command += " -Destination $ResourcePool"; } if (!(Datastore == String.Empty)) { command += " -Datastore \"" + Datastore + "\""; } Script += command + " -confirm:$False"; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { results.Add(new PSObject((object)ex.Message)); } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl")) { String PowerState = obj.Members["PowerState"].Value.ToString(); String VMVersion = obj.Members["Version"].Value.ToString(); String NumCpu = obj.Members["NumCpu"].Value.ToString(); String MemoryMB = obj.Members["MemoryMB"].Value.ToString(); String HostId = obj.Members["HostId"].Value.ToString(); String FolderId = obj.Members["FolderId"].Value.ToString(); String ResourcePoolId = obj.Members["ResourcePoolId"].Value.ToString(); String UsedSpaceGB = obj.Members["UsedSpaceGB"].Value.ToString(); String ProvisionedSpaceGB = obj.Members["ProvisionedSpaceGB"].Value.ToString(); String id = obj.Members["Id"].Value.ToString(); String name = obj.Members["Name"].Value.ToString(); String Description = String.Empty; String Notes = String.Empty; try { Description = obj.Members["Description"].Value.ToString(); } catch { } try { Notes = obj.Members["Notes"].Value.ToString(); } catch { } yield return(new vm(PowerState, VMVersion, Description, Notes, NumCpu, MemoryMB, HostId, FolderId, ResourcePoolId, UsedSpaceGB, ProvisionedSpaceGB, id, name)); } } runspace.Close(); }
private IEnumerable <cluster> getCluster() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String command = "Get-Cluster"; if (!(VM == String.Empty)) { command += " -VM " + VM; } if (!(VMHost == String.Empty)) { command += " -VMHost " + VMHost; } if (!(Location == String.Empty)) { command += " -Location " + Location; } if (!(Name == String.Empty)) { command += " -Name " + Name; } if (!(Id == String.Empty)) { command += " -Id " + Id; } Script += command; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("ClusterImpl")) { String HAEnabled = obj.Members["HAEnabled"].Value.ToString(); String HAAdmissionControlEnabled = obj.Members["HAAdmissionControlEnabled"].Value.ToString(); String HAFailoverLevel = obj.Members["HAFailoverLevel"].Value.ToString(); String HARestartPriority = obj.Members["HARestartPriority"].Value.ToString(); String HAIsolationResponse = obj.Members["HAIsolationResponse"].Value.ToString(); String VMSwapFilePolicy = obj.Members["VMSwapFilePolicy"].Value.ToString(); String DrsEnabled = obj.Members["DrsEnabled"].Value.ToString(); String DrsMode = obj.Members["DrsMode"].Value.ToString(); String DrsAutomationLevel = obj.Members["DrsAutomationLevel"].Value.ToString(); String id = obj.Members["Id"].Value.ToString(); String name = obj.Members["Name"].Value.ToString(); yield return(new cluster(HAEnabled, HAAdmissionControlEnabled, HAFailoverLevel, HARestartPriority, HAIsolationResponse, VMSwapFilePolicy, DrsEnabled, DrsMode, DrsAutomationLevel, id, name)); } } runspace.Close(); }
/// <summary> /// Create the Runspace pool. /// For remote runspaces, load the datatypes optionally to support serialization /// For local commands, load the modules and snapins required or requested /// </summary> /// <param name="commandInfo"></param> /// <param name="pSHost"></param> /// <param name="maxRunspaces"></param> /// <param name="debugStrings"></param> /// <param name="useRemotePS"></param> /// <param name="loadAllTypedata"></param> /// <param name="modules"></param> /// <param name="modulesPath"></param> /// <param name="snapIns"></param> /// <param name="variableEntries"></param> /// <returns></returns> internal static RunspacePool CreateRunspacePool(CommandInfo commandInfo, PSHost pSHost, int maxRunspaces, out List <string> debugStrings, PSSession useRemotePS, bool loadAllTypedata, string[] modules = null, string[] modulesPath = null, string[] snapIns = null, IList <SessionStateVariableEntry> variableEntries = null) { debugStrings = new List <string>(); RunspaceConnectionInfo runspaceConnectionInfo = null; Hashtable modulePrivatedata = commandInfo.Module?.PrivateData as Hashtable; ModuleDetails moduleDetails = GetModuleDetails(commandInfo, debugStrings); //special handling for remote PSsession commands if (moduleDetails.IsFromRemotingModule || useRemotePS != null) { if (useRemotePS != null) { debugStrings.Add("Using the supplied remote PSSession"); runspaceConnectionInfo = useRemotePS.Runspace.ConnectionInfo; } else { debugStrings.Add("Using remote PSSession to execute the command"); PSObject remotepSModule = ScriptBlock.Create( string.Format("Get-Module {0}", commandInfo.ModuleName)).InvokeReturnAsIs() as PSObject; if (remotepSModule.BaseObject is PSModuleInfo remotepSModuleInfo) { PSObject remotePs = ScriptBlock.Create( string.Format("Get-PSSession | Where-Object{{$_.state -eq 'opened' -and (\"{0}\").Contains($_.ComputerName)}} | Select-Object -First 1", remotepSModuleInfo.Description)).InvokeReturnAsIs() as PSObject; if (remotePs.BaseObject is PSSession remotePSSession) { runspaceConnectionInfo = remotePSSession.Runspace.ConnectionInfo; if (modules != null || modulesPath != null) { debugStrings.Add("Modules were specified to load, but they will not be loaded as the command supplied is from a remote PSSession"); } } else { debugStrings.Add(string.Format("Command - Get-PSSession | Where-Object{{$_.state -eq 'opened' -and (\"{0}\").Contains($_.ComputerName)}} " + "| Select-Object -First 1 - was ran to find the PSSession", remotepSModuleInfo.Description)); throw new Exception("Unable to find a PSSession to use. You may try passing the PSSession to use using Parameter -UseRemotePSSession"); } } } debugStrings.Add(string.Format("Using connection info {0}", runspaceConnectionInfo.ComputerName)); TypeTable typeTable = TypeTable.LoadDefaultTypeFiles(); if (loadAllTypedata) { Collection <PSObject> typeDatas = ScriptBlock.Create("Get-TypeData").Invoke(); foreach (PSObject typeData in typeDatas) { TypeData t = (TypeData)typeData.BaseObject; try { typeTable.AddType(t); debugStrings.Add(string.Format("Added typedata{0}", t.TypeName)); } catch (Exception e) { debugStrings.Add(string.Format("Unable to add typeData {0}. Error {1}", t.TypeName, e.Message)); } } } return(RunspaceFactory.CreateRunspacePool(1, Environment.ProcessorCount, runspaceConnectionInfo, pSHost, typeTable)); } InitialSessionState iss = InitialSessionState.CreateDefault2(); List <string> modulesToLoad = new List <String>(); List <string> snapInsToLoad = new List <string>(); PSSnapInException pSSnapInException = new PSSnapInException(); if (modules?.Count() > 0) { modulesToLoad.AddRange(modules); } if (snapIns?.Count() > 0) { snapInsToLoad.AddRange(snapIns); } //Populate ISS with the snapins and modules from the moduleDetails LoadISSWithModuleDetails(moduleDetails, iss); //Load user specified snapins and modules if (modules?.Count() > 0 && modules.Contains("All", StringComparer.OrdinalIgnoreCase)) { var modulesAvailable = ScriptBlock.Create("Get-Module -ListAvailable | Select-Object -ExpandProperty Name").Invoke(); modulesToLoad.AddRange(from module in modulesAvailable select module.BaseObject as string); debugStrings.Add(string.Format("Loaded all the available modules on this computer, {0} modules found", modulesToLoad.Count)); } if (modules?.Count() > 0 && modules.Contains("Loaded", StringComparer.OrdinalIgnoreCase)) { var modulesLoaded = ScriptBlock.Create("Get-Module | Select-Object -ExpandProperty Name").Invoke(); modulesToLoad.AddRange(from module in modulesLoaded select module.BaseObject as string); debugStrings.Add(string.Format("Loaded the modules loaded on current Runspace, {0} modules found", modulesLoaded.Count)); } debugStrings.Add("Loading Modules:"); debugStrings.AddRange(modulesToLoad); iss.ImportPSModule(modulesToLoad.ToArray()); snapInsToLoad.ForEach(s => iss.ImportPSSnapIn(s, out pSSnapInException)); if (variableEntries != null) { iss.Variables.Add(variableEntries); } return(RunspaceFactory.CreateRunspacePool(1, maxRunspaces, iss, pSHost)); }
private IEnumerable <harddisk> runCommand() { PSSnapInException warning = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.RunspaceConfiguration.AddPSSnapIn("VMware.VimAutomation.Core", out warning); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); String Script = "Connect-VIServer -Server " + virtualCenter + " -Port " + port + " -User " + domain + "\\" + userName + " -Password " + password + "\n"; String preCommand = "Get-HardDisk"; if (!(VMName == String.Empty)) { preCommand += " -VM \"" + VMName + "\""; } String command = "Set-HardDisk"; if (!(CapacityKB == String.Empty)) { command += " -CapacityKB \"" + CapacityKB + "\""; } if (!(Persistence == String.Empty)) { command += " -Persistence \"" + Persistence + "\""; } if (!(Datastore == String.Empty)) { command += " -Datastore \"" + Datastore + "\""; } if (!(StorageFormat == String.Empty)) { command += " -StorageFormat \"" + StorageFormat + "\""; } if (!(HostUser == String.Empty)) { command += " -HostUser \"" + HostUser + "\""; } if (!(HostPassword == String.Empty)) { command += " -HostPassword \"" + HostPassword + "\""; } if (!(GuestUser == String.Empty)) { command += " -GuestUser \"" + GuestUser + "\""; } if (!(GuestPassword == String.Empty)) { command += " -GuestPassword \"" + GuestPassword + "\""; } if (!(ToolsWaitSecs == String.Empty)) { command += " -ToolsWaitSecs \"" + ToolsWaitSecs + "\""; } if (!(HelperVM == String.Empty)) { command += " -HelperVM \"" + HelperVM + "\""; } if (!(Partition == String.Empty)) { command += " -Partition \"" + Partition + "\""; } if (Inflate.Equals("true")) { command += " -Inflate"; } Script += preCommand + " | " + command + " -Confirm:$False"; pipeline.Commands.AddScript(Script); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (Exception ex) { throw ex; } foreach (PSObject obj in results) { if (obj.BaseObject.GetType().ToString().Contains("DiskImpl")) { yield return(new harddisk(obj)); } } runspace.Close(); }