示例#1
0
        internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs(
            IntPtr wsmanAPIHandle,
            IntPtr wsmanSessionHandle,
            WSManNativeApi.WSManError errorStruct,
            TransportMethodEnum transportMethodReportingError,
            PSRemotingErrorId errorResourceID,
            params object[] resourceArgs)
        {
            PSRemotingTransportException e;

            if (errorStruct.errorCode == -2144108135)
            {
                string sessionOptionAsString = WSManNativeApi.WSManGetSessionOptionAsString(wsmanSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_REDIRECT_LOCATION);
                string str = WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)).Trim();
                e = (PSRemotingTransportException) new PSRemotingTransportRedirectException(sessionOptionAsString, PSRemotingErrorId.URIEndPointNotResolved, new object[2]
                {
                    (object)str,
                    (object)sessionOptionAsString
                });
            }
            else
            {
                e = new PSRemotingTransportException(PSRemotingErrorId.TroubleShootingHelpTopic, new object[1]
                {
                    (object)PSRemotingErrorInvariants.FormatResourceString(errorResourceID, resourceArgs)
                });
                e.TransportMessage = WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode));
            }
            e.ErrorCode = errorStruct.errorCode;
            return(new TransportErrorOccuredEventArgs(e, transportMethodReportingError));
        }
示例#2
0
        private void RemoveJobAndDispose(Job job, bool jobIsJob2)
        {
            try
            {
                bool job2TypeFound = false;

                if (jobIsJob2)
                {
                    job2TypeFound = JobManager.RemoveJob(job as Job2, this, true, false);
                }

                if (!job2TypeFound)
                {
                    JobRepository.Remove(job);
                }

                job.Dispose();
            }
            catch (ArgumentException ex)
            {
                string message = PSRemotingErrorInvariants.FormatResourceString(
                    RemotingErrorIdStrings.CannotRemoveJob);

                ArgumentException ex2 = new ArgumentException(message, ex);
                WriteError(new ErrorRecord(ex2, "CannotRemoveJob", ErrorCategory.InvalidOperation, job));
            }
        }
示例#3
0
 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;
 }
示例#4
0
        internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs(IntPtr wsmanAPIHandle, WSManClientSessionTransportManager wsmanSessionTM, WSManNativeApi.WSManError errorStruct, TransportMethodEnum transportMethodReportingError, string resourceString, params object[] resourceArgs)
        {
            PSRemotingTransportException exception;

            if ((errorStruct.errorCode == -2144108135) && (wsmanSessionTM != null))
            {
                string redirectLocation = WSManNativeApi.WSManGetSessionOptionAsString(wsmanSessionTM.SessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_REDIRECT_LOCATION);
                string str2             = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)).Trim();
                exception = new PSRemotingTransportRedirectException(redirectLocation, PSRemotingErrorId.URIEndPointNotResolved, RemotingErrorIdStrings.URIEndPointNotResolved, new object[] { str2, redirectLocation });
            }
            else if ((errorStruct.errorCode == -2144108485) && (wsmanSessionTM != null))
            {
                string str3 = wsmanSessionTM.ConnectionInfo.ShellUri.Replace("http://schemas.microsoft.com/powershell/", string.Empty);
                string str4 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidConfigurationName, new object[] { str3, wsmanSessionTM.ConnectionInfo.ComputerName });
                exception = new PSRemotingTransportException(PSRemotingErrorId.InvalidConfigurationName, RemotingErrorIdStrings.ConnectExCallBackError, new object[] { wsmanSessionTM.ConnectionInfo.ComputerName, str4 })
                {
                    TransportMessage = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode))
                };
            }
            else
            {
                string str5 = PSRemotingErrorInvariants.FormatResourceString(resourceString, resourceArgs);
                exception = new PSRemotingTransportException(PSRemotingErrorId.TroubleShootingHelpTopic, RemotingErrorIdStrings.TroubleShootingHelpTopic, new object[] { str5 })
                {
                    TransportMessage = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode))
                };
            }
            exception.ErrorCode = errorStruct.errorCode;
            return(new TransportErrorOccuredEventArgs(exception, transportMethodReportingError));
        }
        /// <summary>
        /// Checks if the specified version of PowerShell is installed.
        /// </summary>
        /// <param name="version"></param>
        internal static void CheckIfPowerShellVersionIsInstalled(Version version)
        {
            // Check if PowerShell 2.0 is installed
            if (version != null && version.Major == 2)
            {
#if CORECLR
                // PowerShell 2.0 is not available for CoreCLR
                throw new ArgumentException(
                          PSRemotingErrorInvariants.FormatResourceString(
                              RemotingErrorIdStrings.PowerShellNotInstalled,
                              version, "PSVersion"));
#else
                // Because of app-compat issues, in Win8, we will have PS 2.0 installed by default but not .NET 2.0
                // In such a case, it is not enough if we check just PowerShell registry keys. We also need to check if .NET 2.0 is installed.
                try
                {
                    RegistryKey engineKey = PSSnapInReader.GetPSEngineKey(PSVersionInfo.RegistryVersion1Key);
                    // Also check for .NET 2.0 installation
                    if (!PsUtils.FrameworkRegistryInstallation.IsFrameworkInstalled(2, 0, 0))
                    {
                        throw new ArgumentException(
                                  PSRemotingErrorInvariants.FormatResourceString(
                                      RemotingErrorIdStrings.NetFrameWorkV2NotInstalled));
                    }
                }
                catch (PSArgumentException)
                {
                    throw new ArgumentException(
                              PSRemotingErrorInvariants.FormatResourceString(
                                  RemotingErrorIdStrings.PowerShellNotInstalled,
                                  version, "PSVersion"));
                }
#endif
            }
        }
示例#6
0
        private void AddRemoveErrorToResults(System.Management.Automation.Job job, Exception ex)
        {
            ArgumentException exception = new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.CannotRemoveJob, new object[0]), ex);
            ErrorRecord       record    = new ErrorRecord(exception, "ReceiveJobAutoRemovalError", ErrorCategory.InvalidOperation, job);

            this._results.Add(new PSStreamObject(PSStreamObjectType.Error, record));
        }
示例#7
0
 public WSManConnectionInfo(Uri uri, string shellUri, PSCredential credential)
 {
     this._scheme         = "http";
     this._computerName   = "localhost";
     this._appName        = DefaultAppName;
     this._port           = -1;
     this._connectionUri  = new Uri("http://localhost/wsman");
     this._shellUri       = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
     this._useCompression = true;
     if (uri == null)
     {
         this.ShellUri            = shellUri;
         this.Credential          = credential;
         this.UseDefaultWSManPort = true;
     }
     else
     {
         if (!uri.IsAbsoluteUri)
         {
             throw new NotSupportedException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RelativeUriForRunspacePathNotSupported, new object[0]));
         }
         if ((uri.AbsolutePath.Equals("/", StringComparison.OrdinalIgnoreCase) && string.IsNullOrEmpty(uri.Query)) && string.IsNullOrEmpty(uri.Fragment))
         {
             this.ConstructUri(uri.Scheme, uri.Host, new int?(uri.Port), DefaultAppName);
         }
         else
         {
             this.ConnectionUri = uri;
         }
         this.ShellUri   = shellUri;
         this.Credential = credential;
     }
 }
示例#8
0
 private void UpdateUri(Uri uri)
 {
     if (!uri.IsAbsoluteUri)
     {
         throw new NotSupportedException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RelativeUriForRunspacePathNotSupported, new object[0]));
     }
     if (uri.OriginalString.LastIndexOf(":", StringComparison.OrdinalIgnoreCase) > uri.AbsoluteUri.IndexOf("//", StringComparison.OrdinalIgnoreCase))
     {
         this._useDefaultWSManPort = false;
     }
     if ((uri.AbsolutePath.Equals("/", StringComparison.OrdinalIgnoreCase) && string.IsNullOrEmpty(uri.Query)) && string.IsNullOrEmpty(uri.Fragment))
     {
         string defaultAppName = DefaultAppName;
         this.ConstructUri(uri.Scheme, uri.Host, new int?(uri.Port), defaultAppName);
     }
     else
     {
         this._connectionUri       = uri;
         this._scheme              = uri.Scheme;
         this._appName             = uri.AbsolutePath;
         this._port                = uri.Port;
         this._computerName        = uri.Host;
         this._useDefaultWSManPort = false;
     }
 }
示例#9
0
        internal void ConstructUri(string scheme, string computerName, int?port, string appName)
        {
            this._scheme = scheme;
            if (string.IsNullOrEmpty(this._scheme))
            {
                this._scheme = "http";
            }
            if ((!this._scheme.Equals("http", StringComparison.OrdinalIgnoreCase) && !this._scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) && !this._scheme.Equals("http", StringComparison.OrdinalIgnoreCase))
            {
                ArgumentException exception = new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidSchemeValue, new object[] { this._scheme }));
                throw exception;
            }
            if (string.IsNullOrEmpty(computerName) || string.Equals(computerName, ".", StringComparison.OrdinalIgnoreCase))
            {
                this._computerName = "localhost";
            }
            else
            {
                this._computerName = computerName.Trim();
                IPAddress address = null;
                if ((IPAddress.TryParse(this._computerName, out address) && (address.AddressFamily == AddressFamily.InterNetworkV6)) && ((this._computerName.Length == 0) || (this._computerName[0] != '[')))
                {
                    this._computerName = "[" + this._computerName + "]";
                }
            }
            PSEtwLog.LogAnalyticVerbose(PSEventId.ComputerName, PSOpcode.Method, PSTask.CreateRunspace, PSKeyword.Runspace | PSKeyword.UseAlwaysAnalytic, new object[] { this._computerName });
            if (port.HasValue)
            {
                if (port.Value == 0)
                {
                    this._port = -1;
                    this.UseDefaultWSManPort = true;
                }
                else if ((port.Value == 80) || (port.Value == 0x1bb))
                {
                    this._port = port.Value;
                    this.UseDefaultWSManPort = false;
                }
                else
                {
                    if ((port.Value < 0) || (port.Value > 0xffff))
                    {
                        ArgumentException exception2 = new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.PortIsOutOfRange, new object[] { port }));
                        throw exception2;
                    }
                    this._port = port.Value;
                    this.UseDefaultWSManPort = false;
                }
            }
            this._appName = appName;
            if (string.IsNullOrEmpty(this._appName))
            {
                this._appName = DefaultAppName;
            }
            UriBuilder builder = new UriBuilder(this._scheme, this._computerName, this._port, this._appName);

            this._connectionUri = builder.Uri;
        }
示例#10
0
        private bool CheckJobCanBeRemoved(Job job, string parameterName, string resourceString, params object[] list)
        {
            if (job.IsFinishedState(job.JobStateInfo.State))
            {
                return(true);
            }
            Exception exception = new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(resourceString, list), parameterName);

            base.WriteError(new ErrorRecord(exception, "JobObjectNotFinishedCannotBeRemoved", ErrorCategory.InvalidOperation, job));
            return(false);
        }
示例#11
0
 protected void ValidateComputerName(string[] computerNames)
 {
     foreach (string str in computerNames)
     {
         UriHostNameType type = Uri.CheckHostName(str);
         if (((type != UriHostNameType.Dns) && (type != UriHostNameType.IPv4)) && (type != UriHostNameType.IPv6))
         {
             base.ThrowTerminatingError(new ErrorRecord(new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidComputerName, new object[0])), "PSSessionInvalidComputerName", ErrorCategory.InvalidArgument, computerNames));
         }
     }
 }
示例#12
0
        private void WriteErrorCreateRemoteRunspaceFailed(Exception exception, object argument)
        {
            PSRemotingTransportException exception2 = exception as PSRemotingTransportException;
            string str = null;

            if ((exception2 != null) && (exception2.ErrorCode == -2144108135))
            {
                str = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception2.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" });
            }
            ErrorRecord errorRecord = new ErrorRecord(exception, argument, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, null, null, null, null, null, str, null);

            base.WriteError(errorRecord);
        }
 internal ServerRunspacePoolDriver(
     Guid clientRunspacePoolId,
     int minRunspaces,
     int maxRunspaces,
     PSThreadOptions threadOptions,
     ApartmentState apartmentState,
     HostInfo hostInfo,
     InitialSessionState initialSessionState,
     PSPrimitiveDictionary applicationPrivateData,
     ConfigurationDataFromXML configData,
     AbstractServerSessionTransportManager transportManager,
     bool isAdministrator,
     RemoteSessionCapability serverCapability)
 {
     using (ServerRunspacePoolDriver.tracer.TraceConstructor((object)this))
     {
         this.serverCapability = serverCapability;
         ServerRemoteHost serverRemoteHost = new ServerRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, (AbstractServerTransportManager)transportManager);
         this.remoteHost             = serverRemoteHost;
         this.configData             = configData;
         this.applicationPrivateData = applicationPrivateData;
         this.localRunspacePool      = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, initialSessionState, (PSHost)serverRemoteHost);
         PSThreadOptions psThreadOptions = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread;
         if (threadOptions == PSThreadOptions.Default || threadOptions == psThreadOptions)
         {
             this.localRunspacePool.ThreadOptions = psThreadOptions;
         }
         else
         {
             if (!isAdministrator)
             {
                 throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.MustBeAdminToOverrideThreadOptions));
             }
             this.localRunspacePool.ThreadOptions = threadOptions;
         }
         ApartmentState apartmentState1 = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : ApartmentState.Unknown;
         this.localRunspacePool.ApartmentState = apartmentState == ApartmentState.Unknown || apartmentState == apartmentState1 ? apartmentState1 : apartmentState;
         this.clientRunspacePoolId             = clientRunspacePoolId;
         this.dsHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager);
         this.localRunspacePool.StateChanged          += new EventHandler <RunspacePoolStateChangedEventArgs>(this.HandleRunspacePoolStateChanged);
         this.localRunspacePool.ForwardEvent          += new EventHandler <PSEventArgs>(this.HandleRunspacePoolForwardEvent);
         this.localRunspacePool.RunspaceCreated       += new EventHandler <RunspaceCreatedEventArgs>(this.HandleRunspaceCreated);
         this.localRunspacePool.RunspaceCreated       += new EventHandler <RunspaceCreatedEventArgs>(this.HandleRunspaceCreatedForTypeTable);
         this.dsHandler.CreateAndInvokePowerShell     += new EventHandler <RemoteDataEventArgs <RemoteDataObject <PSObject> > >(this.HandleCreateAndInvokePowerShell);
         this.dsHandler.GetCommandMetadata            += new EventHandler <RemoteDataEventArgs <RemoteDataObject <PSObject> > >(this.HandleGetCommandMetadata);
         this.dsHandler.HostResponseReceived          += new EventHandler <RemoteDataEventArgs <RemoteHostResponse> >(this.HandleHostResponseReceived);
         this.dsHandler.SetMaxRunspacesReceived       += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleSetMaxRunspacesReceived);
         this.dsHandler.SetMinRunspacesReceived       += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleSetMinRunspacesReceived);
         this.dsHandler.GetAvailableRunspacesReceived += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleGetAvailalbeRunspacesReceived);
     }
 }
示例#14
0
        internal void RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, bool throwExceptions = false)
        {
            bool flag = false;

            lock (this._syncObject)
            {
                foreach (JobSourceAdapter adapter in this._sourceAdapters.Values)
                {
                    Job2 jobByInstanceId = null;
                    try
                    {
                        jobByInstanceId = adapter.GetJobByInstanceId(job.InstanceId, true);
                    }
                    catch (Exception exception)
                    {
                        this.Tracer.TraceException(exception);
                        CommandProcessorBase.CheckForSevereException(exception);
                        if (throwExceptions)
                        {
                            throw;
                        }
                        WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobError", adapter);
                    }
                    if (jobByInstanceId != null)
                    {
                        flag = true;
                        this.RemoveJobIdForReuse(jobByInstanceId);
                        try
                        {
                            adapter.RemoveJob(job);
                        }
                        catch (Exception exception2)
                        {
                            this.Tracer.TraceException(exception2);
                            CommandProcessorBase.CheckForSevereException(exception2);
                            if (throwExceptions)
                            {
                                throw;
                            }
                            WriteErrorOrWarning(writeErrorOnException, cmdlet, exception2, "JobSourceAdapterRemoveJobError", adapter);
                        }
                    }
                }
            }
            if (!flag && throwExceptions)
            {
                throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ItemNotFoundInRepository, new object[] { "Job repository", job.InstanceId.ToString() }));
            }
        }
示例#15
0
 internal static void ValidateSpecifiedAuthentication(PSCredential credential, string thumbprint, AuthenticationMechanism authentication)
 {
     if ((credential != null) && (thumbprint != null))
     {
         throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.NewRunspaceAmbiguosAuthentication, new object[] { "CertificateThumbPrint", "Credential" }));
     }
     if ((authentication != AuthenticationMechanism.Default) && (thumbprint != null))
     {
         throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.NewRunspaceAmbiguosAuthentication, new object[] { "CertificateThumbPrint", authentication.ToString() }));
     }
     if ((authentication == AuthenticationMechanism.NegotiateWithImplicitCredential) && (credential != null))
     {
         throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.NewRunspaceAmbiguosAuthentication, new object[] { "Credential", authentication.ToString() }));
     }
 }
示例#16
0
 private bool CheckJobCanBeRemoved(
     Job job,
     string parameterName,
     PSRemotingErrorId id,
     params object[] list)
 {
     using (JobCmdletBase.tracer.TraceMethod())
     {
         if (job.IsFinishedState(job.JobStateInfo.State))
         {
             return(true);
         }
         this.WriteError(new ErrorRecord((Exception) new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(id, list), parameterName), "JobObjectNotFinishedCannotBeRemoved", ErrorCategory.InvalidOperation, (object)job));
         return(false);
     }
 }
示例#17
0
 public void Remove(T item)
 {
     if (item == null)
     {
         throw new ArgumentNullException(this.identifier);
     }
     lock (this.syncObject)
     {
         Guid key = this.GetKey(item);
         if (!this.repository.ContainsKey(key))
         {
             throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ItemNotFoundInRepository, new object[] { "Job repository", key.ToString() }));
         }
         this.repository.Remove(key);
     }
 }
示例#18
0
        private bool CheckIfJob2CanBeRemoved(bool checkForRemove, string parameterName, Job2 job2, string resourceString, params object[] args)
        {
            if (checkForRemove)
            {
                if (job2.IsFinishedState(job2.JobStateInfo.State))
                {
                    return(true);
                }

                string    message = PSRemotingErrorInvariants.FormatResourceString(resourceString, args);
                Exception ex      = new ArgumentException(message, parameterName);
                WriteError(new ErrorRecord(ex, "JobObjectNotFinishedCannotBeRemoved", ErrorCategory.InvalidOperation, job2));
                return(false);
            }

            return(true);
        }
 internal static void CheckIfPowerShellVersionIsInstalled(Version version)
 {
     if ((version != null) && (version.Major == 2))
     {
         try
         {
             PSSnapInReader.GetPSEngineKey(PSVersionInfo.RegistryVersion1Key);
             if (!PsUtils.FrameworkRegistryInstallation.IsFrameworkInstalled(2, 0, 0))
             {
                 throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.NetFrameWorkV2NotInstalled, new object[0]));
             }
         }
         catch (PSArgumentException)
         {
             throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.PowerShellNotInstalled, new object[] { version, "PSVersion" }));
         }
     }
 }
示例#20
0
        protected System.Management.Automation.ScriptBlock GetScriptBlockFromFile(string filePath, bool isLiteralPath)
        {
            if (!isLiteralPath && WildcardPattern.ContainsWildcardCharacters(filePath))
            {
                throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.WildCardErrorFilePathParameter, new object[0]), "filePath");
            }
            if (!filePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.FilePathShouldPS1Extension, new object[0]), "filePath");
            }
            string             path        = new PathResolver().ResolveProviderAndPath(filePath, isLiteralPath, this, false, "RemotingErrorIdStrings", PSRemotingErrorId.FilePathNotFromFileSystemProvider.ToString());
            ExternalScriptInfo commandInfo = new ExternalScriptInfo(filePath, path, base.Context);

            if (!filePath.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase))
            {
                base.Context.AuthorizationManager.ShouldRunInternal(commandInfo, CommandOrigin.Internal, base.Context.EngineHostInterface);
            }
            return(commandInfo.ScriptBlock);
        }
示例#21
0
 private void RemoveJobAndDispose(System.Management.Automation.Job job, bool jobIsJob2)
 {
     try
     {
         if (jobIsJob2)
         {
             base.JobManager.RemoveJob(job as Job2, this, true, false);
         }
         else
         {
             base.JobRepository.Remove(job);
         }
         job.Dispose();
     }
     catch (ArgumentException exception)
     {
         ArgumentException exception2 = new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.CannotRemoveJob, new object[0]), exception);
         base.WriteError(new ErrorRecord(exception2, "CannotRemoveJob", ErrorCategory.InvalidOperation, job));
     }
 }
示例#22
0
        /// <summary>
        /// Remove the specified item from the repository
        /// </summary>
        /// <param name="item">object to remove</param>
        public void Remove(T item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(_identifier);
            }
            lock (_syncObject)
            {
                Guid instanceId = GetKey(item);

                if (!_repository.Remove(instanceId))
                {
                    String message =
                        PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ItemNotFoundInRepository,
                                                                       "Job repository", instanceId.ToString());

                    throw new ArgumentException(message);
                }
            }
        }
示例#23
0
        /// <summary>
        /// Resume the Job.
        /// </summary>
        protected override void ProcessRecord()
        {
            //List of jobs to resume
            List <Job> jobsToResume = null;

            switch (ParameterSetName)
            {
            case NameParameterSet:
            {
                jobsToResume = FindJobsMatchingByName(true, false, true, false);
            }
            break;

            case InstanceIdParameterSet:
            {
                jobsToResume = FindJobsMatchingByInstanceId(true, false, true, false);
            }
            break;

            case SessionIdParameterSet:
            {
                jobsToResume = FindJobsMatchingBySessionId(true, false, true, false);
            }
            break;

            case StateParameterSet:
            {
                jobsToResume = FindJobsMatchingByState(false);
            }
            break;

            case FilterParameterSet:
            {
                jobsToResume = FindJobsMatchingByFilter(false);
            }
            break;

            default:
            {
                jobsToResume = CopyJobsToList(_jobs, false, false);
            }
            break;
            }

            _allJobsToResume.AddRange(jobsToResume);

            // Blue: 151804 When resuming a single suspended workflow job, Resume-job cmdlet doesn't wait for the job to be in running state
            // Setting Wait to true so that this cmdlet will wait for the running job state.
            if (_allJobsToResume.Count == 1)
            {
                Wait = true;
            }

            foreach (Job job in jobsToResume)
            {
                var job2 = job as Job2;

                // If the job is not Job2, the resume operation is not supported.
                if (job2 == null)
                {
                    WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobResumeNotSupported, job.Id), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job));
                    continue;
                }

                string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id);
                if (ShouldProcess(targetString, VerbsLifecycle.Resume))
                {
                    _cleanUpActions.Add(job2, HandleResumeJobCompleted);
                    job2.ResumeJobCompleted += HandleResumeJobCompleted;

                    lock (_syncObject)
                    {
                        if (!_pendingJobs.Contains(job2.InstanceId))
                        {
                            _pendingJobs.Add(job2.InstanceId);
                        }
                    }

                    job2.ResumeJobAsync();
                }
            }
        }
示例#24
0
        /// <summary>
        /// Stop the Job.
        /// </summary>
        protected override void ProcessRecord()
        {
            //List of jobs to stop
            List <Job> jobsToStop = null;

            switch (ParameterSetName)
            {
            case NameParameterSet:
            {
                jobsToStop = FindJobsMatchingByName(true, false, true, false);
            }
            break;

            case InstanceIdParameterSet:
            {
                jobsToStop = FindJobsMatchingByInstanceId(true, false, true, false);
            }
            break;

            case SessionIdParameterSet:
            {
                jobsToStop = FindJobsMatchingBySessionId(true, false, true, false);
            }
            break;

            case StateParameterSet:
            {
                jobsToStop = FindJobsMatchingByState(false);
            }
            break;

            case FilterParameterSet:
            {
                jobsToStop = FindJobsMatchingByFilter(false);
            }
            break;

            default:
            {
                jobsToStop = CopyJobsToList(_jobs, false, false);
            }
            break;
            }

            _allJobsToStop.AddRange(jobsToStop);

            foreach (Job job in jobsToStop)
            {
                if (this.Stopping)
                {
                    return;
                }
                if (job.IsFinishedState(job.JobStateInfo.State))
                {
                    continue;
                }
                string targetString =
                    PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget,
                                                                   job.Command, job.Id);
                if (ShouldProcess(targetString, VerbsLifecycle.Stop))
                {
                    Job2 job2 = job as Job2;
                    // if it is a Job2, then async is supported
                    // stop the job asynchronously
                    if (job2 != null)
                    {
                        _cleanUpActions.Add(job2, HandleStopJobCompleted);
                        job2.StopJobCompleted += HandleStopJobCompleted;

                        lock (_syncObject)
                        {
                            if (!job2.IsFinishedState(job2.JobStateInfo.State) &&
                                !_pendingJobs.Contains(job2.InstanceId))
                            {
                                _pendingJobs.Add(job2.InstanceId);
                            }
                        }

                        job2.StopJobAsync();
                    }
                    else
                    {
                        job.StopJob();
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="powerShellVersion"></param>
        /// <param name="credential"></param>
        /// <param name="initializationScript"></param>
        /// <param name="useWow64"></param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            string psWow64Path = s_PSExePath;

            if (useWow64)
            {
                string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

                if ((!string.IsNullOrEmpty(procArch)) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
                                                          procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                {
                    psWow64Path = s_PSExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");

                    if (!File.Exists(psWow64Path))
                    {
                        string message =
                            PSRemotingErrorInvariants.FormatResourceString(
                                RemotingErrorIdStrings.IPCWowComponentNotPresent,
                                psWow64Path);
                        throw new PSInvalidOperationException(message);
                    }
                }
            }

            string processArguments = string.Empty;
            // Adding Version parameter to powershell.exe
            // Version parameter needs to go before all other parameters because the native layer looks for Version or
            // PSConsoleFile parameters before parsing other parameters.
            // The other parameters get parsed in the managed layer.
            Version tempVersion = powerShellVersion ?? PSVersionInfo.PSVersion;

            processArguments = string.Format(CultureInfo.InvariantCulture,
                                             "-Version {0}", new Version(tempVersion.Major, tempVersion.Minor));

            processArguments = string.Format(CultureInfo.InvariantCulture,
                                             "{0} -s -NoLogo -NoProfile", processArguments);

            if (initializationScript != null)
            {
                string scripBlockAsString = initializationScript.ToString();
                if (!string.IsNullOrEmpty(scripBlockAsString))
                {
                    string encodedCommand =
                        Convert.ToBase64String(Encoding.Unicode.GetBytes(scripBlockAsString));
                    processArguments = string.Format(CultureInfo.InvariantCulture,
                                                     "{0} -EncodedCommand {1}", processArguments, encodedCommand);
                }
            }

            // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
            // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
            _startInfo = new ProcessStartInfo
            {
                FileName               = useWow64 ? psWow64Path : s_PSExePath,
                Arguments              = processArguments,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true,
                LoadUserProfile        = true,
            };

            if (credential != null)
            {
                Net.NetworkCredential netCredential = credential.GetNetworkCredential();

                _startInfo.UserName = netCredential.UserName;
                _startInfo.Domain   = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
#if CORECLR
                _startInfo.PasswordInClearText = ClrFacade.ConvertSecureStringToString(credential.Password);
#else
                _startInfo.Password = credential.Password;
#endif
            }

            Process = new Process {
                StartInfo = _startInfo, EnableRaisingEvents = true
            };
        }
示例#26
0
        private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs)
        {
            ErrorRecord errorRecord;
            PSRemotingTransportException exception2;
            string str;

            if (sender == null)
            {
                throw PSTraceSource.NewArgumentNullException("sender");
            }
            if (stateEventArgs == null)
            {
                throw PSTraceSource.NewArgumentNullException("stateEventArgs");
            }
            RunspaceStateEventArgs baseEvent        = stateEventArgs.BaseEvent as RunspaceStateEventArgs;
            RunspaceState          state            = baseEvent.RunspaceStateInfo.State;
            OpenRunspaceOperation  operation        = sender as OpenRunspaceOperation;
            RemoteRunspace         operatedRunspace = operation.OperatedRunspace;

            if (operatedRunspace != null)
            {
                operatedRunspace.URIRedirectionReported -= new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported);
            }
            PipelineWriter objectWriter = this.stream.ObjectWriter;
            Exception      reason       = baseEvent.RunspaceStateInfo.Reason;

            switch (state)
            {
            case RunspaceState.Opened:
            {
                PSSession remoteRunspaceInfo = new PSSession(operatedRunspace);
                base.RunspaceRepository.Add(remoteRunspaceInfo);
                Action <Cmdlet> action = cmdlet => cmdlet.WriteObject(remoteRunspaceInfo);
                if (objectWriter.IsOpen)
                {
                    objectWriter.Write(action);
                }
                return;
            }

            case RunspaceState.Closed:
            {
                Uri             uri     = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <Uri>(operatedRunspace.ConnectionInfo, "ConnectionUri", null);
                string          message = base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, new object[] { (uri != null) ? uri.AbsoluteUri : string.Empty });
                Action <Cmdlet> action3 = cmdlet => cmdlet.WriteVerbose(message);
                if (objectWriter.IsOpen)
                {
                    objectWriter.Write(action3);
                }
                if (reason != null)
                {
                    ErrorRecord     errorRecord2 = new ErrorRecord(reason, "PSSessionStateClosed", ErrorCategory.OpenError, operatedRunspace);
                    Action <Cmdlet> action4      = cmdlet => cmdlet.WriteError(errorRecord2);
                    if (objectWriter.IsOpen)
                    {
                        objectWriter.Write(action4);
                    }
                }
                return;
            }

            case RunspaceState.Closing:
                return;

            case RunspaceState.Broken:
                exception2 = reason as PSRemotingTransportException;
                str        = null;
                if (exception2 != null)
                {
                    OpenRunspaceOperation operation2 = sender as OpenRunspaceOperation;
                    if (operation2 != null)
                    {
                        string computerName = operation2.OperatedRunspace.ConnectionInfo.ComputerName;
                        if (exception2.ErrorCode != -2144108135)
                        {
                            str = "[" + computerName + "] ";
                            if (!string.IsNullOrEmpty(exception2.Message))
                            {
                                str = str + exception2.Message;
                            }
                            else if (!string.IsNullOrEmpty(exception2.TransportMessage))
                            {
                                str = str + exception2.TransportMessage;
                            }
                            break;
                        }
                        string str3 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception2.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" });
                        str = "[" + computerName + "] " + str3;
                    }
                }
                break;

            default:
                return;
            }
            PSRemotingDataStructureException exception3 = reason as PSRemotingDataStructureException;

            if (exception3 != null)
            {
                OpenRunspaceOperation operation3 = sender as OpenRunspaceOperation;
                if (operation3 != null)
                {
                    string str4 = operation3.OperatedRunspace.ConnectionInfo.ComputerName;
                    str = "[" + str4 + "] " + exception3.Message;
                }
            }
            if (reason == null)
            {
                reason = new RuntimeException(base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, new object[] { state }));
            }
            string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError((exception2 != null) ? exception2.ErrorCode : 0, this._defaultFQEID);

            errorRecord = new ErrorRecord(reason, operatedRunspace, fQEIDFromTransportError, ErrorCategory.OpenError, null, null, null, null, null, str, null);
            Action <Cmdlet> action2 = cmdlet => cmdlet.WriteError(errorRecord);

            if (objectWriter.IsOpen)
            {
                objectWriter.Write(action2);
            }
            this.toDispose.Add(operatedRunspace);
        }
示例#27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PowerShellProcessInstance"/> class. Initializes the underlying dotnet process class.
        /// </summary>
        /// <param name="powerShellVersion">Specifies the version of powershell.</param>
        /// <param name="credential">Specifies a user account credentials.</param>
        /// <param name="initializationScript">Specifies a script that will be executed when the powershell process is initialized.</param>
        /// <param name="useWow64">Specifies if the powershell process will be 32-bit.</param>
        /// <param name="workingDirectory">Specifies the initial working directory for the new powershell process.</param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64, string workingDirectory)
        {
            string exePath = PwshExePath;
            bool   startingWindowsPowerShell51 = false;

#if !UNIX
            // if requested PS version was "5.1" then we start Windows PS instead of PS Core
            startingWindowsPowerShell51 = (powerShellVersion != null) && (powerShellVersion.Major == 5) && (powerShellVersion.Minor == 1);
            if (startingWindowsPowerShell51)
            {
                if (WinPwshExePath is null)
                {
                    throw new PSInvalidOperationException(RemotingErrorIdStrings.WindowsPowerShellNotPresent);
                }

                exePath = WinPwshExePath;

                if (useWow64)
                {
                    string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

                    if ((!string.IsNullOrEmpty(procArch)) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
                                                              procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                    {
                        exePath = WinPwshExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");

                        if (!File.Exists(exePath))
                        {
                            string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.WowComponentNotPresent, exePath);
                            throw new PSInvalidOperationException(message);
                        }
                    }
                }
            }
#endif
            // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
            // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
            _startInfo = new ProcessStartInfo
            {
                FileName               = exePath,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true,
#if !UNIX
                LoadUserProfile = true,
#endif
            };
#if !UNIX
            if (startingWindowsPowerShell51)
            {
                _startInfo.ArgumentList.Add("-Version");
                _startInfo.ArgumentList.Add("5.1");

                // if starting Windows PowerShell, need to remove PowerShell specific segments of PSModulePath
                _startInfo.Environment["PSModulePath"] = ModuleIntrinsics.GetWindowsPowerShellModulePath();
            }
#endif
            _startInfo.ArgumentList.Add("-s");
            _startInfo.ArgumentList.Add("-NoLogo");
            _startInfo.ArgumentList.Add("-NoProfile");

            if (!string.IsNullOrWhiteSpace(workingDirectory) && !startingWindowsPowerShell51)
            {
                _startInfo.ArgumentList.Add("-wd");
                _startInfo.ArgumentList.Add(workingDirectory);
            }

            if (initializationScript != null)
            {
                var scriptBlockString = initializationScript.ToString();
                if (!string.IsNullOrEmpty(scriptBlockString))
                {
                    var encodedCommand = Convert.ToBase64String(Encoding.Unicode.GetBytes(scriptBlockString));
                    _startInfo.ArgumentList.Add("-EncodedCommand");
                    _startInfo.ArgumentList.Add(encodedCommand);
                }
            }

            if (credential != null)
            {
                Net.NetworkCredential netCredential = credential.GetNetworkCredential();

                _startInfo.UserName = netCredential.UserName;
                _startInfo.Domain   = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
                _startInfo.Password = credential.Password;
            }

            Process = new Process {
                StartInfo = _startInfo, EnableRaisingEvents = true
            };
        }
示例#28
0
 public InvalidJobStateException(JobState currentState, string actionMessage) : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidJobStateSpecific, new object[] { currentState, actionMessage }))
 {
     this.currState = currentState;
 }
示例#29
0
 internal InvalidJobStateException(JobState currentState) : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidJobStateGeneral, new object[0]))
 {
     this.currState = currentState;
 }
示例#30
0
 public InvalidJobStateException() : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidJobStateGeneral, new object[0]))
 {
 }