public override void SetSessionOptions(PSSessionOption options) { if (options == null) { throw new ArgumentNullException("options"); } if ((options.ProxyAccessType == System.Management.Automation.Remoting.ProxyAccessType.None) && (options.ProxyCredential != null)) { throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ProxyCredentialWithoutAccess, new object[] { System.Management.Automation.Remoting.ProxyAccessType.None })); } base.SetSessionOptions(options); this.MaximumConnectionRedirectionCount = (options.MaximumConnectionRedirectionCount >= 0) ? options.MaximumConnectionRedirectionCount : 0x7fffffff; this.MaximumReceivedDataSizePerCommand = options.MaximumReceivedDataSizePerCommand; this.MaximumReceivedObjectSize = options.MaximumReceivedObjectSize; this.UseCompression = !options.NoCompression; this.NoMachineProfile = options.NoMachineProfile; this._proxyAcessType = options.ProxyAccessType; this._proxyAuthentication = options.ProxyAuthentication; this._proxyCredential = options.ProxyCredential; this._skipCaCheck = options.SkipCACheck; this._skipCnCheck = options.SkipCNCheck; this._skipRevocationCheck = options.SkipRevocationCheck; this._noEncryption = options.NoEncryption; this._useUtf16 = options.UseUTF16; this._includePortInSPN = options.IncludePortInSPN; this._outputBufferingMode = options.OutputBufferingMode; }
public MSActorReturnMessageModel GetMoveRequest(string identity) { // Multiple paths to error MSActorReturnMessageModel errorMessage; try { PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { using (Runspace runspace = RunspaceFactory.CreateRunspace()) { powershell.Runspace = runspace; runspace.Open(); ConnectToExchange(powershell, runspace); PSCommand command = new PSCommand(); command.AddCommand("Get-MoveRequest"); command.AddParameter("Identity", identity); powershell.Commands = command; Collection <PSObject> existingMoveRequests = powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { // Here we are throwing an error on purpose if a move request does not exist throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); string status = existingMoveRequests[0].Properties["Status"].Value.ToString() as string; switch (status) { case "Completed": MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); case "InProgress": case "Queued": MSActorReturnMessageModel pendingMessage = new MSActorReturnMessageModel(PendingCode, ""); return(pendingMessage); default: string errorString = "Move request status is '" + status + "'"; errorMessage = new MSActorReturnMessageModel(ErrorCode, errorString); Debug.WriteLine("ERROR: " + errorString); return(errorMessage); } } } } catch (Exception e) { return(util.ReportError(e)); } }
public SessionEntry(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption) { SessionOptions = sessionOptions; _credential = credential; _certificateThumbprint = certificateThumbprint; _authenticationMechanism = authenticationMechanism; _useSsl = useSsl; _port = port; _psSessionOption = pssessionOption; Session = CimSession.Create(computerName, sessionOptions); }
protected override List <ActivityImplementationContext> GetImplementation(NativeActivityContext context) { bool hasValue; string[] strArrays = this.PSComputerName.Get(context); string[] strArrays1 = this.PSConnectionUri.Get(context); PSSessionOption pSSessionOption = this.PSSessionOption.Get(context); List <ActivityImplementationContext> activityImplementationContexts = new List <ActivityImplementationContext>(); RemotingBehavior remotingBehavior = this.PSRemotingBehavior.Get(context); if (this.PSRemotingBehavior.Expression == null) { remotingBehavior = RemotingBehavior.PowerShell; } if (remotingBehavior != RemotingBehavior.Custom || this.SupportsCustomRemoting) { if (this.PSCredential.Get(context) != null) { AuthenticationMechanism?nullable = this.PSAuthentication.Get(context); if (nullable.GetValueOrDefault() != AuthenticationMechanism.NegotiateWithImplicitCredential) { hasValue = false; } else { hasValue = nullable.HasValue; } if (hasValue) { throw new ArgumentException(Resources.CredentialParameterCannotBeSpecifiedWithNegotiateWithImplicitAuthentication); } } if ((remotingBehavior == RemotingBehavior.PowerShell || PSActivity.IsActivityInlineScript(this) && base.RunWithCustomRemoting(context)) && (this.GetIsComputerNameSpecified(context) || strArrays1 != null && (int)strArrays1.Length > 0)) { AuthenticationMechanism?nullable1 = this.PSAuthentication.Get(context); bool?nullable2 = this.PSAllowRedirection.Get(context); List <WSManConnectionInfo> connectionInfo = ActivityUtils.GetConnectionInfo(strArrays, strArrays1, this.PSCertificateThumbprint.Get(context), this.PSConfigurationName.Get(context), this.PSUseSsl.Get(context), this.PSPort.Get(context), this.PSApplicationName.Get(context), this.PSCredential.Get(context), nullable1.GetValueOrDefault(AuthenticationMechanism.Default), nullable2.GetValueOrDefault(false), pSSessionOption); foreach (WSManConnectionInfo wSManConnectionInfo in connectionInfo) { this.CreatePowerShellInstance(context, wSManConnectionInfo, activityImplementationContexts); } } else { this.CreatePowerShellInstance(context, null, activityImplementationContexts); } return(activityImplementationContexts); } else { throw new ArgumentException(Resources.CustomRemotingNotSupported); } }
protected override List <ActivityImplementationContext> GetImplementation(NativeActivityContext context) { string[] computernames = PSComputerName.Get(context); string[] connectionUris = PSConnectionUri.Get(context); PSSessionOption sessionOptions = PSSessionOption.Get(context); List <ActivityImplementationContext> commands = new List <ActivityImplementationContext>(); // Configure the remote connectivity options RemotingBehavior remotingBehavior = PSRemotingBehavior.Get(context); if (PSRemotingBehavior.Expression == null) { remotingBehavior = RemotingBehavior.PowerShell; } // If they've specified the 'Custom' remoting behavior, ensure the activity // supports it. if ((remotingBehavior == RemotingBehavior.Custom) && (!SupportsCustomRemoting)) { throw new ArgumentException(Resources.CustomRemotingNotSupported); } if (PSCredential.Get(context) != null && PSAuthentication.Get(context) == AuthenticationMechanism.NegotiateWithImplicitCredential) { throw new ArgumentException(Resources.CredentialParameterCannotBeSpecifiedWithNegotiateWithImplicitAuthentication); } // we need connection info to be populated even for the custom remoting case. // This is because the ComputerName is picked up from the connection info field if ((remotingBehavior == RemotingBehavior.PowerShell || (IsActivityInlineScript(this) && RunWithCustomRemoting(context))) && (GetIsComputerNameSpecified(context) || (connectionUris != null && connectionUris.Length > 0))) { List <WSManConnectionInfo> connectionInfo = ActivityUtils.GetConnectionInfo( computernames, connectionUris, PSCertificateThumbprint.Get(context), PSConfigurationName.Get(context), PSUseSsl.Get(context), PSPort.Get(context), PSApplicationName.Get(context), PSCredential.Get(context), PSAuthentication.Get(context).GetValueOrDefault(AuthenticationMechanism.Default), PSAllowRedirection.Get(context).GetValueOrDefault(false), sessionOptions); foreach (WSManConnectionInfo connection in connectionInfo) { CreatePowerShellInstance(context, connection, commands); } } // Configure the local invocation options else { CreatePowerShellInstance(context, null, commands); } return(commands); }
protected override void BeginProcessing() { PSSessionOption sendToPipeline = new PSSessionOption { ProxyAccessType = this.ProxyAccessType, ProxyAuthentication = this.ProxyAuthentication, ProxyCredential = this.ProxyCredential, SkipCACheck = (bool)this.SkipCACheck, SkipCNCheck = (bool)this.SkipCNCheck, SkipRevocationCheck = (bool)this.SkipRevocationCheck }; if (this.operationtimeout.HasValue) { sendToPipeline.OperationTimeout = TimeSpan.FromMilliseconds((double)this.operationtimeout.Value); } sendToPipeline.NoEncryption = (bool)this.NoEncryption; sendToPipeline.UseUTF16 = (bool)this.UseUTF16; sendToPipeline.IncludePortInSPN = (bool)this.IncludePortInSPN; if (this.maximumRedirection.HasValue) { sendToPipeline.MaximumConnectionRedirectionCount = this.MaximumRedirection; } sendToPipeline.NoCompression = this.NoCompression.IsPresent; sendToPipeline.NoMachineProfile = this.NoMachineProfile.IsPresent; sendToPipeline.MaximumReceivedDataSizePerCommand = this.maxRecvdDataSizePerCommand; sendToPipeline.MaximumReceivedObjectSize = this.maxRecvdObjectSize; if (this.Culture != null) { sendToPipeline.Culture = this.Culture; } if (this.UICulture != null) { sendToPipeline.UICulture = this.UICulture; } if (this.openTimeout.HasValue) { sendToPipeline.OpenTimeout = TimeSpan.FromMilliseconds((double)this.openTimeout.Value); } if (this.cancelTimeout.HasValue) { sendToPipeline.CancelTimeout = TimeSpan.FromMilliseconds((double)this.cancelTimeout.Value); } if (this.idleTimeout.HasValue) { sendToPipeline.IdleTimeout = TimeSpan.FromMilliseconds((double)this.idleTimeout.Value); } sendToPipeline.OutputBufferingMode = this.outputBufferingMode; if (this.ApplicationArguments != null) { sendToPipeline.ApplicationArguments = this.ApplicationArguments; } base.WriteObject(sendToPipeline); }
public MSActorReturnMessageModel NewDirectory(string computername, string path) { try { MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, ""); PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { string url = String.Format("http://{0}:5985/wsman", computername); Uri uri = new Uri(url); WSManConnectionInfo conn = new WSManConnectionInfo(uri); using (Runspace runspace = RunspaceFactory.CreateRunspace(conn)) { powershell.Runspace = runspace; runspace.Open(); PSCommand command = new PSCommand(); command.AddCommand("New-Item"); command.AddParameter("ItemType", "directory"); command.AddParameter("Path", path); powershell.Commands = command; Collection <PSObject> returns = powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { if (powershell.Streams.Error[0].Exception.Message == String.Format("Item with specified name {0} already exists.", path)) { return(successMessage); } else { throw powershell.Streams.Error[0].Exception; } } powershell.Streams.ClearStreams(); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }
public virtual void SetSessionOptions(PSSessionOption options) { if (options == null) { throw new ArgumentNullException("options"); } if (options.Culture != null) { this.Culture = options.Culture; } if (options.UICulture != null) { this.UICulture = options.UICulture; } this.openTimeout = this.TimeSpanToTimeOutMs(options.OpenTimeout); this.cancelTimeout = this.TimeSpanToTimeOutMs(options.CancelTimeout); this.operationTimeout = this.TimeSpanToTimeOutMs(options.OperationTimeout); this.idleTimeout = ((options.IdleTimeout.TotalMilliseconds >= -1.0) && (options.IdleTimeout.TotalMilliseconds < 2147483647.0)) ? ((int)options.IdleTimeout.TotalMilliseconds) : 0x7fffffff; }
public Runspace ConnectRemotePSSession(string serverpath) { PSSessionOption option = new PSSessionOption(); string url = serverpath; System.Uri uri = new Uri(url); Runspace runspace = RunspaceFactory.CreateRunspace(); PowerShell powershell = PowerShell.Create(); PSCommand command = new PSCommand(); command.AddCommand("New-PSSession"); command.AddParameter("ConfigurationName", "Microsoft.Exchange"); command.AddParameter("ConnectionUri", uri); command.AddParameter("Authentication", "Default"); powershell.Commands = command; runspace.Open(); powershell.Runspace = runspace; Collection <PSSession> result = powershell.Invoke <PSSession>(); powershell = PowerShell.Create(); command = new PSCommand(); command.AddCommand("Set-Variable"); command.AddParameter("Name", "ra"); command.AddParameter("Value", result[0]); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); powershell = PowerShell.Create(); command = new PSCommand(); command.AddScript("Import-PSSession -Session $ra"); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); Debug.WriteLine("About to make it out of the util controller"); return(runspace); }
public MSActorReturnMessageModel SetMailboxQuotas(string identity, string prohibitsendreceivequota, string prohibitsendquota, string issuewarningquota) { try { PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { using (Runspace runspace = RunspaceFactory.CreateRunspace()) { powershell.Runspace = runspace; runspace.Open(); ConnectToExchange(powershell, runspace); PSCommand command = new PSCommand(); command.AddCommand("Set-Mailbox"); command.AddParameter("Identity", identity); command.AddParameter("IssueWarningQuota", issuewarningquota); command.AddParameter("ProhibitSendQuota", prohibitsendquota); command.AddParameter("ProhibitSendReceiveQuota", prohibitsendreceivequota); command.AddParameter("UseDatabaseQuotaDefaults", false); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }
public MSActorReturnMessageModel ModifyDirQuota(string computername, string path, string limit) { // Project P0975: Replace old command line scripts with new PowerShell commands, // required after upgrading the Windows Server version on the file servers try { PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { string url = String.Format("http://{0}:5985/wsman", computername); Uri uri = new Uri(url); WSManConnectionInfo conn = new WSManConnectionInfo(uri); using (Runspace runspace = RunspaceFactory.CreateRunspace(conn)) { powershell.Runspace = runspace; runspace.Open(); PSCommand command = new PSCommand(); command.AddCommand("Set-FsrmQuota"); command.AddParameter("Path", path); command.AddParameter("Size", NumericLimit(limit)); powershell.Commands = command; Collection <PSObject> result = powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }
/// <summary> /// Create an instance of the CIM activity implementation class /// </summary> /// <param name="activityImplementationContext"></param> /// <param name="computerName"></param> /// <param name="credential"></param> /// <param name="certificateThumbprint"></param> /// <param name="authenticationMechanism"></param> /// <param name="useSsl"></param> /// <param name="port"></param> /// <param name="sessionOption"></param> /// <param name="session"></param> /// <param name="cimSessionOptions"></param> /// <param name="moduleDefinition"></param> /// <param name="resourceUri"></param> public CimActivityImplementationContext( ActivityImplementationContext activityImplementationContext, string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism?authenticationMechanism, bool useSsl, uint port, PSSessionOption sessionOption, CimSession session, CimSessionOptions cimSessionOptions, string moduleDefinition, Uri resourceUri) { if (activityImplementationContext == null) { throw new ArgumentNullException("activityImplementationContext"); } this.PowerShellInstance = activityImplementationContext.PowerShellInstance; ResourceUri = resourceUri; ComputerName = computerName; PSCredential = credential; PSCertificateThumbprint = certificateThumbprint; PSAuthentication = authenticationMechanism; PSUseSsl = useSsl; PSPort = port; PSSessionOption = sessionOption; Session = session; SessionOptions = cimSessionOptions; if (moduleDefinition != null) { // Creating a script block forces the string into the compiled script cache so we // don't need to reparse it at execution time. Locking the static _moduleDefinition is not // required since the operation is idempotent. _moduleScriptBlock = ScriptBlock.Create(moduleDefinition); _moduleDefinition = moduleDefinition; } }
public MSActorReturnMessageModel RenameDirectory(string computername, string path, string newname) { try { PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { string url = String.Format("http://{0}:5985/wsman", computername); Uri uri = new Uri(url); WSManConnectionInfo conn = new WSManConnectionInfo(uri); using (Runspace runspace = RunspaceFactory.CreateRunspace(conn)) { powershell.Runspace = runspace; runspace.Open(); PSCommand command = new PSCommand(); command.AddCommand("Rename-Item"); command.AddParameter("Path", path); command.AddParameter("NewName", newname); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }
public MSActorReturnMessageModel HideMailboxFromAddressLists(string identity, string hidemailbox) { try { PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { using (Runspace runspace = RunspaceFactory.CreateRunspace()) { powershell.Runspace = runspace; runspace.Open(); ConnectToExchange(powershell, runspace); // Now set the HiddenFromAddressListsEnabled flag PSCommand command = new PSCommand(); command.AddCommand("Set-Mailbox"); command.AddParameter("Identity", identity); command.AddParameter("HiddenFromAddressListsEnabled", Boolean.Parse(hidemailbox)); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }
public MSActorReturnMessageModel EnableDistributionGroup(string identity, string path, string description, string info) { try { PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { using (Runspace runspace = RunspaceFactory.CreateRunspace()) { powershell.Runspace = runspace; runspace.Open(); ConnectToExchange(powershell, runspace); PSCommand command = new PSCommand(); command.AddCommand("New-DistributionGroup"); command.AddParameter("Name", identity); command.AddParameter("OrganizationalUnit", path); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }
internal CimSession GetSession(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption) { CimSession session; lock (this.SyncRoot) { if (this.availableSessions.ContainsKey(computerName)) { List <CimConnectionManager.SessionEntry> item = this.availableSessions[computerName]; if (item.Count > 0) { int num = 0; while (num < item.Count) { CimConnectionManager.SessionEntry sessionEntry = item[num]; if ((sessionEntry.SessionOptions != null || sessionOptions != null) && !CimConnectionManager.CompareSessionOptions(sessionEntry, sessionOptions, credential, certificateThumbprint, authenticationMechanism, useSsl, port, pssessionOption)) { num++; } else { sessionEntry.AddReference(); session = sessionEntry.Session; return(session); } } } } CimConnectionManager.SessionEntry sessionEntry1 = new CimConnectionManager.SessionEntry(computerName, credential, certificateThumbprint, authenticationMechanism, sessionOptions, useSsl, port, pssessionOption); sessionEntry1.IterationsRemaining = 6; sessionEntry1.AddReference(); if (!this.availableSessions.ContainsKey(computerName)) { this.availableSessions.Add(computerName, new List <CimConnectionManager.SessionEntry>()); } this.availableSessions[computerName].Add(sessionEntry1); session = sessionEntry1.Session; } return(session); }
internal static List <WSManConnectionInfo> GetConnectionInfo(string[] PSComputerName, string[] PSConnectionUri, string PSCertificateThumbprint, string PSConfigurationName, bool?PSUseSsl, int?PSPort, string PSApplicationName, PSCredential PSCredential, AuthenticationMechanism PSAuthentication, bool PSAllowRedirection, PSSessionOption options) { int defaultMaximumConnectionRedirectionCount; List <WSManConnectionInfo> wSManConnectionInfos = new List <WSManConnectionInfo>(); string[] pSConnectionUri = null; bool flag = false; if (PSComputerName.IsNullOrEmpty() || !PSConnectionUri.IsNullOrEmpty()) { if (!PSComputerName.IsNullOrEmpty() || PSConnectionUri.IsNullOrEmpty()) { throw new ArgumentException(Resources.CannotSupplyUriAndComputername); } else { pSConnectionUri = PSConnectionUri; } } else { pSConnectionUri = PSComputerName; flag = true; } string[] strArrays = pSConnectionUri; for (int i = 0; i < (int)strArrays.Length; i++) { string str = strArrays[i]; if (string.IsNullOrEmpty(str)) { wSManConnectionInfos.Add(null); } else { WSManConnectionInfo wSManConnectionInfo = new WSManConnectionInfo(); if (PSPort.HasValue) { wSManConnectionInfo.Port = PSPort.Value; } if (PSUseSsl.HasValue && PSUseSsl.Value) { wSManConnectionInfo.Scheme = "https"; } if (!string.IsNullOrEmpty(PSConfigurationName)) { wSManConnectionInfo.ShellUri = PSConfigurationName; } if (!string.IsNullOrEmpty(PSApplicationName)) { wSManConnectionInfo.AppName = PSApplicationName; } if (!flag) { wSManConnectionInfo.ConnectionUri = (Uri)LanguagePrimitives.ConvertTo(str, typeof(Uri), CultureInfo.InvariantCulture); } else { wSManConnectionInfo.ComputerName = str; } if (PSCredential != null) { wSManConnectionInfo.Credential = PSCredential; } if (!string.IsNullOrEmpty(PSCertificateThumbprint)) { wSManConnectionInfo.CertificateThumbprint = PSCertificateThumbprint; } if (PSAuthentication != AuthenticationMechanism.Default) { wSManConnectionInfo.AuthenticationMechanism = PSAuthentication; } WSManConnectionInfo wSManConnectionInfo1 = wSManConnectionInfo; if (PSAllowRedirection) { defaultMaximumConnectionRedirectionCount = ActivityUtils.DefaultMaximumConnectionRedirectionCount; } else { defaultMaximumConnectionRedirectionCount = 0; } wSManConnectionInfo1.MaximumConnectionRedirectionCount = defaultMaximumConnectionRedirectionCount; if (options != null) { wSManConnectionInfo.SetSessionOptions(options); } wSManConnectionInfos.Add(wSManConnectionInfo); } } return(wSManConnectionInfos); }
protected override List <ActivityImplementationContext> GetImplementation(NativeActivityContext context) { bool needRunspace = !typeof(GenericCimCmdletActivity).IsAssignableFrom(this.GetType()); string[] computernames = PSComputerName.Get(context); CimSession[] sessions = this.CimSession.Get(context); Uri resourceUri = null; if (ResourceUri != null) { resourceUri = ResourceUri.Get(context); } List <ActivityImplementationContext> commands = new List <ActivityImplementationContext>(); // Configure the remote connectivity options... if (computernames != null && computernames.Length > 0) { WSManSessionOptions sessionOptions = new WSManSessionOptions(); // Set a timeout on the connection... uint?timeout = PSActionRunningTimeoutSec.Get(context); if (timeout.HasValue) { sessionOptions.Timeout = TimeSpan.FromSeconds((double)(timeout.Value)); } // See if we should use SSL or not... bool?useSsl = PSUseSsl.Get(context); bool sessionOptionUseSsl = false; if (useSsl.HasValue) { sessionOptions.UseSsl = useSsl.Value; sessionOptionUseSsl = useSsl.Value; } // Set the port to use uint?port = PSPort.Get(context); uint sessionOptionPort = 0; if (port.HasValue) { sessionOptions.DestinationPort = port.Value; sessionOptionPort = port.Value; } // Map over options from PSSessionConfig to WSManSessionOptions PSSessionOption pso = PSSessionOption.Get(context); if (pso != null) { sessionOptions.NoEncryption = pso.NoEncryption; sessionOptions.CertCACheck = pso.SkipCACheck; sessionOptions.CertCNCheck = pso.SkipCNCheck; sessionOptions.CertRevocationCheck = pso.SkipRevocationCheck; if (pso.UseUTF16) { sessionOptions.PacketEncoding = PacketEncoding.Utf16; } if (pso.Culture != null) { sessionOptions.Culture = pso.Culture; } if (pso.UICulture != null) { sessionOptions.UICulture = pso.UICulture; } if (pso.ProxyCredential != null) { string[] parts = pso.ProxyCredential.UserName.Split('\\'); string domain, userid; if (parts.Length < 2) { domain = string.Empty; userid = parts[0]; } else { domain = parts[0]; userid = parts[1]; } sessionOptions.AddProxyCredentials( new CimCredential(ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(pso.ProxyAuthentication), domain, userid, pso.ProxyCredential.Password)); } switch (pso.ProxyAccessType) { case ProxyAccessType.WinHttpConfig: sessionOptions.ProxyType = ProxyType.WinHttp; break; case ProxyAccessType.AutoDetect: sessionOptions.ProxyType = ProxyType.Auto; break; case ProxyAccessType.IEConfig: sessionOptions.ProxyType = ProxyType.InternetExplorer; break; } } PSCredential pscreds = PSCredential.Get(context); string certificateThumbprint = PSCertificateThumbprint.Get(context); if (pscreds != null && certificateThumbprint != null) { throw new ArgumentException(Resources.CredentialParameterCannotBeSpecifiedWithPSCertificateThumbPrint); } PasswordAuthenticationMechanism passwordAuthenticationMechanism = PasswordAuthenticationMechanism.Default; AuthenticationMechanism? authenticationMechanism = PSAuthentication.Get(context); if (authenticationMechanism.HasValue) { passwordAuthenticationMechanism = ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(authenticationMechanism.Value); } if (certificateThumbprint != null) { sessionOptions.AddDestinationCredentials(new CimCredential(CertificateAuthenticationMechanism.Default, certificateThumbprint)); } if (pscreds != null) { string[] parts = pscreds.UserName.Split('\\'); string domain, userid; if (parts.Length < 2) { domain = string.Empty; userid = parts[0]; } else { domain = parts[0]; userid = parts[1]; } sessionOptions.AddDestinationCredentials(new CimCredential(passwordAuthenticationMechanism, domain, userid, pscreds.Password)); } // Create the PowerShell instance, and add the script to it. if (sessions != null && sessions.Length > 0) { foreach (CimSession session in sessions) { ActivityImplementationContext configuredCommand = GetPowerShell(context); CimActivityImplementationContext activityImplementationContext = new CimActivityImplementationContext( configuredCommand, session.ComputerName, pscreds, certificateThumbprint, authenticationMechanism, sessionOptionUseSsl, sessionOptionPort, pso, session, sessionOptions, ModuleDefinition, resourceUri); commands.Add(activityImplementationContext); //if (needRunspace) // GetRunspaceForCimCmdlet(context, activityImplementationContext); } } else if (this.PSCommandName.Equals("CimCmdlets\\New-CimSession", StringComparison.OrdinalIgnoreCase)) { // NewCimSession activity is a special one as it creates the required sessions based on number of computers specified in one go. ActivityImplementationContext baseContext = GetPowerShell(context); CimActivityImplementationContext activityImplementationContext = new CimActivityImplementationContext(baseContext, null, // ComputerName pscreds, certificateThumbprint, authenticationMechanism, sessionOptionUseSsl, sessionOptionPort, pso, null, // session sessionOptions, ModuleDefinition, resourceUri); commands.Add(activityImplementationContext); } else { foreach (string computer in computernames) { ActivityImplementationContext baseContext = GetPowerShell(context); CimActivityImplementationContext activityImplementationContext = new CimActivityImplementationContext(baseContext, computer, pscreds, certificateThumbprint, authenticationMechanism, sessionOptionUseSsl, sessionOptionPort, pso, null, // session sessionOptions, ModuleDefinition, resourceUri); commands.Add(activityImplementationContext); } } } // Configure the local invocation options else { // Create the PowerShell instance, and add the script to it. ActivityImplementationContext baseContext = GetPowerShell(context); CimActivityImplementationContext activityImplementationContext = new CimActivityImplementationContext(baseContext, null, // ComputerName null, // Credential null, // CertificateThumbprint AuthenticationMechanism.Default, false, // UseSsl 0, // Port null, // PSSessionOption null, // Session null, // CimSessionOptions ModuleDefinition, resourceUri); commands.Add(activityImplementationContext); } return(commands); }
public MSActorReturnMessageModel RemoveDirectory(string computername, string path) { try { MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, ""); PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { string url = String.Format("http://{0}:5985/wsman", computername); Uri uri = new Uri(url); WSManConnectionInfo conn = new WSManConnectionInfo(uri); using (Runspace runspace = RunspaceFactory.CreateRunspace(conn)) { powershell.Runspace = runspace; runspace.Open(); PSCommand command = new PSCommand(); command.AddCommand("Remove-Item"); command.AddParameter("Path", path); command.AddParameter("Recurse"); command.AddParameter("Force"); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { RemoteException ex = powershell.Streams.Error[0].Exception as RemoteException; if (ex.SerializedRemoteException.TypeNames.Contains("Deserialized.System.Management.Automation.ItemNotFoundException")) { return(successMessage); } else if (ex.SerializedRemoteException.TypeNames.Contains("Deserialized.System.IO.PathTooLongException")) { // Run our script for extra long paths instead using (PowerShell powershell1 = PowerShell.Create()) { powershell1.Runspace = runspace; PSCommand command1 = new PSCommand(); command1.AddCommand("Set-ExecutionPolicy"); command1.AddParameter("ExecutionPolicy", "RemoteSigned"); command1.AddParameter("Scope", "Process"); command1.AddParameter("Force"); powershell1.Commands = command1; powershell1.Invoke(); if (powershell1.Streams.Error.Count > 0) { throw powershell1.Streams.Error[0].Exception; } powershell1.Streams.ClearStreams(); command1 = new PSCommand(); command1.AddScript(". D:\\PathTooLong.ps1"); powershell1.Commands = command1; powershell1.Invoke(); if (powershell1.Streams.Error.Count > 0) { throw powershell1.Streams.Error[0].Exception; } powershell1.Streams.ClearStreams(); command1 = new PSCommand(); command1.AddCommand("Remove-PathToLongDirectory"); command1.AddArgument(path); powershell1.Commands = command1; powershell1.Invoke(); if (powershell1.Streams.Error.Count > 0) { throw powershell1.Streams.Error[0].Exception; } powershell1.Streams.ClearStreams(); } } else { throw powershell.Streams.Error[0].Exception; } } powershell.Streams.ClearStreams(); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }
private MSActorReturnMessageModel AddFolderAccess(string identity, string computername, string path, string accesstype) { try { PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { string url = String.Format("http://{0}:5985/wsman", computername); Uri uri = new Uri(url); WSManConnectionInfo conn = new WSManConnectionInfo(uri); using (Runspace runspace = RunspaceFactory.CreateRunspace(conn)) { powershell.Runspace = runspace; runspace.Open(); // Note: The commands stacked on top of each other (prior to invoking) below have the effect // of piping the output of one into the other, e.g. the result of Get-Acl becomes an input to Set-Variable. // We need to work this way on a remote session so that type information does not get changed by // retrieving the objects back to the local session. PSCommand command = new PSCommand(); command.AddCommand("Get-Acl"); command.AddParameter("Path", path); command.AddCommand("Set-Variable"); command.AddParameter("Name", "acl"); powershell.Commands = command; Collection <PSObject> result = powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); command = new PSCommand(); command.AddCommand("New-Object"); command.AddParameter("TypeName", "System.Security.AccessControl.FileSystemAccessRule"); command.AddParameter("ArgumentList", new object[] { identity, accesstype, "ContainerInherit,ObjectInherit", "None", "Allow" }); command.AddCommand("Set-Variable"); command.AddParameter("Name", "perms"); powershell.Commands = command; result = powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); command = new PSCommand(); command.AddScript("$acl.SetAccessRule($perms)"); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); command = new PSCommand(); command.AddScript(String.Format("Set-Acl -AclObject $acl -Path {0}", path)); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }
public MSActorReturnMessageModel AddDirQuota(string computername, string path, string limit) { // Project P0975: Replace old command line scripts with new PowerShell commands, // required after upgrading the Windows Server version on the file servers MSActorReturnMessageModel successMessage; try { PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { string url = String.Format("http://{0}:5985/wsman", computername); Uri uri = new Uri(url); WSManConnectionInfo conn = new WSManConnectionInfo(uri); using (Runspace runspace = RunspaceFactory.CreateRunspace(conn)) { powershell.Runspace = runspace; runspace.Open(); PSCommand command = new PSCommand(); command.AddCommand("New-FsrmQuota"); command.AddParameter("Path", path); command.AddParameter("Size", NumericLimit(limit)); powershell.Commands = command; Collection <PSObject> result = powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { if (powershell.Streams.Error[0].Exception.Message.Trim() != "0x80045303, The specified object already exists.") { throw powershell.Streams.Error[0].Exception; } else { powershell.Streams.ClearStreams(); // Check that the existing quota has the same limit command = new PSCommand(); command.AddCommand("Get-FsrmQuota"); command.AddParameter("Path", path); powershell.Commands = command; Collection <PSObject> res = powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } CimInstance quota = (CimInstance)res.FirstOrDefault()?.BaseObject; if ((ulong)quota.CimInstanceProperties["Size"].Value != NumericLimit(limit)) { throw new Exception("A different quota already exists on that folder"); } } } powershell.Streams.ClearStreams(); successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }
public MSActorReturnMessageModel RemoveNetShare(string name, string computername, string path) { MSActorReturnMessageModel successMessage; try { PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { string url = String.Format("http://{0}:5985/wsman", computername); Uri uri = new Uri(url); WSManConnectionInfo conn = new WSManConnectionInfo(uri); using (Runspace runspace = RunspaceFactory.CreateRunspace(conn)) { powershell.Runspace = runspace; runspace.Open(); // First check that the share name is for the correct path PSCommand command = new PSCommand(); string script = String.Format("net share {0}", name); command.AddScript(script); powershell.Commands = command; Collection <PSObject> ret = powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { if (powershell.Streams.Error[0].FullyQualifiedErrorId == "NativeCommandError") { // If the share does not exist return success if (powershell.Streams.Error[0].Exception.Message == "This shared resource does not exist.") { successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } else { StringBuilder msgBuilder = new StringBuilder(); foreach (ErrorRecord errorRec in powershell.Streams.Error) { // Kludge to fix a weird bug with blank lines in the error output if (errorRec.CategoryInfo.ToString() == errorRec.Exception.Message) { msgBuilder.AppendLine(); } else { msgBuilder.AppendLine(errorRec.Exception.Message); } } throw new Exception(msgBuilder.ToString()); } } else { throw powershell.Streams.Error[0].Exception; } } powershell.Streams.ClearStreams(); // Find the first (hopefully only) line in the output with "Path" at the beginning string pathResultLine = ret.First(x => (x.BaseObject as string).StartsWith("Path")).BaseObject as string; // The output looks like "Path D:\Users\srenker". // The regular expression below separates this into groups. // Meaning of the next regex (from left to right): // 1. Save all the characters that are not blanks into a group. (\S+) // 2. Skip over all characters that are blanks. \s+ // 3. Save all the other characters into a group, up to end of line. (.+)$ // It's done this way because the path may have a space embedded in the name. // The @ before the string tells C# not to escape any characters before passing it // to the regular expression processor. GroupCollection groups = Regex.Match(pathResultLine, @"(\S+)\s+(.+)$").Groups; // Group 2 (#3 above) is the path value. string existingPath = groups[2].Value; if (!String.Equals(path, existingPath, StringComparison.OrdinalIgnoreCase)) { throw new Exception(String.Format("Share '{0}' is for path '{1}', different than specified.", name, existingPath)); } // Now delete the share script = String.Format("net share {0} /delete", name); command.AddScript(script); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { if (powershell.Streams.Error[0].FullyQualifiedErrorId == "NativeCommandError") { StringBuilder msgBuilder = new StringBuilder(); foreach (ErrorRecord errorRec in powershell.Streams.Error) { // Kludge to fix a weird bug with blank lines in the error output if (errorRec.CategoryInfo.ToString() == errorRec.Exception.Message) { msgBuilder.AppendLine(); } else { msgBuilder.AppendLine(errorRec.Exception.Message); } } throw new Exception(msgBuilder.ToString()); } else { throw powershell.Streams.Error[0].Exception; } } powershell.Streams.ClearStreams(); successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }
/// <summary> /// Get a CIM session for the target computer /// </summary> /// <param name="computerName"></param> /// <param name="credential"></param> /// <param name="certificateThumbprint"></param> /// <param name="authenticationMechanism"></param> /// <param name="sessionOptions"></param> /// <param name="useSsl"></param> /// <param name="port"></param> /// <param name="pssessionOption"></param> /// <returns></returns> internal CimSession GetSession(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption) { System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(computerName), "ComputerName is null in GetSession. GetSession should not be called in this case."); lock (SyncRoot) { SessionEntry newSessionEntry; if (availableSessions.ContainsKey(computerName)) { List <SessionEntry> sel = availableSessions[computerName]; if (sel.Count > 0) { for (int i = 0; i < sel.Count; i++) { SessionEntry se = sel[i]; // No session options specified or the object matches exactly... if ((se.SessionOptions == null && sessionOptions == null) || CompareSessionOptions(se, sessionOptions, credential, certificateThumbprint, authenticationMechanism, useSsl, port, pssessionOption)) { // Up the number of references to this session object... se.AddReference(); return(se.Session); } } } } // Allocate a new session entry for this computer newSessionEntry = new SessionEntry(computerName, credential, certificateThumbprint, authenticationMechanism, sessionOptions, useSsl, port, pssessionOption); newSessionEntry.IterationsRemaining = MaxIterations; newSessionEntry.AddReference(); if (!availableSessions.ContainsKey(computerName)) { availableSessions.Add(computerName, new List <SessionEntry>()); } availableSessions[computerName].Add(newSessionEntry); // Return the session object return(newSessionEntry.Session); } }
public CimActivityImplementationContext(ActivityImplementationContext activityImplementationContext, string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism?authenticationMechanism, bool useSsl, uint port, PSSessionOption sessionOption, CimSession session, CimSessionOptions cimSessionOptions, string moduleDefinition, Uri resourceUri) { if (activityImplementationContext != null) { base.PowerShellInstance = activityImplementationContext.PowerShellInstance; this.ResourceUri = resourceUri; this.ComputerName = computerName; base.PSCredential = credential; base.PSCertificateThumbprint = certificateThumbprint; base.PSAuthentication = authenticationMechanism; base.PSUseSsl = new bool?(useSsl); base.PSPort = new uint?(port); base.PSSessionOption = sessionOption; this.Session = session; this.SessionOptions = cimSessionOptions; if (moduleDefinition != null) { CimActivityImplementationContext._moduleScriptBlock = ScriptBlock.Create(moduleDefinition); this._moduleDefinition = moduleDefinition; } return; } else { throw new ArgumentNullException("activityImplementationContext"); } }
private static bool CompareSessionOptions(CimConnectionManager.SessionEntry sessionEntry, CimSessionOptions options2, PSCredential credential2, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, bool useSsl, uint port, PSSessionOption pssessionOption) { TimeSpan timeout = sessionEntry.SessionOptions.Timeout; if (timeout.Equals(options2.Timeout)) { if (string.Equals(sessionEntry.SessionOptions.Culture.ToString(), options2.Culture.ToString(), StringComparison.OrdinalIgnoreCase)) { if (string.Equals(sessionEntry.SessionOptions.UICulture.ToString(), options2.UICulture.ToString(), StringComparison.OrdinalIgnoreCase)) { if (string.Equals(sessionEntry.CertificateThumbprint, certificateThumbprint, StringComparison.OrdinalIgnoreCase)) { if (sessionEntry.AuthenticationMechanism == authenticationMechanism) { if (WorkflowUtils.CompareCredential(sessionEntry.Credential, credential2)) { if (sessionEntry.UseSsl == useSsl) { if (sessionEntry.Port == port) { if (!(pssessionOption == null ^ sessionEntry.PSSessionOption == null)) { if (pssessionOption != null && sessionEntry.PSSessionOption != null) { if (sessionEntry.PSSessionOption.ProxyAccessType == pssessionOption.ProxyAccessType) { if (sessionEntry.PSSessionOption.ProxyAuthentication == pssessionOption.ProxyAuthentication) { if (WorkflowUtils.CompareCredential(sessionEntry.PSSessionOption.ProxyCredential, pssessionOption.ProxyCredential)) { if (sessionEntry.PSSessionOption.SkipCACheck == pssessionOption.SkipCACheck) { if (sessionEntry.PSSessionOption.SkipCNCheck == pssessionOption.SkipCNCheck) { if (sessionEntry.PSSessionOption.SkipRevocationCheck == pssessionOption.SkipRevocationCheck) { if (sessionEntry.PSSessionOption.NoEncryption == pssessionOption.NoEncryption) { if (sessionEntry.PSSessionOption.UseUTF16 != pssessionOption.UseUTF16) { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } return(true); } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } } else { return(false); } }
private static bool CompareSessionOptions(SessionEntry sessionEntry, CimSessionOptions options2, PSCredential credential2, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, bool useSsl, uint port, PSSessionOption pssessionOption) { if (!sessionEntry.SessionOptions.Timeout.Equals(options2.Timeout)) { return(false); } if (!string.Equals(sessionEntry.SessionOptions.Culture.ToString(), options2.Culture.ToString(), StringComparison.OrdinalIgnoreCase)) { return(false); } if (!string.Equals(sessionEntry.SessionOptions.UICulture.ToString(), options2.UICulture.ToString(), StringComparison.OrdinalIgnoreCase)) { return(false); } if (!string.Equals(sessionEntry.CertificateThumbprint, certificateThumbprint, StringComparison.OrdinalIgnoreCase)) { return(false); } if (sessionEntry.AuthenticationMechanism != authenticationMechanism) { return(false); } if (!Workflow.WorkflowUtils.CompareCredential(sessionEntry.Credential, credential2)) { return(false); } if (sessionEntry.UseSsl != useSsl) { return(false); } if (sessionEntry.Port != port) { return(false); } // check PSSessionOption if present if (pssessionOption == null ^ sessionEntry.PSSessionOption == null) { return(false); } if (pssessionOption != null && sessionEntry.PSSessionOption != null) { if (sessionEntry.PSSessionOption.ProxyAccessType != pssessionOption.ProxyAccessType) { return(false); } if (sessionEntry.PSSessionOption.ProxyAuthentication != pssessionOption.ProxyAuthentication) { return(false); } if (!Workflow.WorkflowUtils.CompareCredential(sessionEntry.PSSessionOption.ProxyCredential, pssessionOption.ProxyCredential)) { return(false); } if (sessionEntry.PSSessionOption.SkipCACheck != pssessionOption.SkipCACheck) { return(false); } if (sessionEntry.PSSessionOption.SkipCNCheck != pssessionOption.SkipCNCheck) { return(false); } if (sessionEntry.PSSessionOption.SkipRevocationCheck != pssessionOption.SkipRevocationCheck) { return(false); } if (sessionEntry.PSSessionOption.NoEncryption != pssessionOption.NoEncryption) { return(false); } if (sessionEntry.PSSessionOption.UseUTF16 != pssessionOption.UseUTF16) { return(false); } } return(true); }
public void process() { string password = "******"; string userName = "******"; System.Uri uri = new Uri("https://WIN-KURRR2QSDJ0.jnittech.com/powershell?serializationLevel=Full"); System.Security.SecureString securePassword = String2SecureString(password); PSCredential creds = new PSCredential(userName, securePassword); Runspace runspace = RunspaceFactory.CreateRunspace(); PowerShell powershell = PowerShell.Create(); PSCommand command = new PSCommand(); command.AddCommand("New-PSSession"); command.AddParameter("ConfigurationName", "Microsoft.Exchange"); command.AddParameter("ConnectionUri", uri); command.AddParameter("Credential", creds); command.AddParameter("Authentication", "Default"); PSSessionOption sessionOption = new PSSessionOption(); sessionOption.SkipCACheck = true; sessionOption.SkipCNCheck = true; sessionOption.SkipRevocationCheck = true; command.AddParameter("SessionOption", sessionOption); powershell.Commands = command; try { // open the remote runspace runspace.Open(); // associate the runspace with powershell powershell.Runspace = runspace; // invoke the powershell to obtain the results Collection <PSSession> result = powershell.Invoke <PSSession>(); foreach (ErrorRecord current in powershell.Streams.Error) { Console.WriteLine("Exception: " + current.Exception.ToString()); Console.WriteLine("Inner Exception: " + current.Exception.InnerException); } if (result.Count != 1) { throw new Exception("Unexpected number of Remote Runspace connections returned."); } // Set the runspace as a local variable on the runspace powershell = PowerShell.Create(); command = new PSCommand(); command.AddCommand("Set-Variable"); command.AddParameter("Name", "ra"); command.AddParameter("Value", result[0]); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); // First import the cmdlets in the current runspace (using Import-PSSession) powershell = PowerShell.Create(); command = new PSCommand(); command.AddScript("Import-PSSession -Session $ra"); powershell.Commands = command; powershell.Runspace = runspace; powershell.Invoke(); // Now run get-ExchangeServer System.Collections.ObjectModel.Collection <PSObject> results = new System.Collections.ObjectModel.Collection <PSObject>(); powershell = PowerShell.Create(); powershell.Runspace = runspace; //Change the Path to the Script to suit your needs System.IO.StreamReader sr = new System.IO.StreamReader("C:\\GetIn\\Sudheer\\PowerShellScript-Own\\c#PowerShellScripts\\EX_QueuesBasedOnIdentity.ps1"); string reportStream = sr.ReadToEnd(); powershell.AddScript(reportStream); powershell.AddParameter("identity", "WIN-KURRR2QSDJ0\\Submission"); try { results = powershell.Invoke(); } catch (Exception ex) { Console.WriteLine(ex.Message); } //powershell.Runspace.SessionStateProxy.SetVariable("server", "win-kurrr2qsdj0.jnittech.com"); //powershell.Runspace.SessionStateProxy.SetVariable("mbx", "*MBX"); if (powershell.Streams.Error.Count > 51) { foreach (ErrorRecord er in powershell.Streams.Error) { Console.WriteLine(er.ErrorDetails); } } else { foreach (var ps in results) { Console.WriteLine(ps.Properties["RunspaceId"].Name.ToString() + ": " + ps.Properties["RunspaceId"].Value.ToString()); Console.WriteLine(ps.Properties["Identity"].Name.ToString() + ": " + ps.Properties["Identity"].Value.ToString()); Console.WriteLine(ps.Properties["DeliveryType"].Name.ToString() + ": " + ps.Properties["DeliveryType"].Value.ToString()); } } } finally { // dispose the runspace and enable garbage collection runspace.Dispose(); runspace = null; // Finally dispose the powershell and set all variables to null to free // up any resources. powershell.Dispose(); powershell = null; } }
protected override List <ActivityImplementationContext> GetImplementation(NativeActivityContext context) { string empty; string str; string empty1; string str1; typeof(GenericCimCmdletActivity).IsAssignableFrom(base.GetType()); string[] strArrays = this.PSComputerName.Get(context); CimSession[] cimSessionArray = this.CimSession.Get(context); Uri uri = null; if (this.ResourceUri != null) { uri = this.ResourceUri.Get(context); } List <ActivityImplementationContext> activityImplementationContexts = new List <ActivityImplementationContext>(); if (strArrays == null || (int)strArrays.Length <= 0) { ActivityImplementationContext powerShell = this.GetPowerShell(context); CimActivityImplementationContext cimActivityImplementationContext = new CimActivityImplementationContext(powerShell, null, null, null, new AuthenticationMechanism?(AuthenticationMechanism.Default), false, 0, null, null, null, this.ModuleDefinition, uri); activityImplementationContexts.Add(cimActivityImplementationContext); } else { WSManSessionOptions wSManSessionOption = new WSManSessionOptions(); uint?nullable = base.PSActionRunningTimeoutSec.Get(context); if (nullable.HasValue) { wSManSessionOption.Timeout = TimeSpan.FromSeconds((double)((float)nullable.Value)); } bool?nullable1 = this.PSUseSsl.Get(context); bool value = false; if (nullable1.HasValue) { wSManSessionOption.UseSsl = nullable1.Value; value = nullable1.Value; } uint?nullable2 = this.PSPort.Get(context); uint num = 0; if (nullable2.HasValue) { wSManSessionOption.DestinationPort = nullable2.Value; num = nullable2.Value; } PSSessionOption pSSessionOption = this.PSSessionOption.Get(context); if (pSSessionOption != null) { wSManSessionOption.NoEncryption = pSSessionOption.NoEncryption; wSManSessionOption.CertCACheck = pSSessionOption.SkipCACheck; wSManSessionOption.CertCNCheck = pSSessionOption.SkipCNCheck; wSManSessionOption.CertRevocationCheck = pSSessionOption.SkipRevocationCheck; if (pSSessionOption.UseUTF16) { wSManSessionOption.PacketEncoding = PacketEncoding.Utf16; } if (pSSessionOption.Culture != null) { wSManSessionOption.Culture = pSSessionOption.Culture; } if (pSSessionOption.UICulture != null) { wSManSessionOption.UICulture = pSSessionOption.UICulture; } if (pSSessionOption.ProxyCredential != null) { char[] chrArray = new char[1]; chrArray[0] = '\\'; string[] strArrays1 = pSSessionOption.ProxyCredential.UserName.Split(chrArray); if ((int)strArrays1.Length >= 2) { empty = strArrays1[0]; str = strArrays1[1]; } else { empty = string.Empty; str = strArrays1[0]; } wSManSessionOption.AddProxyCredentials(new CimCredential(PSGeneratedCIMActivity.ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(pSSessionOption.ProxyAuthentication), empty, str, pSSessionOption.ProxyCredential.Password)); } ProxyAccessType proxyAccessType = pSSessionOption.ProxyAccessType; if (proxyAccessType == ProxyAccessType.IEConfig) { wSManSessionOption.ProxyType = ProxyType.InternetExplorer; goto Label0; } else if (proxyAccessType == ProxyAccessType.WinHttpConfig) { wSManSessionOption.ProxyType = ProxyType.WinHttp; goto Label0; } else if (proxyAccessType == (ProxyAccessType.IEConfig | ProxyAccessType.WinHttpConfig)) { goto Label0; } else if (proxyAccessType == ProxyAccessType.AutoDetect) { wSManSessionOption.ProxyType = ProxyType.Auto; goto Label0; } } Label0: PSCredential pSCredential = this.PSCredential.Get(context); string str2 = this.PSCertificateThumbprint.Get(context); if (pSCredential == null || str2 == null) { PasswordAuthenticationMechanism cimPasswordAuthenticationMechanism = PasswordAuthenticationMechanism.Default; AuthenticationMechanism? nullable3 = this.PSAuthentication.Get(context); if (nullable3.HasValue) { cimPasswordAuthenticationMechanism = PSGeneratedCIMActivity.ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(nullable3.Value); } if (str2 != null) { wSManSessionOption.AddDestinationCredentials(new CimCredential(CertificateAuthenticationMechanism.Default, str2)); } if (pSCredential != null) { char[] chrArray1 = new char[1]; chrArray1[0] = '\\'; string[] strArrays2 = pSCredential.UserName.Split(chrArray1); if ((int)strArrays2.Length >= 2) { empty1 = strArrays2[0]; str1 = strArrays2[1]; } else { empty1 = string.Empty; str1 = strArrays2[0]; } wSManSessionOption.AddDestinationCredentials(new CimCredential(cimPasswordAuthenticationMechanism, empty1, str1, pSCredential.Password)); } if (cimSessionArray == null || (int)cimSessionArray.Length <= 0) { string[] strArrays3 = strArrays; for (int i = 0; i < (int)strArrays3.Length; i++) { string str3 = strArrays3[i]; ActivityImplementationContext activityImplementationContext = this.GetPowerShell(context); CimActivityImplementationContext cimActivityImplementationContext1 = new CimActivityImplementationContext(activityImplementationContext, str3, pSCredential, str2, nullable3, value, num, pSSessionOption, null, wSManSessionOption, this.ModuleDefinition, uri); activityImplementationContexts.Add(cimActivityImplementationContext1); } } else { CimSession[] cimSessionArray1 = cimSessionArray; for (int j = 0; j < (int)cimSessionArray1.Length; j++) { CimSession cimSession = cimSessionArray1[j]; ActivityImplementationContext powerShell1 = this.GetPowerShell(context); CimActivityImplementationContext cimActivityImplementationContext2 = new CimActivityImplementationContext(powerShell1, cimSession.ComputerName, pSCredential, str2, nullable3, value, num, pSSessionOption, cimSession, wSManSessionOption, this.ModuleDefinition, uri); activityImplementationContexts.Add(cimActivityImplementationContext2); } } } else { throw new ArgumentException(Resources.CredentialParameterCannotBeSpecifiedWithPSCertificateThumbPrint); } } return(activityImplementationContexts); }
/// <summary> /// Performs initialization of cmdlet execution. /// </summary> protected override void BeginProcessing() { PSSessionOption result = new PSSessionOption(); // Begin: WSMan specific options #if !UNIX result.ProxyAccessType = this.ProxyAccessType; result.ProxyAuthentication = this.ProxyAuthentication; result.ProxyCredential = this.ProxyCredential; #endif result.SkipCACheck = this.SkipCACheck; result.SkipCNCheck = this.SkipCNCheck; #if !UNIX result.SkipRevocationCheck = this.SkipRevocationCheck; if (_operationtimeout.HasValue) { result.OperationTimeout = TimeSpan.FromMilliseconds(_operationtimeout.Value); } result.NoEncryption = this.NoEncryption; result.UseUTF16 = this.UseUTF16; result.IncludePortInSPN = this.IncludePortInSPN; // End: WSMan specific options if (_maximumRedirection.HasValue) { result.MaximumConnectionRedirectionCount = this.MaximumRedirection; } result.NoCompression = this.NoCompression.IsPresent; result.NoMachineProfile = this.NoMachineProfile.IsPresent; result.MaximumReceivedDataSizePerCommand = _maxRecvdDataSizePerCommand; result.MaximumReceivedObjectSize = _maxRecvdObjectSize; if (this.Culture != null) { result.Culture = this.Culture; } if (this.UICulture != null) { result.UICulture = this.UICulture; } if (_openTimeout.HasValue) { result.OpenTimeout = TimeSpan.FromMilliseconds(_openTimeout.Value); } if (_cancelTimeout.HasValue) { result.CancelTimeout = TimeSpan.FromMilliseconds(_cancelTimeout.Value); } if (_idleTimeout.HasValue) { result.IdleTimeout = TimeSpan.FromMilliseconds(_idleTimeout.Value); } result.OutputBufferingMode = OutputBufferingMode; result.MaxConnectionRetryCount = MaxConnectionRetryCount; if (this.ApplicationArguments != null) { result.ApplicationArguments = this.ApplicationArguments; } #endif this.WriteObject(result); }
public MSActorReturnMessageModel AddNetShare(string name, string computername, string path) { MSActorReturnMessageModel successMessage; try { PSSessionOption option = new PSSessionOption(); using (PowerShell powershell = PowerShell.Create()) { string url = String.Format("http://{0}:5985/wsman", computername); Uri uri = new Uri(url); WSManConnectionInfo conn = new WSManConnectionInfo(uri); using (Runspace runspace = RunspaceFactory.CreateRunspace(conn)) { powershell.Runspace = runspace; runspace.Open(); PSCommand command = new PSCommand(); string script = String.Format("net share {0}={1} \"/GRANT:Everyone,Full\"", name, path); command.AddScript(script); powershell.Commands = command; powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { if (powershell.Streams.Error[0].FullyQualifiedErrorId == "NativeCommandError") { // If the share already exists it might be okay (see "else" below). Otherwise this is an error. if (powershell.Streams.Error[0].Exception.Message != "The name has already been shared.") { StringBuilder msgBuilder = new StringBuilder(); foreach (ErrorRecord errorRec in powershell.Streams.Error) { // Kludge to fix a weird bug with blank lines in the error output if (errorRec.CategoryInfo.ToString() == errorRec.Exception.Message) { msgBuilder.AppendLine(); } else { msgBuilder.AppendLine(errorRec.Exception.Message); } } throw new Exception(msgBuilder.ToString()); } else { powershell.Streams.ClearStreams(); // Check that the existing share has the same path command = new PSCommand(); script = String.Format("net share {0}", name); command.AddScript(script); powershell.Commands = command; Collection <PSObject> ret = powershell.Invoke(); if (powershell.Streams.Error.Count > 0) { throw powershell.Streams.Error[0].Exception; } powershell.Streams.ClearStreams(); // Find the first (hopefully only) line in the output with "Path" at the beginning string pathResultLine = ret.First(x => (x.BaseObject as string).StartsWith("Path")).BaseObject as string; if (pathResultLine == null) { // There was not a line in the output containing the path, so we assume we got an error message instead. string message = ret.First(x => (x.BaseObject as string).Length > 0).BaseObject as string; throw new Exception(message); } else { // The output looks like "Path D:\Users\srenker". // The regular expression below separates this into groups. // Meaning of the next regex (from left to right): // 1. Save all the characters that are not blanks into a group. (\S+) // 2. Skip over all characters that are blanks. \s+ // 3. Save all the other characters into a group, up to end of line. (.+)$ // It's done this way because the path may have a space embedded in the name. // The @ before the string tells C# not to escape any characters before passing it // to the regular expression processor. GroupCollection groups = Regex.Match(pathResultLine, @"(\S+)\s+(.+)$").Groups; // Group 2 (#3 above) is the path value. string pathResult = groups[2].Value; if (pathResult == path) { successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } else { throw new Exception(String.Format("Share '{0}' already exists for a different path '{1}'.", name, pathResult)); } } } } else { throw powershell.Streams.Error[0].Exception; } // powershell.Streams.ClearStreams(); -- is unreachable here } successMessage = new MSActorReturnMessageModel(SuccessCode, ""); return(successMessage); } } } catch (Exception e) { return(util.ReportError(e)); } }