示例#1
0
        public static List <string> ResolvePaths(this PSCmdlet cmdlet, bool shouldExpandWildcards, params string[] paths)
        {
            var resolvedPaths = new List <string>();

            foreach (var path in paths)
            {
                // this contains the paths to process for this iteration of the
                // loop to resolve and optionally expand wildcards.
                var filePaths = new List <string>();
                try
                {
                    // This will hold information about the provider containing
                    // the items that this path string might resolve to.
                    ProviderInfo provider;
                    if (shouldExpandWildcards)
                    {
                        // Turn *.txt into foo.txt,foo2.txt etc.
                        // if path is just "foo.txt," it will return unchanged.
                        filePaths.AddRange(cmdlet.GetResolvedProviderPathFromPSPath(path, out provider));
                    }
                    else
                    {
                        // no wildcards, so don't try to expand any * or ? symbols.
                        filePaths.Add(cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(
                                          path, out provider, out _));
                    }

                    // ensure that this path (or set of paths after wildcard expansion)
                    // is on the filesystem. A wildcard can never expand to span multiple
                    // providers.
                    if (provider.ImplementingType != typeof(FileSystemProvider))
                    {
                        // create a .NET exception wrapping our error text
                        var ex = new ArgumentException(path +
                                                       " does not resolve to a path on the FileSystem provider.");
                        // wrap this in a powershell errorrecord
                        var error = new ErrorRecord(ex, "InvalidProvider",
                                                    ErrorCategory.InvalidArgument, path);
                        // write a non-terminating error to pipeline
                        cmdlet.WriteError(error);

                        // no, so skip to next path in _paths.
                        continue;
                    }
                }
                catch (Exception exception)
                {
                    // wrap this in a powershell errorrecord
                    var error = new ErrorRecord(exception, "InvalidPath",
                                                ErrorCategory.InvalidArgument, path);
                    // write a non-terminating error to pipeline
                    cmdlet.WriteError(error);
                    continue;
                }

                resolvedPaths.AddRange(filePaths);
            }

            return(resolvedPaths);
        }
示例#2
0
        internal static List <OrderByPropertyEntry> CreateOrderMatrix(
            PSCmdlet cmdlet,
            List <PSObject> inputObjects,
            List <MshParameter> mshParameterList
            )
        {
            List <OrderByPropertyEntry> orderMatrixToCreate = new List <OrderByPropertyEntry>();

            foreach (PSObject so in inputObjects)
            {
                if (so == null || so == AutomationNull.Value)
                {
                    continue;
                }
                List <ErrorRecord>   evaluationErrors     = new List <ErrorRecord>();
                List <string>        propertyNotFoundMsgs = new List <string>();
                OrderByPropertyEntry result =
                    OrderByPropertyEntryEvaluationHelper.ProcessObject(so, mshParameterList, evaluationErrors, propertyNotFoundMsgs);
                foreach (ErrorRecord err in evaluationErrors)
                {
                    cmdlet.WriteError(err);
                }
                foreach (string debugMsg in propertyNotFoundMsgs)
                {
                    cmdlet.WriteDebug(debugMsg);
                }
                orderMatrixToCreate.Add(result);
            }

            return(orderMatrixToCreate);
        }
示例#3
0
        public bool InvokeTestVault(
            string vaultName,
            PSCmdlet cmdlet)
        {
            var additionalParameters = GetAdditionalParams(cmdlet);
            var parameters           = new Hashtable()
            {
                { "VaultName", VaultName },
                { "AdditionalParameters", additionalParameters }
            };

            var results = InvokeOnCmdlet <bool>(
                cmdlet: cmdlet,
                script: RunCommandScript,
                args: new object[] { ModulePath, ModuleExtensionName, TestVaultCmd, parameters },
                out Exception terminatingError);

            if (terminatingError != null)
            {
                ThrowPasswordRequiredException(terminatingError);

                cmdlet.WriteError(
                    new ErrorRecord(
                        new PSInvalidOperationException(
                            message: string.Format("Unable to run Test-SecretVault on vault {0}", VaultName),
                            innerException: terminatingError),
                        "TestSecretVaultInvalidOperation",
                        ErrorCategory.InvalidOperation,
                        this));
            }

            return((results.Count > 0) ? results[0] : false);
        }
示例#4
0
        /// <Summary>
        /// Optional Unregister-Vault extension command.  Will invoke if available.
        /// </Summary>
        public void InvokeUnregisterVault(
            PSCmdlet cmdlet)
        {
            var additionalParameters = GetAdditionalParams(cmdlet);
            var parameters           = new Hashtable()
            {
                { "VaultName", VaultName },
                { "AdditionalParameters", additionalParameters }
            };

            InvokeOnCmdlet(
                cmdlet: cmdlet,
                script: RunIfCommandScript,
                args: new object[] { ModulePath, ModuleExtensionName, UnregisterSecretVaultCommand, parameters },
                out Exception terminatingError);

            if (terminatingError != null)
            {
                ThrowPasswordRequiredException(terminatingError);

                cmdlet.WriteError(
                    new ErrorRecord(
                        new PSInvalidOperationException(
                            message: string.Format("An error occurred while running Unregister-SecretVault on vault {0}, Error: {1}",
                                                   VaultName, terminatingError.Message),
                            innerException: terminatingError),
                        "UnregisterSecretVaultInvalidOperation",
                        ErrorCategory.InvalidOperation,
                        this));
            }
        }
示例#5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="files"></param>
        /// <param name="errorId"></param>
        /// <param name="cmdlet"></param>
        /// <returns></returns>
        internal static Collection <string> Glob(string[] files, string errorId, PSCmdlet cmdlet)
        {
            Collection <string> retValue = new Collection <string>();

            foreach (string file in files)
            {
                Collection <string> providerPaths;
                ProviderInfo        provider = null;
                try
                {
                    providerPaths = cmdlet.SessionState.Path.GetResolvedProviderPathFromPSPath(file, out provider);
                }
                catch (SessionStateException e)
                {
                    cmdlet.WriteError(new ErrorRecord(e, errorId, ErrorCategory.InvalidOperation, file));
                    continue;
                }
                if (!provider.NameEquals(cmdlet.Context.ProviderNames.FileSystem))
                {
                    ReportWrongProviderType(provider.FullName, errorId, cmdlet);
                    continue;
                }
                foreach (string providerPath in providerPaths)
                {
                    if (!providerPath.EndsWith(".ps1xml", StringComparison.OrdinalIgnoreCase))
                    {
                        ReportWrongExtension(providerPath, "WrongExtension", cmdlet);
                        continue;
                    }
                    retValue.Add(providerPath);
                }
            }

            return(retValue);
        }
        /// <summary>
        /// Shortcut to <see cref="PSCmdlet.WriteError"/>
        /// </summary>
        /// <param name="cmdlet"></param>
        /// <param name="error"></param>
        /// <param name="errorCat"></param>
        /// <param name="targetObj"></param>
        public static void WriteError(this PSCmdlet cmdlet, string error, ErrorCategory errorCat = ErrorCategory.InvalidOperation, object targetObj = null)
        {
            targetObj ??= cmdlet;
            var errrec = new ErrorRecord(new Exception(error), "SimpleStringError", errorCat, targetObj);

            cmdlet.WriteError(errrec);
        }
        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);
        }
示例#8
0
        /// <summary>
        /// Utility function used to create OrderByPropertyEntry for the supplied input object.
        /// </summary>
        /// <param name="cmdlet">PSCmdlet</param>
        /// <param name="inputObject">Input Object.</param>
        /// <param name="isCaseSensitive">Indicates if the Property value comparisons need to be case sensitive or not.</param>
        /// <param name="cultureInfo">Culture Info that needs to be used for comparison.</param>
        /// <returns>OrderByPropertyEntry for the supplied InputObject.</returns>
        internal OrderByPropertyEntry CreateOrderByPropertyEntry(
            PSCmdlet cmdlet,
            PSObject inputObject,
            bool isCaseSensitive,
            CultureInfo cultureInfo)
        {
            Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance");

            if (_unExpandedParametersWithWildCardPattern != null)
            {
                ExpandExpressions(inputObject, _unExpandedParametersWithWildCardPattern, _mshParameterList);
            }

            List <ErrorRecord>   evaluationErrors     = new List <ErrorRecord>();
            List <string>        propertyNotFoundMsgs = new List <string>();
            OrderByPropertyEntry result =
                OrderByPropertyEntryEvaluationHelper.ProcessObject(inputObject, _mshParameterList, evaluationErrors, propertyNotFoundMsgs, isCaseSensitive, cultureInfo);

            foreach (ErrorRecord err in evaluationErrors)
            {
                cmdlet.WriteError(err);
            }
            foreach (string debugMsg in propertyNotFoundMsgs)
            {
                cmdlet.WriteDebug(debugMsg);
            }

            return(result);
        }
示例#9
0
 public static IObservable <T> IgnoreException <T, TException>(this IObservable <T> source, PSCmdlet cmdlet, object targetObject) where  TException : Exception
 {
     return(source.ObserveOn(SynchronizationContext.Current)
            .Catch <T, TException>(exception => {
         cmdlet.WriteError(new ErrorRecord(exception, $"{exception.GetHashCode()}", ErrorCategory.InvalidOperation, targetObject));
         return Observable.Empty <T>();
     }));
 }
示例#10
0
 public void WriteError(Exception ex, string errorId, ErrorCategory category, PSCmdlet source)
 {
     if (_cmd != null && !string.IsNullOrWhiteSpace(errorId))
     {
         var rec = new ErrorRecord(ex, errorId, category, source);
         _cmd?.WriteError(rec);
     }
 }
示例#11
0
        /// <summary>
        /// Looks up a single secret by name.
        /// </summary>
        /// <returns>Secret object</returns>
        public object InvokeGetSecret(
            string name,
            string vaultName,
            PSCmdlet cmdlet)
        {
            var additionalParameters = GetAdditionalParams(cmdlet);
            var parameters           = new Hashtable()
            {
                { "Name", name },
                { "VaultName", vaultName },
                { "AdditionalParameters", additionalParameters }
            };

            var results = InvokeOnCmdlet <object>(
                cmdlet: cmdlet,
                script: RunCommandScript,
                args: new object[] { ModulePath, ModuleExtensionName, GetSecretCmd, parameters },
                out Exception terminatingError);

            if (terminatingError != null)
            {
                ThrowPasswordRequiredException(terminatingError);

                cmdlet.WriteError(
                    new ErrorRecord(
                        new PSInvalidOperationException(
                            message: string.Format("Unable to get secret {0} from vault {1}", name, VaultName),
                            innerException: terminatingError),
                        "GetSecretInvalidOperation",
                        ErrorCategory.InvalidOperation,
                        this));
            }
            else
            {
                cmdlet.WriteVerbose(
                    string.Format("Secret {0} was successfully retrieved from vault {1}.", name, VaultName));
            }

            if (results.Count > 0)
            {
                if (results[0] is byte)
                {
                    // Re-wrap collection of bytes into a byte array.
                    byte[] byteArray = new byte[results.Count];
                    for (int i = 0; i < results.Count; i++)
                    {
                        byteArray[i] = (byte)results[i];
                    }
                    return(byteArray);
                }

                return(results[0]);
            }

            return(null);
        }
示例#12
0
        private static void ReportWrongExtension(string file, string errorId, PSCmdlet cmdlet)
        {
            ErrorRecord errorRecord = new ErrorRecord(
                PSTraceSource.NewInvalidOperationException(UpdateDataStrings.UpdateData_WrongExtension, file, "ps1xml"),
                errorId,
                ErrorCategory.InvalidArgument,
                null);

            cmdlet.WriteError(errorRecord);
        }
示例#13
0
        private static void ReportWrongProviderType(string providerId, string errorId, PSCmdlet cmdlet)
        {
            ErrorRecord errorRecord = new ErrorRecord(
                PSTraceSource.NewInvalidOperationException(UpdateDataStrings.UpdateData_WrongProviderError, providerId),
                errorId,
                ErrorCategory.InvalidArgument,
                null);

            cmdlet.WriteError(errorRecord);
        }
        public static void WriteError(
            this PSCmdlet cmdlet,
            Exception exception,
            string errorId,
            ErrorCategory category,
            object target)
        {
            var er = new ErrorRecord(exception, errorId, category, target);

            cmdlet.WriteError(er);
        }
示例#15
0
        public void LogError(string message, params object[] messageArgs)
        {
            var exeception = new InvalidOperationException(string.Format(message, messageArgs));

            _cmdlet.WriteError(
                new ErrorRecord(exeception, null, ErrorCategory.InvalidOperation, null));
        }
    /// <summary>
    /// Execute the given cmdlet in powershell using the given pipeline parameters.
    /// </summary>
    /// <typeparam name="T">The output type for the cmdlet</typeparam>
    /// <param name="cmdlet">The cmdlet to execute</param>
    /// <param name="name">The name of the cmdlet</param>
    /// <param name="cmdletParameters">The parameters to pass to the cmdlet on the pipeline</param>
    /// <param name="ignoreErrors">Do not throw exception if command has errors.</param>
    /// <param name="writeErrors">Write errors to host if command has errors.</param>
    /// <returns>The output of executing the cmdlet</returns>
    /// <exception cref="System.InvalidOperationException">Throws InvalidOperationException if any error occurs from the cmdlet call.</exception>
    public static List <T> ExecuteCmdletInPipeline <T>(this PSCmdlet cmdlet, string name, KeyValuePair <string, object>[] cmdletParameters, bool ignoreErrors = false, bool writeErrors = false)
    {
        List <T> output = new List <T>();

        using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
        {
            powershell.AddCommand(name);
            foreach (var pair in cmdletParameters)
            {
                if (pair.Value == null)
                {
                    powershell.AddParameter(pair.Key);
                }
                else
                {
                    powershell.AddParameter(pair.Key, pair.Value);
                }
            }
            Collection <PSObject> result = powershell.Invoke();
            if (powershell.Streams.Error != null && powershell.Streams.Error.Count > 0)
            {
                StringBuilder details = new StringBuilder();
                if (writeErrors)
                {
                    powershell.Streams.Error.ForEach(e => cmdlet.WriteError(e));
                }
                powershell.Streams.Error.ForEach(e => details.AppendLine($"Error: {e}"));
                InvalidOperationException ex;
                if (powershell.Streams.Error[0].Exception != null)
                {
                    ex = new InvalidOperationException($"Errors while running cmdlet:\n {details}", powershell.Streams.Error[0].Exception);
                }
                else
                {
                    ex = new InvalidOperationException($"Errors while running cmdlet:\n {details}");
                }
                int i = 0;
                powershell.Streams.Error.ForEach(e => ex.Data.Add($"ErrorRecord{i++}", e));
                if (!ignoreErrors)
                {
                    throw ex;
                }
            }

            if (result != null && result.Count > 0)
            {
                result.ForEach(r => output.Add((T)r.BaseObject));
            }
        }

        return(output);
    }
示例#17
0
        public bool InvokeSetSecretMetadata(
            string name,
            Hashtable metadata,
            string vaultName,
            PSCmdlet cmdlet)
        {
            var additionalParameters = GetAdditionalParams(cmdlet);
            var parameters           = new Hashtable()
            {
                { "Name", name },
                { "Metadata", metadata },
                { "VaultName", vaultName },
                { "AdditionalParameters", additionalParameters }
            };

            // Result values:
            // 0 - Command ran (command will emit any error message)
            // 1 - Module not found
            // 2 - Command not found
            var results = InvokeOnCmdlet <int>(
                cmdlet: cmdlet,
                script: RunConditionalCommandScript,
                args: new object[] { ModulePath, ModuleExtensionName, SetSecretInfoCmd, parameters },
                out Exception terminatingError);

            if (terminatingError != null)
            {
                ThrowPasswordRequiredException(terminatingError);

                cmdlet.WriteError(
                    new ErrorRecord(
                        new PSInvalidOperationException(
                            message: string.Format("Unable to add secret metadata {0} to vault {1}", name, VaultName),
                            innerException: terminatingError),
                        "SetSecretMetadataInvalidOperation",
                        ErrorCategory.InvalidOperation,
                        this));

                return(false);
            }

            int result  = (results.Count > 0) ? results[0] : 0;
            var success = result == 0;

            if (success)
            {
                cmdlet.WriteVerbose(
                    string.Format("Secret metadata {0} was successfully added to vault {1}.", name, VaultName));
            }

            return(success);
        }
示例#18
0
            public static void Log <T>(T message, LogTarget logTarget, PSCmdlet invokeAll, bool noFileLogging = false)
            {
                string messageStr = null;

                if (message is ErrorRecord)
                {
                    //cast to object and then to ErrorRecord as direct casting is not allowed
                    messageStr = ((ErrorRecord)(object)message).Exception.Message;
                }
                else
                {
                    messageStr = (string)(object)message;
                }
                string logEntry = string.Format("[{0}] {1}", System.DateTime.Now.ToString(datetimeFormat), messageStr);

                switch (logTarget)
                {
                case LogTarget.File:
                    if (!noFileLogging)
                    {
                        using (StreamWriter streamWriter = new StreamWriter(logFile, append: true))
                        {
                            streamWriter.WriteLine(logEntry);
                            streamWriter.Close();
                        };
                    }
                    break;

                case LogTarget.HostVerbose:
                    invokeAll.WriteVerbose(logEntry);
                    break;

                case LogTarget.HostDebug:
                    invokeAll.WriteDebug(logEntry);
                    break;

                case LogTarget.HostError:
                    if (message is ErrorRecord)
                    {
                        invokeAll.WriteError((ErrorRecord)(object)message);
                    }
                    break;

                case LogTarget.HostWarning:
                    invokeAll.WriteWarning(logEntry);
                    break;

                default:

                    break;
                }
            }
示例#19
0
        internal static bool SkipSystemRestoreOperationForARMPlatform(PSCmdlet cmdlet)
        {
            bool flag = false;

            if (PsUtils.IsRunningOnProcessorArchitectureARM())
            {
                InvalidOperationException invalidOperationException = new InvalidOperationException(ComputerResources.SystemRestoreNotSupported);
                ErrorRecord errorRecord = new ErrorRecord(invalidOperationException, "SystemRestoreNotSupported", ErrorCategory.InvalidOperation, null);
                cmdlet.WriteError(errorRecord);
                flag = true;
            }
            return(flag);
        }
示例#20
0
        public static Hashtable ParseModuleManifest(string moduleFileInfo, PSCmdlet cmdletPassedIn)
        {
            Hashtable parsedMetadataHash = new Hashtable();

            // A script will already  have the metadata parsed into the parsedMetadatahash,
            // a module will still need the module manifest to be parsed.
            if (moduleFileInfo.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase))
            {
                // Parse the module manifest
                System.Management.Automation.Language.Token[] tokens;
                ParseError[] errors;
                var          ast = Parser.ParseFile(moduleFileInfo, out tokens, out errors);

                if (errors.Length > 0)
                {
                    var message          = String.Format("Could not parse '{0}' as a PowerShell data file.", moduleFileInfo);
                    var ex               = new ArgumentException(message);
                    var psdataParseError = new ErrorRecord(ex, "psdataParseError", ErrorCategory.ParserError, null);
                    cmdletPassedIn.WriteError(psdataParseError);
                }
                else
                {
                    var data = ast.Find(a => a is HashtableAst, false);
                    if (data != null)
                    {
                        parsedMetadataHash = (Hashtable)data.SafeGetValue();
                    }
                    else
                    {
                        var message          = String.Format("Could not parse as PowerShell data file-- no hashtable root for file '{0}'", moduleFileInfo);
                        var ex               = new ArgumentException(message);
                        var psdataParseError = new ErrorRecord(ex, "psdataParseError", ErrorCategory.ParserError, null);
                        cmdletPassedIn.WriteError(psdataParseError);
                    }
                }
            }

            return(parsedMetadataHash);
        }
 public void WriteError(ErrorRecord errorRecord)
 {
     if (caller != null)
     {
         caller.WriteError(errorRecord);
     }
     else
     {
         OnOutput(new CallerProxyEventArgs()
         {
             StreamName = "Error", Text = errorRecord.ToString()
         });
     }
 }
示例#22
0
        internal PSVariable GetVariableByName(string variableName)
        {
            if (String.IsNullOrEmpty(variableName))
            {
                throw new ArgumentException("variableName cannot be null or empty.");
            }

            if (reVarFixup.IsMatch(variableName))
            {
                variableName = reVarFixup.Match(variableName).Groups[1].Value;
            }
            PSVariable variable = m_context.SessionState.PSVariable.Get(variableName);

            string message = "Path variable:" + variableName;

            if (variable == null)
            {
                m_context.WriteError(new ErrorRecord(null, "VarNotFound", ErrorCategory.InvalidArgument, message + " not found."));
                return(null);
            }

            object target = GetBaseObject(variable);

            if (target == null)
            {
                m_context.WriteError(new ErrorRecord(null, "VarIsNull", ErrorCategory.InvalidArgument, message + " -eq $null."));
                return(null);
            }

            if (target is PSCustomObject)
            {
                m_context.WriteError(new ErrorRecord(null, "VarIsCustomObject", ErrorCategory.InvalidArgument, message + " -is PSCustomObject."));
                return(null);
            }

            return(variable);
        }
示例#23
0
        /// <summary>
        /// Returns secret meta data.
        /// </summary>
        public SecretInformation[] InvokeGetSecretInfo(
            string filter,
            string vaultName,
            PSCmdlet cmdlet)
        {
            var additionalParameters = GetAdditionalParams(cmdlet);
            var parameters           = new Hashtable()
            {
                { "Filter", filter },
                { "VaultName", vaultName },
                { "AdditionalParameters", additionalParameters }
            };

            var results = InvokeOnCmdlet <SecretInformation>(
                cmdlet: cmdlet,
                script: RunCommandScript,
                args: new object[] { ModulePath, ModuleExtensionName, GetSecretInfoCmd, parameters },
                out Exception terminatingError);

            if (terminatingError != null)
            {
                ThrowPasswordRequiredException(terminatingError);

                cmdlet.WriteError(
                    new ErrorRecord(
                        new PSInvalidOperationException(
                            message: string.Format("Unable to get secret information from vault {0}", VaultName),
                            innerException: terminatingError),
                        "GetSecretInfoInvalidOperation",
                        ErrorCategory.InvalidOperation,
                        this));
            }
            else
            {
                cmdlet.WriteVerbose(
                    string.Format("Secret information was successfully retrieved from vault {0}.", VaultName));
            }

            var secretInfo = new SecretInformation[results.Count];

            results.CopyTo(secretInfo, 0);
            return(secretInfo);
        }
示例#24
0
        internal static void WriteNonTerminatingError(int errorcode, PSCmdlet cmdlet, string computername)
        {
            Win32Exception win32Exception  = new Win32Exception(errorcode);
            string         empty           = string.Empty;
            int            nativeErrorCode = win32Exception.NativeErrorCode;

            if (nativeErrorCode.Equals(53))
            {
                empty = StringUtil.Format(ComputerResources.NetworkPathNotFound, computername);
            }
            object[] message = new object[3];
            message[0] = win32Exception.Message;
            message[1] = computername;
            message[2] = empty;
            string      str         = StringUtil.Format(ComputerResources.OperationFailed, message);
            ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(str), "InvalidOperationException", ErrorCategory.InvalidOperation, computername);

            cmdlet.WriteError(errorRecord);
        }
示例#25
0
    public static bool IsFileSystemPath(ProviderInfo provider, string path, PSCmdlet context)
    {
        bool isFileSystem = true;

        // check that this provider is the filesystem
        if (provider.ImplementingType != typeof(FileSystemProvider))
        {
            // create a .NET exception wrapping our error text
            ArgumentException ex = new ArgumentException(path +
                                                         " does not resolve to a path on the FileSystem provider.");
            // wrap this in a powershell errorrecord
            ErrorRecord error = new ErrorRecord(ex, "InvalidProvider",
                                                ErrorCategory.InvalidArgument, path);
            // write a non-terminating error to pipeline
            // TODO pass in a context to allow logging
            context.WriteError(error);
            // tell our caller that the item was not on the filesystem
            isFileSystem = false;
        }
        return(isFileSystem);
    }
示例#26
0
        /// <summary>
        /// Invoke SetSecret method on vault extension.
        /// </summary>
        /// <param name="name">Name of secret to add.</param>
        /// <param name="secret">Secret object to add.</param>
        /// <param name="vaultName">Name of registered vault.</param>
        /// <param name="cmdlet">Calling cmdlet.</param>
        public void InvokeSetSecret(
            string name,
            object secret,
            string vaultName,
            PSCmdlet cmdlet)
        {
            var additionalParameters = GetAdditionalParams(cmdlet);
            var parameters           = new Hashtable()
            {
                { "Name", name },
                { "Secret", secret },
                { "VaultName", vaultName },
                { "AdditionalParameters", additionalParameters }
            };

            InvokeOnCmdlet(
                cmdlet: cmdlet,
                script: RunCommandScript,
                args: new object[] { ModulePath, ModuleExtensionName, SetSecretCmd, parameters },
                out Exception terminatingError);

            if (terminatingError != null)
            {
                ThrowPasswordRequiredException(terminatingError);

                cmdlet.WriteError(
                    new ErrorRecord(
                        new PSInvalidOperationException(
                            message: string.Format("Unable to add secret {0} to vault {1}", name, VaultName),
                            innerException: terminatingError),
                        "SetSecretInvalidOperation",
                        ErrorCategory.InvalidOperation,
                        this));
            }
            else
            {
                cmdlet.WriteVerbose(
                    string.Format("Secret {0} was successfully added to vault {1}.", name, VaultName));
            }
        }
示例#27
0
        internal static Collection <string> Glob(string[] files, string errorId, PSCmdlet cmdlet)
        {
            Collection <string> collection = new Collection <string>();

            foreach (string str in files)
            {
                Collection <string> resolvedProviderPathFromPSPath;
                ProviderInfo        provider = null;
                try
                {
                    resolvedProviderPathFromPSPath = cmdlet.SessionState.Path.GetResolvedProviderPathFromPSPath(str, out provider);
                }
                catch (SessionStateException exception)
                {
                    cmdlet.WriteError(new ErrorRecord(exception, errorId, ErrorCategory.InvalidOperation, str));
                    continue;
                }
                if (!provider.NameEquals(cmdlet.Context.ProviderNames.FileSystem))
                {
                    ReportWrongProviderType(provider.FullName, errorId, cmdlet);
                }
                else
                {
                    foreach (string str2 in resolvedProviderPathFromPSPath)
                    {
                        if (!str2.EndsWith(".ps1xml", StringComparison.OrdinalIgnoreCase))
                        {
                            ReportWrongExtension(str2, "WrongExtension", cmdlet);
                        }
                        else
                        {
                            collection.Add(str2);
                        }
                    }
                }
            }
            return(collection);
        }
示例#28
0
        internal static List <OrderByPropertyEntry> CreateOrderMatrix(PSCmdlet cmdlet, List <PSObject> inputObjects, List <MshParameter> mshParameterList)
        {
            List <OrderByPropertyEntry> list = new List <OrderByPropertyEntry>();

            foreach (PSObject obj2 in inputObjects)
            {
                if ((obj2 != null) && (obj2 != AutomationNull.Value))
                {
                    List <ErrorRecord>   errors = new List <ErrorRecord>();
                    List <string>        propertyNotFoundMsgs = new List <string>();
                    OrderByPropertyEntry item = OrderByPropertyEntryEvaluationHelper.ProcessObject(obj2, mshParameterList, errors, propertyNotFoundMsgs);
                    foreach (ErrorRecord record in errors)
                    {
                        cmdlet.WriteError(record);
                    }
                    foreach (string str in propertyNotFoundMsgs)
                    {
                        cmdlet.WriteDebug(str);
                    }
                    list.Add(item);
                }
            }
            return(list);
        }
示例#29
0
        public static void CloseClient(this PSCmdlet cmdlet, IClusterClient client)
        {
            try
            {
                if (client == null)
                {
                    return;
                }

                try
                {
                    client.Close().GetAwaiter().GetResult();
                }
                catch (Exception exception)
                {
                    cmdlet.WriteError(
                        new ErrorRecord(
                            exception,
                            $"{nameof(IClusterClient)}{nameof(IClusterClient.Close)}Failed",
                            ErrorCategory.CloseError,
                            client));
                }

                client.Dispose();
            }
            finally
            {
                var sessionClient = cmdlet.GetClient();

                // If this client is the client associated with the current session, clear the current session's client.
                if (ReferenceEquals(sessionClient, client))
                {
                    cmdlet.SetClient(null);
                }
            }
        }
示例#30
0
        public static List <T> ExecuteScript <T>(this PSCmdlet cmdlet, string contents)
        {
            List <T> output = new List <T>();

            using (PowerShell powershell = PowerShell.Create(RunspaceMode.CurrentRunspace))
            {
                powershell.AddScript(contents);
                Collection <T> result = powershell.Invoke <T>();

                if (cmdlet.SessionState != null)
                {
                    powershell.Streams.Error.ForEach(e => cmdlet.WriteError(e));
                    powershell.Streams.Verbose.ForEach(r => cmdlet.WriteVerbose(r.Message));
                    powershell.Streams.Warning.ForEach(r => cmdlet.WriteWarning(r.Message));
                }

                if (result != null && result.Count > 0)
                {
                    output.AddRange(result);
                }
            }

            return(output);
        }