Ejemplo n.º 1
0
        /// <summary>
        /// Gets an array of commands that can be run sequentially to set $profile and run the profile commands.
        /// </summary>
        /// <param name="shellId">The id identifying the host or shell used in profile file names.</param>
        /// <param name="useTestProfile">Used from test not to overwrite the profile file names from development boxes.</param>
        /// <returns></returns>
        internal static PSCommand[] GetProfileCommands(string shellId, bool useTestProfile)
        {
            List <PSCommand> commands = new List <PSCommand>();
            string           allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost;
            PSObject         dollarProfile;

            HostUtilities.GetProfileObjectData(shellId, useTestProfile, out allUsersAllHosts, out allUsersCurrentHost, out currentUserAllHosts, out currentUserCurrentHost, out dollarProfile);

            PSCommand command = new PSCommand();

            command.AddCommand("set-variable");
            command.AddParameter("Name", "profile");
            command.AddParameter("Value", dollarProfile);
            command.AddParameter("Option", ScopedItemOptions.None);
            commands.Add(command);

            string[] profilePaths = new string[] { allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost };
            foreach (string profilePath in profilePaths)
            {
                if (!System.IO.File.Exists(profilePath))
                {
                    continue;
                }

                command = new PSCommand();
                command.AddCommand(profilePath, false);
                commands.Add(command);
            }

            return(commands.ToArray());
        }
Ejemplo n.º 2
0
        internal static PSCommand[] GetProfileCommands(string shellId, bool useTestProfile)
        {
            List <PSCommand> psCommandList        = new List <PSCommand>();
            string           fullProfileFileName1 = HostUtilities.GetFullProfileFileName((string)null, false, useTestProfile);
            string           fullProfileFileName2 = HostUtilities.GetFullProfileFileName(shellId, false, useTestProfile);
            string           fullProfileFileName3 = HostUtilities.GetFullProfileFileName((string)null, true, useTestProfile);
            string           fullProfileFileName4 = HostUtilities.GetFullProfileFileName(shellId, true, useTestProfile);
            PSObject         dollarProfile        = HostUtilities.GetDollarProfile(fullProfileFileName1, fullProfileFileName2, fullProfileFileName3, fullProfileFileName4);
            PSCommand        psCommand1           = new PSCommand();

            psCommand1.AddCommand("set-variable");
            psCommand1.AddParameter("Name", (object)"profile");
            psCommand1.AddParameter("Value", (object)dollarProfile);
            psCommand1.AddParameter("Option", (object)ScopedItemOptions.None);
            psCommandList.Add(psCommand1);
            string[] strArray = new string[4]
            {
                fullProfileFileName1,
                fullProfileFileName2,
                fullProfileFileName3,
                fullProfileFileName4
            };
            foreach (string str in strArray)
            {
                if (File.Exists(str))
                {
                    PSCommand psCommand2 = new PSCommand();
                    psCommand2.AddCommand(str, false);
                    psCommandList.Add(psCommand2);
                }
            }
            return(psCommandList.ToArray());
        }
Ejemplo n.º 3
0
 internal static string GetFullProfileFileName(
     string shellId,
     bool forCurrentUser,
     bool useTestProfile)
 {
     using (HostUtilities.tracer.TraceMethod())
     {
         string str = (string)null;
         string path1;
         if (forCurrentUser)
         {
             path1 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), Utils.ProductNameForDirectory);
         }
         else
         {
             path1 = HostUtilities.GetAllUsersFolderPath(shellId);
             if (string.IsNullOrEmpty(path1))
             {
                 HostUtilities.tracer.WriteLine("could not locate all users folder", new object[0]);
                 return("");
             }
         }
         string path2 = useTestProfile ? "profile_test.ps1" : "profile.ps1";
         if (!string.IsNullOrEmpty(shellId))
         {
             path2 = shellId + "_" + path2;
         }
         return(str = Path.Combine(path1, path2));
     }
 }
Ejemplo n.º 4
0
        internal static ArrayList GetSuggestion(Runspace runspace)
        {
            if (!(runspace is LocalRunspace localRunspace))
            {
                return(new ArrayList());
            }
            bool markVariableValue = localRunspace.ExecutionContext.QuestionMarkVariableValue;

            HistoryInfo[] entries = localRunspace.History.GetEntries(-1L, 1L, (SwitchParameter)true);
            if (entries.Length == 0)
            {
                return(new ArrayList());
            }
            HistoryInfo lastHistory         = entries[0];
            ArrayList   dollarErrorVariable = (ArrayList)localRunspace.GetExecutionContext.DollarErrorVariable;
            object      lastError           = (object)null;

            if (dollarErrorVariable.Count > 0)
            {
                lastError = (object)(dollarErrorVariable[0] as Exception);
                ErrorRecord errorRecord = (ErrorRecord)null;
                if (lastError == null)
                {
                    errorRecord = dollarErrorVariable[0] as ErrorRecord;
                }
                else if (lastError is RuntimeException)
                {
                    errorRecord = ((RuntimeException)lastError).ErrorRecord;
                }
                if (errorRecord != null && errorRecord.InvocationInfo != null)
                {
                    lastError = errorRecord.InvocationInfo.HistoryId != lastHistory.Id ? (object)null : (object)errorRecord;
                }
            }
            Runspace runspace1 = (Runspace)null;
            bool     flag      = false;

            if (Runspace.DefaultRunspace != runspace)
            {
                runspace1 = Runspace.DefaultRunspace;
                flag      = true;
                Runspace.DefaultRunspace = runspace;
            }
            ArrayList arrayList = (ArrayList)null;

            try
            {
                arrayList = HostUtilities.GetSuggestion(lastHistory, lastError, dollarErrorVariable);
            }
            finally
            {
                if (flag)
                {
                    Runspace.DefaultRunspace = runspace1;
                }
            }
            localRunspace.ExecutionContext.QuestionMarkVariableValue = markVariableValue;
            return(arrayList);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Gets the object that serves as a value to $profile and the paths on it
 /// </summary>
 /// <param name="shellId">The id identifying the host or shell used in profile file names.</param>
 /// <param name="useTestProfile">used from test not to overwrite the profile file names from development boxes</param>
 /// <param name="allUsersAllHosts">path for all users and all hosts</param>
 /// <param name="currentUserAllHosts">path for current user and all hosts</param>
 /// <param name="allUsersCurrentHost">path for all users current host</param>
 /// <param name="currentUserCurrentHost">path for current user and current host</param>
 /// <param name="dollarProfile">the object that serves as a value to $profile</param>
 /// <returns></returns>
 internal static void GetProfileObjectData(string shellId, bool useTestProfile, out string allUsersAllHosts, out string allUsersCurrentHost, out string currentUserAllHosts, out string currentUserCurrentHost, out PSObject dollarProfile)
 {
     allUsersAllHosts       = HostUtilities.GetFullProfileFileName(null, false, useTestProfile);
     allUsersCurrentHost    = HostUtilities.GetFullProfileFileName(shellId, false, useTestProfile);
     currentUserAllHosts    = HostUtilities.GetFullProfileFileName(null, true, useTestProfile);
     currentUserCurrentHost = HostUtilities.GetFullProfileFileName(shellId, true, useTestProfile);
     dollarProfile          = HostUtilities.GetDollarProfile(allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost);
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Gets an array of commands that can be run sequentially to set $profile and run the profile commands.
 /// </summary>
 /// <param name="shellId">The id identifying the host or shell used in profile file names.</param>
 /// <returns></returns>
 internal static PSCommand[] GetProfileCommands(string shellId)
 {
     return(HostUtilities.GetProfileCommands(shellId, false));
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Used to get all profile file names for the current or all hosts and for the current or all users.
 /// </summary>
 /// <param name="shellId">null for all hosts, not null for the specified host</param>
 /// <param name="forCurrentUser">false for all users, true for the current user.</param>
 /// <returns>The profile file name matching the parameters.</returns>
 internal static string GetFullProfileFileName(string shellId, bool forCurrentUser)
 {
     return(HostUtilities.GetFullProfileFileName(shellId, forCurrentUser, false));
 }
Ejemplo n.º 8
0
 internal static string GetFullProfileFileName(string shellId, bool forCurrentUser)
 {
     using (HostUtilities.tracer.TraceMethod())
         return(HostUtilities.GetFullProfileFileName(shellId, forCurrentUser, false));
 }
Ejemplo n.º 9
0
 public static PSCommand[] GetProfileCommands(string shellId) => HostUtilities.GetProfileCommands(shellId, false);
Ejemplo n.º 10
0
        internal static PSCredential CredUIPromptForCredential(
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options,
            IntPtr parentHWND)
        {
            using (HostUtilities.tracer.TraceMethod())
            {
                if (string.IsNullOrEmpty(caption))
                {
                    caption = ResourceManagerCache.GetResourceString("CredUI", "PromptForCredential_DefaultCaption");
                }
                if (string.IsNullOrEmpty(message))
                {
                    message = ResourceManagerCache.GetResourceString("CredUI", "PromptForCredential_DefaultMessage");
                }
                HostUtilities.CREDUI_INFO pUiInfo = new HostUtilities.CREDUI_INFO();
                pUiInfo.pszCaptionText = caption;
                pUiInfo.pszMessageText = message;
                StringBuilder pszUserName = new StringBuilder(userName, 513);
                StringBuilder pszPassword = new StringBuilder(256);
                int           int32       = Convert.ToInt32(false);
                pUiInfo.cbSize     = Marshal.SizeOf((object)pUiInfo);
                pUiInfo.hwndParent = parentHWND;
                HostUtilities.CREDUI_FLAGS dwFlags = HostUtilities.CREDUI_FLAGS.DO_NOT_PERSIST;
                if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
                {
                    dwFlags |= HostUtilities.CREDUI_FLAGS.GENERIC_CREDENTIALS;
                    if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
                    {
                        dwFlags |= HostUtilities.CREDUI_FLAGS.ALWAYS_SHOW_UI;
                    }
                }
                HostUtilities.CredUIReturnCodes credUiReturnCodes = HostUtilities.CredUIReturnCodes.ERROR_INVALID_PARAMETER;
                if (pszUserName.Length <= 513 && pszPassword.Length <= 256)
                {
                    credUiReturnCodes = HostUtilities.CredUIPromptForCredentials(ref pUiInfo, targetName, IntPtr.Zero, 0, pszUserName, 513, pszPassword, 256, ref int32, dwFlags);
                }
                PSCredential psCredential;
                switch (credUiReturnCodes)
                {
                case HostUtilities.CredUIReturnCodes.NO_ERROR:
                    string userName1 = (string)null;
                    if (pszUserName != null)
                    {
                        userName1 = pszUserName.ToString();
                    }
                    SecureString password = new SecureString();
                    for (int index = 0; index < pszPassword.Length; ++index)
                    {
                        password.AppendChar(pszPassword[index]);
                        pszPassword[index] = char.MinValue;
                    }
                    psCredential = string.IsNullOrEmpty(userName1) ? (PSCredential)null : new PSCredential(userName1, password);
                    break;

                case HostUtilities.CredUIReturnCodes.ERROR_CANCELLED:
                    psCredential = (PSCredential)null;
                    break;

                default:
                    HostUtilities.tracer.TraceError("CredUIPromptForCredentials returned an error: " + credUiReturnCodes.ToString());
                    goto case HostUtilities.CredUIReturnCodes.ERROR_CANCELLED;
                }
                return(psCredential);
            }
        }
Ejemplo n.º 11
0
        internal static ArrayList GetSuggestion(
            HistoryInfo lastHistory,
            object lastError,
            ArrayList errorList)
        {
            ArrayList    arrayList        = new ArrayList();
            PSModuleInfo invocationModule = new PSModuleInfo(true);

            invocationModule.SessionState.PSVariable.Set(nameof(lastHistory), (object)lastHistory);
            invocationModule.SessionState.PSVariable.Set(nameof(lastError), lastError);
            foreach (Hashtable suggestion in HostUtilities.suggestions)
            {
                int count = errorList.Count;
                if (LanguagePrimitives.IsTrue(suggestion[(object)"Enabled"]))
                {
                    SuggestionMatchType suggestionMatchType = (SuggestionMatchType)LanguagePrimitives.ConvertTo(suggestion[(object)"MatchType"], typeof(SuggestionMatchType), (IFormatProvider)CultureInfo.InvariantCulture);
                    if (suggestionMatchType == SuggestionMatchType.Dynamic)
                    {
                        if (!(suggestion[(object)"Rule"] is ScriptBlock sb))
                        {
                            suggestion[(object)"Enabled"] = (object)false;
                            throw new ArgumentException(ResourceManagerCache.GetResourceString("SuggestionStrings", "RuleMustBeScriptBlock"), "Rule");
                        }
                        object obj;
                        try
                        {
                            obj = invocationModule.Invoke(sb, (object[])null);
                        }
                        catch (Exception ex)
                        {
                            CommandProcessorBase.CheckForSevereException(ex);
                            suggestion[(object)"Enabled"] = (object)false;
                            continue;
                        }
                        if (LanguagePrimitives.IsTrue(obj))
                        {
                            string suggestionText = HostUtilities.GetSuggestionText(suggestion[(object)"Suggestion"], invocationModule);
                            if (!string.IsNullOrEmpty(suggestionText))
                            {
                                string str = string.Format((IFormatProvider)Thread.CurrentThread.CurrentCulture, "Suggestion [{0},{1}]: {2}", (object)(int)suggestion[(object)"Id"], (object)(string)suggestion[(object)"Category"], (object)suggestionText);
                                arrayList.Add((object)str);
                            }
                        }
                    }
                    else
                    {
                        string input = string.Empty;
                        if (suggestionMatchType == SuggestionMatchType.Command)
                        {
                            input = lastHistory.CommandLine;
                        }
                        else if (suggestionMatchType == SuggestionMatchType.Error)
                        {
                            if (lastError != null)
                            {
                                input = !(lastError is Exception exception) ? lastError.ToString() : exception.Message;
                            }
                        }
                        else
                        {
                            suggestion[(object)"Enabled"] = (object)false;
                            throw new ArgumentException(ResourceManagerCache.GetResourceString("SuggestionStrings", "InvalidMatchType"), "MatchType");
                        }
                        if (Regex.IsMatch(input, (string)suggestion[(object)"Rule"], RegexOptions.IgnoreCase))
                        {
                            string suggestionText = HostUtilities.GetSuggestionText(suggestion[(object)"Suggestion"], invocationModule);
                            if (!string.IsNullOrEmpty(suggestionText))
                            {
                                string str = string.Format((IFormatProvider)Thread.CurrentThread.CurrentCulture, "Suggestion [{0},{1}]: {2}", (object)(int)suggestion[(object)"Id"], (object)(string)suggestion[(object)"Category"], (object)suggestionText);
                                arrayList.Add((object)str);
                            }
                        }
                    }
                    if (errorList.Count != count)
                    {
                        suggestion[(object)"Enabled"] = (object)false;
                    }
                }
            }
            return(arrayList);
        }