public PowerShellRunner()
 {
     var psHost = new PSHost(new PSHostUserInterface(this)); 
     runSpace = RunspaceFactory.CreateRunspace(psHost);
     runSpace.Open();
     // Allows scripts to be run for this process
     using (var pipeline = runSpace.CreatePipeline())
     {
         pipeline.Commands.AddScript("Set-ExecutionPolicy -ExecutionPolicy unrestricted -Scope Process -Force");
         pipeline.Invoke();
     }
 }
        internal static SPOnlineConnection InstantiateWebloginConnection(Uri url, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            var context = PnPClientContext.ConvertFrom(authManager.GetWebLoginClientContext(url.ToString()), retryCount, retryWait * 1000);

            if (context != null)
            {
                context.RetryCount      = retryCount;
                context.Delay           = retryWait * 1000;
                context.ApplicationName = Properties.Resources.ApplicationName;
                context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
                context.DisableReturnValueCache = true;
#elif SP2016 || SP2019
                context.DisableReturnValueCache = true;
#endif
                var connectionType = ConnectionType.OnPrem;
                if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
                {
                    connectionType = ConnectionType.O365;
                }
                if (skipAdminCheck == false)
                {
                    if (IsTenantAdminSite(context))
                    {
                        connectionType = ConnectionType.TenantAdmin;
                    }
                }
                var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.InteractiveLogin);
                spoConnection.ConnectionMethod = Model.ConnectionMethod.WebLogin;
                return(spoConnection);
            }
            throw new Exception("Error establishing a connection, context is null");
        }
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool disableTelemetry, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            if (realm == null)
            {
                realm = GetRealmFromTargetUrl(url);
            }

            PnPClientContext context;

            if (url.DnsSafeHost.Contains("spoppe.com"))
            {
                context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login"), retryCount, retryWait * 1000);
            }
            else
            {
                context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret), retryCount, retryWait * 1000);
            }

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016 || SP2019
            context.DisableReturnValueCache = true;
#endif
            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.SPClientSecret));
        }
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePEM, string privateKeyPEM, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            string           password    = new System.Net.NetworkCredential(string.Empty, certificatePassword).Password;
            X509Certificate2 certificate = CertificateHelper.GetCertificateFromPEMstring(certificatePEM, privateKeyPEM, password);

            return(InitiateAzureAdAppOnlyConnectionWithCert(url, clientId, tenant, minimalHealthScore, retryCount, retryWait, requestTimeout, tenantAdminUrl, host, disableTelemetry, skipAdminCheck, azureEnvironment, certificate, true));
        }
        internal static SPOnlineConnection InitiateAzureADNativeApplicationConnection(Uri url, string clientId, Uri redirectUri, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();


            string         appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string         configFile    = Path.Combine(appDataFolder, "SharePointPnP.PowerShell\\tokencache.dat");
            FileTokenCache cache         = new FileTokenCache(configFile);

            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADNativeApplicationAuthenticatedContext(url.ToString(), clientId, redirectUri, cache, azureEnvironment), retryCount, retryWait * 10000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADNativeApp);

            spoConnection.ConnectionMethod = Model.ConnectionMethod.AzureADNativeApplication;
            return(spoConnection);
        }
        internal static SPOnlineConnection InstantiateGraphAccessTokenConnection(string accessToken, PSHost host, bool disableTelemetry)
        {
            var jwtToken    = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accessToken);
            var tokenResult = new TokenResult();

            tokenResult.AccessToken = accessToken;
            tokenResult.ExpiresOn   = jwtToken.ValidTo;
            var spoConnection = new SPOnlineConnection(tokenResult, ConnectionMethod.AccessToken, ConnectionType.O365, 0, 0, 0, PnPPSVersionTag, host, disableTelemetry, InitializationType.Graph);

            spoConnection.ConnectionMethod = ConnectionMethod.GraphDeviceLogin;
            return(spoConnection);
        }
示例#7
0
        /// <summary>
        /// Determine if we should run the specified file.
        /// </summary>
        /// <param name="commandInfo">Info on entity to be run.</param>
        /// <param name="origin">The dispatch origin of a command.</param>
        /// <param name="host">Allows access to the host.</param>
        /// <remarks>
        /// This method throws SecurityException in case running is not allowed.
        /// </remarks>
        /// <exception cref="System.Management.Automation.PSSecurityException">
        /// If the derived security manager threw an exception or returned
        /// false with a reason.
        /// </exception>
        internal void ShouldRunInternal(CommandInfo commandInfo,
                                        CommandOrigin origin,
                                        PSHost host)
        {
#if UNIX
            // TODO:PSL this is a workaround since the exception below
            // hides the internal issue of what's going on in terms of
            // execution policy.
            // On non-Windows platform Set/Get-ExecutionPolicy throw
            // PlatformNotSupportedException
            return;
#else
#if DEBUG
            // If we are debugging, let the unit tests swap the file from beneath us
            if (commandInfo.CommandType == CommandTypes.ExternalScript)
            {
                while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPreDelay") != null)
                {
                    System.Threading.Thread.Sleep(100);
                }
            }
#endif

            bool      result       = false;
            bool      defaultCatch = false;
            Exception authorizationManagerException = null;

            try
            {
                lock (_policyCheckLock)
                {
                    result = this.ShouldRun(commandInfo, origin, host, out authorizationManagerException);
                }

#if DEBUG
                // If we are debugging, let the unit tests swap the file from beneath us
                if (commandInfo.CommandType == CommandTypes.ExternalScript)
                {
                    while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPostDelay") != null)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                }
#endif
            }
            catch (Exception e) // Catch-all OK. 3rd party callout
            {
                authorizationManagerException = e;

                defaultCatch = true;
                result       = false;
            }

            if (!result)
            {
                if (authorizationManagerException != null)
                {
                    if (authorizationManagerException is PSSecurityException)
                    {
                        throw authorizationManagerException;
                    }
                    else
                    {
                        string message = authorizationManagerException.Message;
                        if (defaultCatch)
                        {
                            message = AuthorizationManagerBase.AuthorizationManagerDefaultFailureReason;
                        }

                        PSSecurityException securityException = new PSSecurityException(message, authorizationManagerException);
                        throw securityException;
                    }
                }
                else
                {
                    throw new PSSecurityException(AuthorizationManagerBase.AuthorizationManagerDefaultFailureReason);
                }
            }
#endif
        }
示例#8
0
 /// <summary>
 /// Sets the reference to the external host and the internal UI to a temporary
 /// new host and its UI. This exists so that if the PowerShell/Pipeline
 /// object has a different host from the runspace it can set it's host during its
 /// invocation, and then revert it after the invocation is completed.
 /// </summary>
 /// <seealso cref="RevertHostRef"/> and
 internal void SetHostRef(PSHost psHost)
 {
     _externalHostRef.Override(psHost);
     _internalUIRef.Override(new InternalHostUserInterface(psHost.UI, this));
 }
示例#9
0
        private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason)
        {
            bool policyCheckPassed = false;

            reason = null;
            string path = script.Path;
            string reasonMessage;

            // path is assumed to be fully qualified here
            if (path.IndexOf(System.IO.Path.DirectorySeparatorChar) < 0)
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            if (path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) == (path.Length - 1))
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            FileInfo fi = new FileInfo(path);

            // Return false if the file does not exist, so that
            // we don't introduce a race condition
            if (!fi.Exists)
            {
                reason = new FileNotFoundException(path);
                return(false);
            }

            // Quick exit if we don't support the file type
            if (!IsSupportedExtension(fi.Extension))
            {
                return(true);
            }

            // Get the execution policy
            _executionPolicy = SecuritySupport.GetExecutionPolicy(_shellId);

            // See if they want to bypass the authorization manager
            if (_executionPolicy == ExecutionPolicy.Bypass)
            {
                return(true);
            }

            // Always check the SAFER APIs if code integrity isn't being handled system-wide through
            // WLDP or AppLocker. In those cases, the scripts will be run in ConstrainedLanguage.
            // Otherwise, block.
            // SAFER APIs are not on CSS or OneCore
            if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce)
            {
                SaferPolicy saferPolicy    = SaferPolicy.Disallowed;
                int         saferAttempt   = 0;
                bool        gotSaferPolicy = false;

                // We need to put in a retry workaround, as the SAFER APIs fail when under stress.
                while ((!gotSaferPolicy) && (saferAttempt < 5))
                {
                    try
                    {
                        saferPolicy    = SecuritySupport.GetSaferPolicy(path, null);
                        gotSaferPolicy = true;
                    }
                    catch (System.ComponentModel.Win32Exception)
                    {
                        if (saferAttempt > 4)
                        {
                            throw;
                        }

                        saferAttempt++;
                        System.Threading.Thread.Sleep(100);
                    }
                }

                // If the script is disallowed via AppLocker, block the file
                // unless the system-wide lockdown policy is "Enforce" (where all PowerShell
                // scripts are in blocked). If the system policy is "Enforce", then the
                // script will be allowed (but ConstrainedLanguage will be applied).
                if (saferPolicy == SaferPolicy.Disallowed)
                {
                    reasonMessage = StringUtil.Format(Authenticode.Reason_DisallowedBySafer, path);
                    reason        = new UnauthorizedAccessException(reasonMessage);

                    return(false);
                }
            }

            if (_executionPolicy == ExecutionPolicy.Unrestricted)
            {
                // Product binaries are always trusted
                // This avoids signature and security zone checks
                if (SecuritySupport.IsProductBinary(path))
                {
                    return(true);
                }

                // We need to give the "Remote File" warning
                // if the file originated from the internet
                if (!IsLocalFile(fi.FullName))
                {
                    // Get the signature of the file.
                    if (string.IsNullOrEmpty(script.ScriptContents))
                    {
                        reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path);
                        reason        = new UnauthorizedAccessException(reasonMessage);

                        return(false);
                    }

                    Signature signature = GetSignatureWithEncodingRetry(path, script);

                    // The file is signed, with a publisher that
                    // we trust
                    if (signature.Status == SignatureStatus.Valid)
                    {
                        // The file is signed by a trusted publisher
                        if (IsTrustedPublisher(signature, path))
                        {
                            policyCheckPassed = true;
                        }
                    }

                    // We don't care about the signature.  If you distrust them,
                    // or the signature does not exist, we prompt you only
                    // because it's remote.
                    if (!policyCheckPassed)
                    {
                        RunPromptDecision decision = RunPromptDecision.DoNotRun;

                        // Get their remote prompt answer, allowing them to
                        // enter nested prompts, if wanted.
                        do
                        {
                            decision = RemoteFilePrompt(path, host);

                            if (decision == RunPromptDecision.Suspend)
                            {
                                host.EnterNestedPrompt();
                            }
                        } while (decision == RunPromptDecision.Suspend);

                        switch (decision)
                        {
                        case RunPromptDecision.RunOnce:
                            policyCheckPassed = true;
                            break;

                        case RunPromptDecision.DoNotRun:
                        default:
                            policyCheckPassed = false;
                            reasonMessage     = StringUtil.Format(Authenticode.Reason_DoNotRun, path);
                            reason            = new UnauthorizedAccessException(reasonMessage);
                            break;
                        }
                    }
                }
                else
                {
                    policyCheckPassed = true;
                }
            }
            // Don't need to check the signature if the file is local
            // and we're in "RemoteSigned" mode
            else if ((IsLocalFile(fi.FullName)) &&
                     (_executionPolicy == ExecutionPolicy.RemoteSigned))
            {
                policyCheckPassed = true;
            }
            else if ((_executionPolicy == ExecutionPolicy.AllSigned) ||
                     (_executionPolicy == ExecutionPolicy.RemoteSigned))
            {
                // if policy requires signature verification,
                // make it so.

                // Get the signature of the file.
                if (string.IsNullOrEmpty(script.ScriptContents))
                {
                    reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path);
                    reason        = new UnauthorizedAccessException(reasonMessage);

                    return(false);
                }

                Signature signature = GetSignatureWithEncodingRetry(path, script);

                // The file is signed.
                if (signature.Status == SignatureStatus.Valid)
                {
                    // The file is signed by a trusted publisher
                    if (IsTrustedPublisher(signature, path))
                    {
                        policyCheckPassed = true;
                    }
                    // The file is signed by an unknown publisher,
                    // So prompt.
                    else
                    {
                        policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature);
                    }
                }
                // The file is UnknownError, NotSigned, HashMismatch,
                // NotTrusted, NotSupportedFileFormat
                else
                {
                    policyCheckPassed = false;

                    if (signature.Status == SignatureStatus.NotTrusted)
                    {
                        reason = new UnauthorizedAccessException(
                            StringUtil.Format(Authenticode.Reason_NotTrusted,
                                              path,
                                              signature.SignerCertificate.SubjectName.Name));
                    }
                    else
                    {
                        reason = new UnauthorizedAccessException(
                            StringUtil.Format(Authenticode.Reason_Unknown,
                                              path,
                                              signature.StatusMessage));
                    }
                }
            }
            else // if(executionPolicy == ExecutionPolicy.Restricted)
            {
                // Deny everything
                policyCheckPassed = false;

                // But accept mshxml files from publishers that we
                // trust, or files in the system protected directories
                bool reasonSet = false;
                if (string.Equals(fi.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase))
                {
                    string[] trustedDirectories = new string[]
                    { Platform.GetFolderPath(Environment.SpecialFolder.System),
                      Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles) };

                    foreach (string trustedDirectory in trustedDirectories)
                    {
                        if (fi.FullName.StartsWith(trustedDirectory, StringComparison.OrdinalIgnoreCase))
                        {
                            policyCheckPassed = true;
                        }
                    }

                    if (!policyCheckPassed)
                    {
                        // Get the signature of the file.
                        Signature signature = GetSignatureWithEncodingRetry(path, script);

                        // The file is signed by a trusted publisher
                        if (signature.Status == SignatureStatus.Valid)
                        {
                            if (IsTrustedPublisher(signature, path))
                            {
                                policyCheckPassed = true;
                            }
                            // The file is signed by an unknown publisher,
                            // So prompt.
                            else
                            {
                                policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature);
                                reasonSet         = true;
                            }
                        }
                    }
                }

                if (!policyCheckPassed && !reasonSet)
                {
                    reason = new UnauthorizedAccessException(
                        StringUtil.Format(Authenticode.Reason_RestrictedMode,
                                          path));
                }
            }

            return(policyCheckPassed);
        }
示例#10
0
        internal static SPIaCConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, PSHost host, bool currentCredentials, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            ClientContext context = new ClientContext(url.AbsoluteUri)
            {
                ApplicationName = Resources.ApplicationName,
                RequestTimeout  = requestTimeout
            };

            if (!currentCredentials)
            {
                try
                {
                    SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(credentials.UserName, credentials.Password);
                    context.Credentials = onlineCredentials;
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (IdcrlException iex)
                    {
                        System.Diagnostics.Trace.TraceError("Authentication Exception {0}", iex.Message);
                        return(null);
                    }
                    catch (WebException wex)
                    {
                        System.Diagnostics.Trace.TraceError("Authentication Exception {0}", wex.Message);
                        return(null);
                    }
                    catch (ClientRequestException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                    catch (ServerException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                }
                catch (ArgumentException)
                {
                    // OnPrem?
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                    catch (ServerException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                }
            }
            else
            {
                if (credentials != null)
                {
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                }
            }

            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }

            return(new SPIaCConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, credentials, url.ToString()));
        }
示例#11
0
        internal static SPIaCConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, string appDomain, string resourceUri, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            if (realm == null)
            {
                realm = url.GetRealmFromTargetUrl();
            }

            var context = authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret);

            context.ApplicationName = Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;

            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }

            var connection = new SPIaCConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString())
            {
                AddInCredentials = new SPOAddInKeys()
                {
                    AppId  = clientId,
                    AppKey = clientSecret,
                    Realm  = realm
                }
            };

            return(connection);
        }
 public MsmqSetup(PSHost Host) : base(Host)
 {
 }
示例#13
0
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            Core.AuthenticationManager authManager = new Core.AuthenticationManager();
            if (realm == null)
            {
                realm = GetRealmFromTargetUrl(url);
            }

            var context = authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret);

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;

            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
 public static string GetInteractiveHtml(PSHost host,
                                         bool includeCurrentLine, TrailingSpaceBehavior behavior)
 {
     return(string.Concat(GetInteractiveHtmlImpl(
                              Capturer.StreamCapture(host, includeCurrentLine, behavior, false))));
 }
 /// <summary>
 /// Captures the console as a string.
 /// </summary>
 public static string Capture(PSHost host,
                              bool includeCurrentLine,
                              TrailingSpaceBehavior behavior)
 {
     return(string.Concat(StreamCapture(host, includeCurrentLine, behavior)));
 }
        /// <summary>
        /// Enumerates the substrings of HTML-formatted ConsoleLog.
        /// </summary>
        /// <param name="host">$Host from PowerShell.</param>
        /// <param name="includeCurrentLine">Whether the current line should be included.
        /// This can be set to $False if the command is used interactively.</param>
        /// <param name="behavior">Behavior of trailing space characters.</param>
        public static IEnumerable <string> StreamCapture(PSHost host,
                                                         bool includeCurrentLine,
                                                         TrailingSpaceBehavior behavior)
        {
            ConsoleColor fgDefault = ConsoleColor.White, bgDefault = ConsoleColor.Black;
            ConsoleColor fgLine = ConsoleColor.White, bgLine = ConsoleColor.Black;
            ConsoleColor fg = ConsoleColor.White, bg = ConsoleColor.Black;
            bool         emptyLine = true;

            /* The loop directly walks the tree, so we do not need
            ** the tree to be stored in the returned objects.
            ** Setting "populate" to $False make it GC-efficient. */
            foreach (object obj in Capturer.StreamCapture(host, includeCurrentLine, behavior, false))
            {
                ConsoleLog console = obj as ConsoleLog;
                if (!ReferenceEquals(console, null))
                {
                    yield return("<pre class=\"gl-console gl-console-fg-");

                    yield return(Helper.ColorToName(fgDefault = console.Foreground));

                    yield return(" gl-console-bg-");

                    yield return(Helper.ColorToName(bgLine = bgDefault = console.Background));

                    yield return("\" lang=\"console\" data-width=\"");

                    yield return(console.Width.ToString(CultureInfo.InvariantCulture));

                    yield return("\">\n");

                    continue;
                }
                Line line = obj as Line;
                if (!ReferenceEquals(line, null))
                {
                    yield return("<code class=\"gl-console-line");

                    if ((fgLine = line.Foreground) != fgDefault)
                    {
                        yield return(" gl-console-fg-");

                        yield return(Helper.ColorToName(fgLine));
                    }
                    yield return(" gl-console-bg-");

                    ConsoleColor bgLine2 = line.Background;
                    if (bgLine != bgLine2)
                    {
                        yield return("change gl-console-bg-");
                    }
                    yield return((bgLine = bgLine2) != bgDefault
                        ? Helper.ColorToName(bgLine2) : "none");

                    yield return("\">");

                    emptyLine = true;
                    continue;
                }
                Span span = obj as Span;
                if (!ReferenceEquals(span, null))
                {
                    emptyLine = false;
                    fg        = span.Foreground;
                    bg        = span.Background;
                    if (fg == fgLine && bg == bgLine)
                    {
                        yield return("<span>");

                        yield return(Helper.HtmlEncode(span.Content));

                        yield return("</span>");
                    }
                    else if (fg == fgLine && bg != bgLine)
                    {
                        yield return("<span class=\"gl-console-bg-");

                        yield return(Helper.ColorToName(bg));

                        yield return("\">");

                        yield return(Helper.HtmlEncode(span.Content));

                        yield return("</span>");
                    }
                    else if (fg != fgLine && bg == bgLine)
                    {
                        yield return("<span class=\"gl-console-fg-");

                        yield return(Helper.ColorToName(fg));

                        yield return("\">");

                        yield return(Helper.HtmlEncode(span.Content));

                        yield return("</span>");
                    }
                    else
                    {
                        yield return("<span class=\"gl-console-fg-");

                        yield return(Helper.ColorToName(fg));

                        yield return(" gl-console-bg-");

                        yield return(Helper.ColorToName(bg));

                        yield return("\">");

                        yield return(Helper.HtmlEncode(span.Content));

                        yield return("</span>");
                    }
                    continue;
                }
                /* A line has ended. */
                yield return(emptyLine ? "<span> </span></code>\n" : "</code>\n");
            }
            yield return("</pre>");
        }
示例#17
0
 public PowerShellCustomConfirmation(PSHost host)
 {
     this.host = host;
 }
示例#18
0
        /// <summary>
        /// Determines if should run the specified command.  Please see the
        /// class summary for an overview of the semantics enforced by this
        /// authorization manager.
        /// </summary>
        /// <param name="commandInfo">
        /// The command to be run.
        /// </param>
        /// <param name="origin">
        /// The origin of the command.
        /// </param>
        /// <param name="host">
        /// The PSHost executing the command.
        /// </param>
        /// <param name="reason">
        /// If access is denied, this parameter provides a specialized
        /// Exception as the reason.
        /// </param>
        /// <returns>
        /// True if the command should be run.  False otherwise.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        /// CommandInfo is invalid. This may occur if
        /// commandInfo.Name is null or empty.
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// CommandInfo is null.
        /// </exception>
        /// <exception cref="System.IO.FileNotFoundException">
        /// The file specified by commandInfo.Path is not found.
        /// </exception>
        protected internal override bool ShouldRun(CommandInfo commandInfo,
                                                   CommandOrigin origin,
                                                   PSHost host,
                                                   out Exception reason)
        {
            Dbg.Diagnostics.Assert(commandInfo != null, "caller should validate the parameter");

            bool allowRun = false;

            reason = null;
            Utils.CheckArgForNull(commandInfo, "commandInfo");
            Utils.CheckArgForNullOrEmpty(commandInfo.Name, "commandInfo.Name");

            switch (commandInfo.CommandType)
            {
            case CommandTypes.Cmdlet:
                // Always allow cmdlets to run
                allowRun = true;
                break;

            case CommandTypes.Alias:
                //
                // we do not care about verifying an alias as we will
                // get subsequent call(s) for commands/scripts
                // when the alias is expanded.
                //
                allowRun = true;
                break;

            case CommandTypes.Function:
            case CommandTypes.Filter:
            case CommandTypes.Configuration:
                //
                // we do not check functions/filters.
                // we only perform script level check.
                //
                allowRun = true;
                break;

            case CommandTypes.Script:
                //
                // Allow scripts that are built into the
                // runspace configuration to run.
                //
                allowRun = true;
                break;

            case CommandTypes.ExternalScript:
                ExternalScriptInfo si = commandInfo as ExternalScriptInfo;
                if (si is null)
                {
                    reason = PSTraceSource.NewArgumentException("scriptInfo");
                }
                else
                {
                    bool etwEnabled = ParserEventSource.Log.IsEnabled();
                    if (etwEnabled)
                    {
                        ParserEventSource.Log.CheckSecurityStart(si.Path);
                    }
                    allowRun = CheckPolicy(si, host, out reason);
                    if (etwEnabled)
                    {
                        ParserEventSource.Log.CheckSecurityStop(si.Path);
                    }
                }

                break;

            case CommandTypes.Application:
                //
                // We do not check executables -- that is done by Windows
                //
                allowRun = true;
                break;
            }

            return(allowRun);
        }
示例#19
0
        /// <summary>
        /// Constructor that creates a FormatTable from a set of format files.
        /// </summary>
        /// <param name="formatFiles">
        /// Format files to load for format information.
        /// </param>
        /// <param name="authorizationManager">
        /// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed)
        /// </param>
        /// <param name="host">
        /// Host passed to <paramref name="authorizationManager"/>.  Can be null if no interactive questions should be asked.
        /// </param>
        /// <exception cref="ArgumentException">
        /// 1. Path {0} is not fully qualified. Specify a fully qualified type file path.
        /// </exception>
        /// <exception cref="FormatTableLoadException">
        /// 1. There were errors loading Formattable. Look in the Errors property to
        /// get detailed error messages.
        /// </exception>
        internal FormatTable(IEnumerable <string> formatFiles, AuthorizationManager authorizationManager, PSHost host)
        {
            if (null == formatFiles)
            {
                throw PSTraceSource.NewArgumentNullException("formatFiles");
            }

            _formatDBMgr = new TypeInfoDataBaseManager(formatFiles, true, authorizationManager, host);
        }
示例#20
0
        private RunPromptDecision AuthenticodePrompt(string path,
                                                     Signature signature,
                                                     PSHost host)
        {
            if ((host is null) || (host.UI is null))
            {
                return(RunPromptDecision.DoNotRun);
            }

            RunPromptDecision decision = RunPromptDecision.DoNotRun;

            if (signature is null)
            {
                return(decision);
            }

            switch (signature.Status)
            {
            //
            // we do not allow execution in any one of the
            // following cases
            //
            case SignatureStatus.UnknownError:
            case SignatureStatus.NotSigned:
            case SignatureStatus.HashMismatch:
            case SignatureStatus.NotSupportedFileFormat:
                decision = RunPromptDecision.DoNotRun;
                break;

            case SignatureStatus.Valid:
                Collection <ChoiceDescription> choices = GetAuthenticodePromptChoices();

                string promptCaption =
                    Authenticode.AuthenticodePromptCaption;

                string promptText;

                if (signature.SignerCertificate is null)
                {
                    promptText =
                        StringUtil.Format(Authenticode.AuthenticodePromptText_UnknownPublisher,
                                          path);
                }
                else
                {
                    promptText =
                        StringUtil.Format(Authenticode.AuthenticodePromptText,
                                          path,
                                          signature.SignerCertificate.SubjectName.Name
                                          );
                }

                int userChoice =
                    host.UI.PromptForChoice(promptCaption,
                                            promptText,
                                            choices,
                                            (int)RunPromptDecision.DoNotRun);
                decision = (RunPromptDecision)userChoice;

                break;

            //
            // if the publisher is not trusted, we prompt and
            // ask the user if s/he wants to allow it to run
            //
            default:
                decision = RunPromptDecision.DoNotRun;
                break;
            }

            return(decision);
        }
        private static SPOnlineConnection InstantiateHighTrustConnection(ClientContext context, string url, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck)
        {
            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if SP2016 || SP2019
            context.DisableReturnValueCache = true;
#endif
            var connectionType = ConnectionType.OnPrem;
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url, tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.HighTrust));
        }
示例#22
0
        protected XmlDocument LoadXmlDocumentFromFileLoadingInfo(AuthorizationManager authorizationManager, PSHost host, out bool isFullyTrusted)
        {
            // get file contents
            ExternalScriptInfo ps1xmlInfo   = new ExternalScriptInfo(FilePath, FilePath);
            string             fileContents = ps1xmlInfo.ScriptContents;

            isFullyTrusted = false;
            if (ps1xmlInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage)
            {
                isFullyTrusted = true;
            }

            if (authorizationManager != null)
            {
                try
                {
                    authorizationManager.ShouldRunInternal(ps1xmlInfo, CommandOrigin.Internal, host);
                }
                catch (PSSecurityException reason)
                {
                    string errorMessage = StringUtil.Format(TypesXmlStrings.ValidationException,
                                                            string.Empty /* TODO/FIXME snapin */,
                                                            FilePath,
                                                            reason.Message);
                    ReportLogEntryHelper(errorMessage, XmlLoaderLoggerEntry.EntryType.Error, failToLoadFile: true);
                    return(null);
                }
            }

            // load file into XML document
            try
            {
                XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
                    fileContents,
                    true,  /* preserve whitespace, comments, etc. */
                    null); /* default maxCharacters */
                this.ReportTrace("XmlDocument loaded OK");
                return(doc);
            }
            catch (XmlException e)
            {
                this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFile, FilePath, e.Message));
                this.ReportTrace("XmlDocument discarded");
                return(null);
            }
        }
        internal static SPOnlineConnection InstantiateGraphDeviceLoginConnection(bool launchBrowser, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, Action <string> messageCallback, Action <string> progressCallback, Func <bool> cancelRequest, PSHost host, bool disableTelemetry)
        {
            var        connectionUri = new Uri("https://graph.microsoft.com");
            HttpClient client        = new HttpClient();
            var        result        = client.GetStringAsync($"https://login.microsoftonline.com/common/oauth2/devicecode?resource={connectionUri.Scheme}://{connectionUri.Host}&client_id={SPOnlineConnection.DeviceLoginAppId}").GetAwaiter().GetResult();
            var        returnData    = JsonConvert.DeserializeObject <Dictionary <string, string> >(result);

            SPOnlineConnection spoConnection = null;

            if (launchBrowser)
            {
                Utilities.Clipboard.Copy(returnData["user_code"]);
                messageCallback("Code has been copied to clipboard");
#if !NETSTANDARD2_0
                BrowserHelper.OpenBrowser(returnData["verification_url"], (success) =>
                {
                    if (success)
                    {
                        var tokenResult = GetTokenResult(connectionUri, returnData, messageCallback, progressCallback, cancelRequest);
                        if (tokenResult != null)
                        {
                            progressCallback("Token received");
                            spoConnection = new SPOnlineConnection(tokenResult, ConnectionMethod.GraphDeviceLogin, ConnectionType.O365, minimalHealthScore, retryCount, retryWait, PnPPSVersionTag, host, disableTelemetry, InitializationType.GraphDeviceLogin);
                        }
                        else
                        {
                            progressCallback("No token received.");
                        }
                    }
                });
#else
                OpenBrowser(returnData["verification_url"]);
                messageCallback(returnData["message"]);

                var tokenResult = GetTokenResult(connectionUri, returnData, messageCallback, progressCallback, cancelRequest);

                if (tokenResult != null)
                {
                    progressCallback("Token received");
                    spoConnection = new SPOnlineConnection(tokenResult, ConnectionMethod.GraphDeviceLogin, ConnectionType.O365, minimalHealthScore, retryCount, retryWait, PnPPSVersionTag, host, disableTelemetry, InitializationType.GraphDeviceLogin);
                }
                else
                {
                    progressCallback("No token received.");
                }
#endif
            }
            else
            {
                messageCallback(returnData["message"]);


                var tokenResult = GetTokenResult(connectionUri, returnData, messageCallback, progressCallback, cancelRequest);

                if (tokenResult != null)
                {
                    progressCallback("Token received");
                    spoConnection = new SPOnlineConnection(tokenResult, ConnectionMethod.GraphDeviceLogin, ConnectionType.O365, minimalHealthScore, retryCount, retryWait, PnPPSVersionTag, host, disableTelemetry, InitializationType.GraphDeviceLogin);
                }
                else
                {
                    progressCallback("No token received.");
                }
            }
            spoConnection.ConnectionMethod = ConnectionMethod.GraphDeviceLogin;
            return(spoConnection);
        }
示例#24
0
        //internal static Uri RedirectUri;
        //internal static string ClientId;

        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            if (realm == null)
            {
                realm = GetRealmFromTargetUrl(url);
            }

            var context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret), retryCount, retryWait * 1000);

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif
            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant,
                                                                            string thumbprint, int minimalHealthScore,
                                                                            int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host,
                                                                            bool disableTelemetry, bool skipAdminCheck = false,
                                                                            AzureEnvironment azureEnvironment          = AzureEnvironment.Production)
        {
            X509Certificate2 certificate = CertificateHelper.GetCertificatFromStore(thumbprint);

            return(InitiateAzureAdAppOnlyConnectionWithCert(url, clientId, tenant, minimalHealthScore, retryCount, retryWait, requestTimeout, tenantAdminUrl, host, disableTelemetry, skipAdminCheck, azureEnvironment, certificate, false));
        }
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, PSHost host, bool currentCredentials, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false, ClientAuthenticationMode authenticationMode = ClientAuthenticationMode.Default)
        {
            var context = new PnPClientContext(url.AbsoluteUri);

            context.RetryCount      = retryCount;
            context.Delay           = retryWait * 1000;
            context.ApplicationName = Properties.Resources.ApplicationName;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif
            context.RequestTimeout = requestTimeout;

            context.AuthenticationMode = authenticationMode;

            if (authenticationMode == ClientAuthenticationMode.FormsAuthentication)
            {
                var formsAuthInfo = new FormsAuthenticationLoginInfo(credentials.UserName, EncryptionUtility.ToInsecureString(credentials.Password));
                context.FormsAuthenticationLoginInfo = formsAuthInfo;
            }

            if (!currentCredentials)
            {
                try
                {
                    SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(credentials.UserName, credentials.Password);
                    context.Credentials = onlineCredentials;
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException)
                    {
                        context.ExecutingWebRequest += Ctx_ExecutingWebRequest;
                        context.Credentials          = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                    catch (ServerException)
                    {
                        context.ExecutingWebRequest += Ctx_ExecutingWebRequest;
                        context.Credentials          = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                }
                catch (ArgumentException)
                {
                    // OnPrem?
                    context.ExecutingWebRequest += Ctx_ExecutingWebRequest;
                    context.Credentials          = new NetworkCredential(credentials.UserName, credentials.Password);
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                    catch (ServerException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                }
            }
            else
            {
                if (credentials != null)
                {
                    context.ExecutingWebRequest += Ctx_ExecutingWebRequest;
                    context.Credentials          = new NetworkCredential(credentials.UserName, credentials.Password);
                }
            }
            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, credentials, url.ToString(), tenantAdminUrl, PnPPSVersionTag));
        }
        private static SPOnlineConnection InitiateAzureAdAppOnlyConnectionWithCert(Uri url, string clientId, string tenant,
                                                                                   int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry,
                                                                                   bool skipAdminCheck, AzureEnvironment azureEnvironment, X509Certificate2 certificate, bool certificateFromFile)
        {
            var authManager   = new OfficeDevPnP.Core.AuthenticationManager();
            var clientContext =
                authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificate,
                                                                  azureEnvironment);
            var context = PnPClientContext.ConvertFrom(clientContext, retryCount, retryWait * 1000);

            context.RequestTimeout = requestTimeout;
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }

            if (certificateFromFile)
            {
                CleanupCryptoMachineKey(certificate);
            }

            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null,
                                                       url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADAppOnly);

            spoConnection.ConnectionMethod = ConnectionMethod.AzureADAppOnly;

            return(spoConnection);
        }
        internal static SPOnlineConnection InstantiateAdfsConnection(Uri url, PSCredential credentials, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            var networkCredentials = credentials.GetNetworkCredential();

            string adfsHost;
            string adfsRelyingParty;

            GetAdfsConfigurationFromTargetUri(url, out adfsHost, out adfsRelyingParty);

            if (string.IsNullOrEmpty(adfsHost) || string.IsNullOrEmpty(adfsRelyingParty))
            {
                throw new Exception("Cannot retrieve ADFS settings.");
            }

            var context = PnPClientContext.ConvertFrom(authManager.GetADFSUserNameMixedAuthenticatedContext(url.ToString(), networkCredentials.UserName, networkCredentials.Password, networkCredentials.Domain, adfsHost, adfsRelyingParty), retryCount, retryWait * 1000);

            context.RetryCount = retryCount;
            context.Delay      = retryWait * 1000;

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif

            var connectionType = ConnectionType.OnPrem;

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag));
        }
        internal static SPOnlineConnection InitiateAccessTokenConnection(Uri url, string accessToken, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADAccessTokenAuthenticatedContext(url.ToString(), accessToken), retryCount, retryWait);
            var connectionType = ConnectionType.O365;

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.Token);

            spoConnection.ConnectionMethod = Model.ConnectionMethod.AccessToken;
            return(spoConnection);
        }
        /// <summary>
        /// It loads a database from file(s).
        /// </summary>
        /// <param name="files">*.formal.xml files to be loaded.</param>
        /// <param name="expressionFactory">Expression factory to validate script blocks.</param>
        /// <param name="authorizationManager">
        /// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed)
        /// </param>
        /// <param name="host">
        /// Host passed to <paramref name="authorizationManager"/>.  Can be null if no interactive questions should be asked.
        /// </param>
        /// <param name="preValidated">
        /// True if the format data has been pre-validated (build time, manual testing, etc) so that validation can be
        /// skipped at runtime.
        /// </param>
        /// <param name="logEntries">List of logger entries (errors, etc.) to return to the caller.</param>
        /// <param name="success">True if no error occurred.</param>
        /// <returns>A database instance loaded from file(s).</returns>
        private static TypeInfoDataBase LoadFromFileHelper(
            Collection <PSSnapInTypeAndFormatErrors> files,
            PSPropertyExpressionFactory expressionFactory,
            AuthorizationManager authorizationManager,
            PSHost host,
            bool preValidated,
            out List <XmlLoaderLoggerEntry> logEntries,
            out bool success)
        {
            success = true;
            // Holds the aggregated log entries for all files...
            logEntries = new List <XmlLoaderLoggerEntry>();

            // fresh instance of the database
            TypeInfoDataBase db = new TypeInfoDataBase();

            // prepopulate the database with any necessary overriding data
            AddPreLoadIntrinsics(db);

            var etwEnabled = RunspaceEventSource.Log.IsEnabled();

            // load the XML document into a copy of the
            // in memory database
            foreach (PSSnapInTypeAndFormatErrors file in files)
            {
                // Loads formatting data from ExtendedTypeDefinition instance
                if (file.FormatData != null)
                {
                    LoadFormatDataHelper(file.FormatData, expressionFactory, logEntries, ref success, file, db, isBuiltInFormatData: false, isForHelp: false);
                    continue;
                }

                if (etwEnabled)
                {
                    RunspaceEventSource.Log.ProcessFormatFileStart(file.FullPath);
                }

                if (!ProcessBuiltin(file, db, expressionFactory, logEntries, ref success))
                {
                    // Loads formatting data from formatting data XML file
                    XmlFileLoadInfo info =
                        new XmlFileLoadInfo(Path.GetPathRoot(file.FullPath), file.FullPath, file.Errors, file.PSSnapinName);
                    using (TypeInfoDataBaseLoader loader = new TypeInfoDataBaseLoader())
                    {
                        if (!loader.LoadXmlFile(info, db, expressionFactory, authorizationManager, host, preValidated))
                        {
                            success = false;
                        }

                        foreach (XmlLoaderLoggerEntry entry in loader.LogEntries)
                        {
                            // filter in only errors from the current file...
                            if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error)
                            {
                                string mshsnapinMessage = StringUtil.Format(FormatAndOutXmlLoadingStrings.MshSnapinQualifiedError, info.psSnapinName, entry.message);
                                info.errors.Add(mshsnapinMessage);
                                if (entry.failToLoadFile)
                                {
                                    file.FailToLoadFile = true;
                                }
                            }
                        }
                        // now aggregate the entries...
                        logEntries.AddRange(loader.LogEntries);
                    }
                }

                if (etwEnabled)
                {
                    RunspaceEventSource.Log.ProcessFormatFileStop(file.FullPath);
                }
            }

            // add any sensible defaults to the database
            AddPostLoadIntrinsics(db);

            return(db);
        }
 public PowerShellRunner()
 {
     var psHost = new PSHost(new PSHostUserInterface(this)); 
     runSpace = RunspaceFactory.CreateRunspace(psHost);
     runSpace.Open();
 }
示例#32
0
 public ExecutionContext(PSHost host, RunspaceConfiguration config)
     : this()
 {
     RunspaceConfiguration = config;
     LocalHost             = host;
 }