コード例 #1
0
        internal static void UpdateConfig(PSCmdlet cmdlet, string[] name, ConfigScope scope, bool enable)
        {
            IEnumerable <WildcardPattern> namePatterns = SessionStateUtilities.CreateWildcardsFromStrings(name, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
            GetExperimentalFeatureCommand getExperimentalFeatureCommand = new GetExperimentalFeatureCommand();

            getExperimentalFeatureCommand.Context = cmdlet.Context;
            bool foundFeature = false;

            foreach (ExperimentalFeature feature in getExperimentalFeatureCommand.GetAvailableExperimentalFeatures(namePatterns))
            {
                foundFeature = true;
                if (!cmdlet.ShouldProcess(feature.Name))
                {
                    return;
                }

                PowerShellConfig.Instance.SetExperimentalFeatures(scope, feature.Name, enable);
            }

            if (!foundFeature)
            {
                string errMsg = string.Format(CultureInfo.InvariantCulture, ExperimentalFeatureStrings.ExperimentalFeatureNameNotFound, name);
                cmdlet.WriteError(new ErrorRecord(new ItemNotFoundException(errMsg), "ItemNotFoundException", ErrorCategory.ObjectNotFound, name));
                return;
            }

            cmdlet.WriteWarning(ExperimentalFeatureStrings.ExperimentalFeaturePending);
        }
コード例 #2
0
        /// <summary>
        /// Perform the actual logic
        /// </summary>
        protected override void ProcessRecord()
        {
            bool test = PSCmdlet.ShouldProcess(LanguagePrimitives.ConvertTo <string>(Target), _Message);

            if (test)
            {
                WriteMessage(Localization.LocalizationHost.Read("PSFramework.FlowControl.Invoke-PSFProtectedCommand.Confirmed", new object[] { _Message }), Message.MessageLevel.SomewhatVerbose, _Caller.CallerFunction, _Caller.CallerModule, _Caller.CallerFile, _Caller.CallerLine, Tag, Target);
            }
            else
            {
                WriteMessage(Localization.LocalizationHost.Read("PSFramework.FlowControl.Invoke-PSFProtectedCommand.Denied", new object[] { _Message }), Message.MessageLevel.SomewhatVerbose, _Caller.CallerFunction, _Caller.CallerModule, _Caller.CallerFile, _Caller.CallerLine, Tag, Target);
                return;
            }

            int countAttempted = 0;

            while (countAttempted <= RetryCount)
            {
                countAttempted++;

                try
                {
                    object result = PSCmdlet.InvokeCommand.InvokeScript(false, ScriptBlock, null, null);
                    WriteMessage(Localization.LocalizationHost.Read("PSFramework.FlowControl.Invoke-PSFProtectedCommand.Success", new object[] { _Message }), Message.MessageLevel.SomewhatVerbose, _Caller.CallerFunction, _Caller.CallerModule, _Caller.CallerFile, _Caller.CallerLine, Tag, Target);
                    if (result != null)
                    {
                        WriteObject(result);
                    }
                    return;
                }
                catch (Exception e)
                {
                    Exception tempError = e;
                    if (tempError is ActionPreferenceStopException)
                    {
                        tempError = ((ActionPreferenceStopException)tempError).ErrorRecord.Exception;
                    }

                    if (RetryCount == 0)
                    {
                        Terminate(tempError);
                        return;
                    }
                    if (RetryErrorType.Length > 0 && !RetryErrorType.Contains(tempError.GetType().FullName, StringComparer.InvariantCultureIgnoreCase))
                    {
                        Terminate(tempError);
                        return;
                    }
                    if (countAttempted > RetryCount)
                    {
                        Terminate(tempError);
                        return;
                    }
                }
                WriteMessage(Localization.LocalizationHost.Read("PSFramework.FlowControl.Invoke-PSFProtectedCommand.Retry", new object[] { countAttempted, (RetryCount + 1), _Message }), Message.MessageLevel.SomewhatVerbose, _Caller.CallerFunction, _Caller.CallerModule, _Caller.CallerFile, _Caller.CallerLine, Tag, Target);
                Thread.Sleep(RetryWait);
            }
        }
コード例 #3
0
ファイル: HostContext.cs プロジェクト: djnatronic/PSDocs
        public bool ShouldProcess(string target, string action)
        {
            if (CommandRuntime == null)
            {
                return(true);
            }

            return(CommandRuntime.ShouldProcess(target, action));
        }
コード例 #4
0
        public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string errorMsg)
        {
            errorMsg = string.Empty;
            // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition
            repoName = repoName.Trim(' ');
            if (String.IsNullOrEmpty(repoName) || repoName.Contains("*"))
            {
                throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace");
            }

            if (repoUri == null || !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile))
            {
                errorMsg = "Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based";
                return(null);
            }

            if (repoCredentialInfo != null)
            {
                bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, cmdletPassedIn);

                if (repoCredentialInfo.Credential != null)
                {
                    if (!isSecretManagementModuleAvailable)
                    {
                        errorMsg = $"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault.";
                        return(null);
                    }
                    else
                    {
                        Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, cmdletPassedIn);
                    }
                }

                if (!isSecretManagementModuleAvailable)
                {
                    cmdletPassedIn.WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo.");
                }
            }

            if (!cmdletPassedIn.ShouldProcess(repoName, "Register repository to repository store"))
            {
                return(null);
            }

            if (!string.IsNullOrEmpty(errorMsg))
            {
                return(null);
            }

            var repo = RepositorySettings.Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, force);

            return(repo);
        }
コード例 #5
0
 internal static void RestartWinRMService(PSCmdlet cmdlet, bool isErrorReported, bool force, bool noServiceRestart)
 {
     if (!isErrorReported && !noServiceRestart)
     {
         string restartWSManServiceAction = RemotingErrorIdStrings.RestartWSManServiceAction;
         string target = StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceTarget, "WinRM");
         if (force || cmdlet.ShouldProcess(target, restartWSManServiceAction))
         {
             cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceMessageV, new object[0]));
             cmdlet.InvokeCommand.NewScriptBlock("restart-service winrm -force -confirm:$false").InvokeUsingCmdlet(cmdlet, true, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, new object[0], AutomationNull.Value, new object[0]);
         }
     }
 }
コード例 #6
0
        /// <summary>
        /// Perform the actual logic
        /// </summary>
        protected override void ProcessRecord()
        {
            bool test = PSCmdlet.ShouldProcess(LanguagePrimitives.ConvertTo <string>(Target), _Message);

            if (test)
            {
                WriteMessage(Localization.LocalizationHost.ReadLog("PSFramework.FlowControl.Invoke-PSFProtectedCommand.Confirmed", new object[] { _Message }), Message.MessageLevel.SomewhatVerbose, _Caller.CallerFunction, _Caller.CallerModule, _Caller.CallerFile, _Caller.CallerLine, null, Target);
            }
            else
            {
                WriteMessage(Localization.LocalizationHost.ReadLog("PSFramework.FlowControl.Invoke-PSFProtectedCommand.Denied", new object[] { _Message }), Message.MessageLevel.SomewhatVerbose, _Caller.CallerFunction, _Caller.CallerModule, _Caller.CallerFile, _Caller.CallerLine, null, Target);
                return;
            }

            try
            {
                WriteObject(PSCmdlet.InvokeCommand.InvokeScript(false, ScriptBlock, null, null));
            }
            catch (Exception e)
            {
                ScriptBlock errorBlock = ScriptBlock.Create(@"
param (
    $__PSFramework__Message,

    $__PSFramework__Exception,

    $__PSFramework__Target,

    $__PSFramework__Continue,

    $__PSFramework__FunctionName,

    $__PSFramework__ModuleName,

    $__PSFramework__File,

    $__PSFramework__Line,

    $__PSFramework__Cmdlet,

    $__PSFramework__EnableException
)

Stop-PSFFunction -Message $__PSFramework__Message -Exception $__PSFramework__Exception -Target $__PSFramework__Target -Continue:$__PSFramework__Continue -FunctionName $__PSFramework__FunctionName -ModuleName $__PSFramework__ModuleName -File $__PSFramework__File -Line $__PSFramework__Line -Cmdlet $__PSFramework__Cmdlet -EnableException $__PSFramework__EnableException -StepsUpward 1
return
");
                object[]    arguments  = new object[] { _ErrorMessage, e, Target, Continue, _Caller.CallerFunction, _Caller.CallerModule, _Caller.CallerFile, _Caller.CallerLine, PSCmdlet, EnableException };
                PSCmdlet.InvokeCommand.InvokeScript(false, errorBlock, null, arguments);
            }
        }
コード例 #7
0
        internal static void RestartWinRMService(
            PSCmdlet cmdlet,
            bool isErrorReported,
            bool force,
            bool noServiceRestart)
        {
            if (isErrorReported || noServiceRestart)
            {
                return;
            }
            string resourceString = ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "RestartWSManServiceAction");
            string target         = ResourceManagerCache.FormatResourceString("RemotingErrorIdStrings", "RestartWSManServiceTarget", (object)"WinRM");

            if (!force && !cmdlet.ShouldProcess(target, resourceString))
            {
                return;
            }
            cmdlet.WriteVerbose(ResourceManagerCache.FormatResourceString("RemotingErrorIdStrings", "RestartWSManServiceMessageV"));
            cmdlet.InvokeCommand.NewScriptBlock("restart-service winrm -force -confirm:$false").InvokeUsingCmdlet((Cmdlet)cmdlet, true, true, (object)AutomationNull.Value, (object)new object[0], (object)AutomationNull.Value);
        }
コード例 #8
0
        public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, bool isSet, int defaultPriority, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string errorMsg)
        {
            errorMsg = string.Empty;
            if (repoUri != null && !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile))
            {
                errorMsg = "Invalid Uri, Uri must be one of the following schemes: HTTPS, HTTP, FTP, File Based";
                return(null);
            }

            // check repoName can't contain * or just be whitespace
            // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition
            repoName = repoName.Trim();
            if (String.IsNullOrEmpty(repoName) || repoName.Contains("*"))
            {
                errorMsg = "Name cannot be null or empty, or contain wildcards";
                return(null);
            }

            // check PSGallery Uri is not trying to be set
            if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoUri != null)
            {
                errorMsg = "The PSGallery repository has a predefined Uri. Setting the -Uri parameter for this repository is not allowed. Please run 'Register-PSResourceRepository -PSGallery' to register the PowerShell Gallery.";
                return(null);
            }

            // check PSGallery CredentialInfo is not trying to be set
            if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoCredentialInfo != null)
            {
                errorMsg = "Setting the -CredentialInfo parameter for PSGallery is not allowed. Run 'Register-PSResourceRepository -PSGallery' to register the PowerShell Gallery.";
                return(null);
            }

            // determine trusted value to pass in (true/false if set, null otherwise, hence the nullable bool variable)
            bool?_trustedNullable = isSet ? new bool?(repoTrusted) : new bool?();

            if (repoCredentialInfo != null)
            {
                bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, cmdletPassedIn);

                if (repoCredentialInfo.Credential != null)
                {
                    if (!isSecretManagementModuleAvailable)
                    {
                        errorMsg = $"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault.";
                        return(null);
                    }
                    else
                    {
                        Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, cmdletPassedIn);
                    }
                }

                if (!isSecretManagementModuleAvailable)
                {
                    cmdletPassedIn.WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo.");
                }
            }

            // determine if either 1 of 4 values are attempting to be set: Uri, Priority, Trusted, CredentialInfo.
            // if none are (i.e only Name parameter was provided, write error)
            if (repoUri == null && repoPriority == defaultPriority && _trustedNullable == null && repoCredentialInfo == null)
            {
                errorMsg = "Must set Uri, Priority, Trusted or CredentialInfo parameter";
                return(null);
            }

            if (!cmdletPassedIn.ShouldProcess(repoName, "Set repository's value(s) in repository store"))
            {
                return(null);
            }

            if (!string.IsNullOrEmpty(errorMsg))
            {
                return(null);
            }

            return(Update(repoName, repoUri, repoPriority, _trustedNullable, repoCredentialInfo, cmdletPassedIn, out errorMsg));
        }
コード例 #9
0
 /// <summary>
 /// Perform the query
 /// </summary>
 protected override void ProcessRecord()
 {
     WriteObject(_PSCmdlet.ShouldProcess(Target, _Action));
 }