Example #1
0
        internal PSArgumentException NewArgumentException(string paramName)
        {
            PSArgumentException argumentException = !string.IsNullOrEmpty(paramName) ? new PSArgumentException(ResourceManagerCache.FormatResourceString(Assembly.GetAssembly(typeof(PSObject)), "AutomationExceptions", "Argument", (object)paramName), paramName) : throw new ArgumentNullException(nameof(paramName));

            this.TraceException((Exception)argumentException);
            return(argumentException);
        }
Example #2
0
        void CopyContainerToContainer(ContainerCmdletProvider provider, string srcPath, string destPath, bool recurse,
                                      CopyContainers copyContainers, ProviderRuntime runtime)
        {
            // the "usual" case: if we don't use recursion (empty container is copied) or we want to maintain the
            // original hierarchy
            if (!recurse || copyContainers.Equals(CopyContainers.CopyTargetContainer))
            {
                provider.CopyItem(srcPath, destPath, recurse, runtime);
                return;
            }
            // Otherwise we want a flat-hierachy copy of a folder (because copyContainers is CopyChildrenOfTargetContainer)
            // Make sure recurse is set
            if (!recurse)
            {
                var error = new PSArgumentException("Cannot copy container to existing leaf",
                                                    "CopyContainerItemToLeafError", ErrorCategory.InvalidArgument).ErrorRecord;
                runtime.WriteError(error);
                return;
            }
            // otherwise do the flat copy. To do this: get all child names (recursively) and invoke copying without recursion
            var childNames = ChildItem.GetNames(srcPath, ReturnContainers.ReturnMatchingContainers, true);

            foreach (var child in childNames)
            {
                var childPath = Path.Combine(provider, srcPath, child, runtime);
                provider.CopyItem(childPath, destPath, false, runtime);
            }
        }
Example #3
0
        /// <summary>
        /// Traces the Message and StackTrace properties of the exception
        /// and returns the new exception. This variant uses the default
        /// ArgumentException template text. This is not allowed to call
        /// other Throw*Exception variants, since they call this.
        /// </summary>
        /// <param name="paramName">
        /// The name of the parameter whose argument value was invalid
        /// </param>
        /// <returns>Exception instance ready to throw</returns>
        internal static PSArgumentException NewArgumentException(string paramName)
        {
            if (String.IsNullOrEmpty(paramName))
            {
                throw new ArgumentNullException("paramName");
            }
            string message = StringUtil.Format(AutomationExceptions.Argument, paramName);
            // Note that the message param comes first
            var e = new PSArgumentException(message, paramName);

            return(e);
        }
Example #4
0
        protected override string NormalizeRelativePath(string path, string basePath)
        {
            var normPath = new Path(path).NormalizeSlashes();
            var normBase = new Path(basePath).NormalizeSlashes();
            if (!normPath.StartsWith(normBase))
            {
                var ex = new PSArgumentException("Path is outside of base path!", "PathOutsideBasePath",
                    ErrorCategory.InvalidArgument);
                WriteError(ex.ErrorRecord);
                return null;
            }

            return new Path(path.Substring(basePath.Length)).TrimStartSlash().ToString();
        }
Example #5
0
 protected override void BeginProcessing()
 {
     base.BeginProcessing();
     if (!this.specifiedPath && !this.isLiteralPath)
     {
         PSArgumentException exception = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyDestinationPathAndLiteralPath, new object[0]));
         base.ThrowTerminatingError(exception.ErrorRecord);
     }
     else if ((this.specifiedPath || this.isLiteralPath) && !(this.specifiedPath ^ this.isLiteralPath))
     {
         PSArgumentException exception2 = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyDestinationPathAndLiteralPath, new object[0]));
         base.ThrowTerminatingError(exception2.ErrorRecord);
     }
 }
Example #6
0
        internal void Copy(string[] path, string destinationPath, bool recurse, CopyContainers copyContainers, ProviderRuntime runtime)
        {
            ProviderInfo destinationProvider;
            var          destRuntime = new ProviderRuntime(runtime);
            var          destination = Globber.GetProviderSpecificPath(destinationPath, destRuntime, out destinationProvider);
            // make sure we don't use the version of IsContainer that globs, or we will have unnecessary provider callbacks
            var destProvider    = destinationProvider.CreateInstance() as ContainerCmdletProvider; // it's okay to be null
            var destIsContainer = IsContainer(destProvider, destination, destRuntime);

            GlobAndInvoke <ContainerCmdletProvider>(path, runtime,
                                                    (curPath, provider) => {
                if (!runtime.PSDriveInfo.Provider.Equals(destinationProvider))
                {
                    var msg   = "The source cannot be copied to the destination, because they're not from the same provider";
                    var error = new PSArgumentException(msg, "CopyItemSourceAndDestinationNotSameProvider",
                                                        ErrorCategory.InvalidArgument);
                    runtime.WriteError(error.ErrorRecord);
                    return;
                }
                // Affected by #trailingSeparatorAmbiguity
                // PS would make sure the trailing slash of curPath is removed
                // check if src is a container
                if (IsContainer(provider, curPath, runtime))
                {
                    // if we copy a container to another, invoke a special method for this
                    if (destIsContainer)
                    {
                        CopyContainerToContainer(provider, curPath, destination, recurse, copyContainers, runtime);
                        return;
                    }
                    // otherwise the destination doesn't exist or is a leaf. Copying a container to a leaf doesn't work
                    if (Exists(destination, destRuntime))
                    {
                        var error = new PSArgumentException("Cannot copy container to existing leaf",
                                                            "CopyContainerItemToLeafError", ErrorCategory.InvalidArgument).ErrorRecord;
                        runtime.WriteError(error);
                        return;
                    }
                    // otherwise we just proceed as normal
                }
                // either leaf to leaf, leaf to container, or container to not-existing (i.e. copy the container)
                provider.CopyItem(curPath, destination, recurse, runtime);
            }
                                                    );
        }
Example #7
0
        /// <summary>
        /// Traces the Message and StackTrace properties of the exception
        /// and returns the new exception. This variant allows the caller to
        /// specify alternate template text, but only in assembly S.M.A.Core.
        /// </summary>
        /// <param name="paramName">
        /// The name of the parameter whose argument value was invalid
        /// </param>
        /// <param name="resourceString">
        /// The template string for this error
        /// </param>
        /// <param name="args">
        /// Objects corresponding to {0}, {1}, etc. in the resource string
        /// </param>
        /// <returns>Exception instance ready to throw</returns>
        internal static PSArgumentException NewArgumentException(
            string paramName, string resourceString, params object[] args)
        {
            if (String.IsNullOrEmpty(paramName))
            {
                throw NewArgumentNullException("paramName");
            }
            if (String.IsNullOrEmpty(resourceString))
            {
                throw NewArgumentNullException("resourceString");
            }

            string message = StringUtil.Format(resourceString, args);

            // Note that the message param comes first
            var e = new PSArgumentException(message, paramName);

            return(e);
        }
Example #8
0
        internal void Move(string[] path, string destinationPath, ProviderRuntime runtime)
        {
            ProviderInfo destinationProvider;
            var          destination = Globber.GetProviderSpecificPath(destinationPath, runtime, out destinationProvider);

            GlobAndInvoke <NavigationCmdletProvider>(path, runtime,
                                                     (curPath, provider) => {
                // TODO: I think Powershell checks whether we are currently in the path we want to remove
                //       (or a subpath). Check this and throw an error if it's true
                if (!runtime.PSDriveInfo.Provider.Equals(destinationProvider))
                {
                    var msg   = "The source cannot be moved to the destination, because they're not from the same provider";
                    var error = new PSArgumentException(msg, "MoveItemSourceAndDestinationNotSameProvider",
                                                        ErrorCategory.InvalidArgument);
                    runtime.WriteError(error.ErrorRecord);
                    return;
                }
                provider.MoveItem(curPath, destination, runtime);
            }
                                                     );
        }
Example #9
0
        internal PSArgumentException NewArgumentException(
            string paramName,
            string baseName,
            string resourceId,
            params object[] args)
        {
            if (string.IsNullOrEmpty(paramName))
            {
                throw this.NewArgumentNullException(nameof(paramName));
            }
            if (string.IsNullOrEmpty(baseName))
            {
                throw this.NewArgumentNullException(nameof(baseName));
            }
            if (string.IsNullOrEmpty(resourceId))
            {
                throw this.NewArgumentNullException(nameof(resourceId));
            }
            PSArgumentException argumentException = new PSArgumentException(ResourceManagerCache.FormatResourceString(Assembly.GetCallingAssembly(), baseName, resourceId, args), paramName);

            this.TraceException((Exception)argumentException);
            return(argumentException);
        }
 protected override void ProcessRecord()
 {
     ProviderInfo provider = null;
     PSDriveInfo info2;
     FileStream stream;
     StreamWriter writer;
     FileInfo info3;
     string filePath = base.SessionState.Path.GetUnresolvedProviderPathFromPSPath(this.path, out provider, out info2);
     if (!provider.NameEquals(base.Context.ProviderNames.FileSystem) || !filePath.EndsWith(".pssc", StringComparison.OrdinalIgnoreCase))
     {
         InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, this.path));
         ErrorRecord errorRecord = new ErrorRecord(exception, "InvalidPSSessionConfigurationFilePath", ErrorCategory.InvalidArgument, this.path);
         base.ThrowTerminatingError(errorRecord);
     }
     PathUtils.MasterStreamOpen(this, filePath, "unicode", false, false, false, false, out stream, out writer, out info3, false);
     try
     {
         StringBuilder builder = new StringBuilder();
         builder.Append("@{");
         builder.Append(writer.NewLine);
         builder.Append(writer.NewLine);
         builder.Append(ConfigFragment(ConfigFileContants.SchemaVersion, RemotingErrorIdStrings.DISCSchemaVersionComment, QuoteName(this.schemaVersion.ToString()), writer));
         builder.Append(ConfigFragment(ConfigFileContants.Guid, RemotingErrorIdStrings.DISCGUIDComment, QuoteName(this.guid.ToString()), writer));
         builder.Append(ConfigFragment(ConfigFileContants.ExecutionPolicy, RemotingErrorIdStrings.DISCExecutionPolicyComment, QuoteName(this.executionPolicy), writer));
         if (!this.isLanguageModeSpecified && (this.initialSessionState == System.Management.Automation.Remoting.SessionType.Default))
         {
             this.languageMode = PSLanguageMode.FullLanguage;
         }
         builder.Append(ConfigFragment(ConfigFileContants.LanguageMode, RemotingErrorIdStrings.DISCLanguageModeComment, QuoteName(this.languageMode), writer));
         builder.Append(ConfigFragment(ConfigFileContants.SessionType, RemotingErrorIdStrings.DISCInitialSessionStateComment, QuoteName(this.initialSessionState.ToString()), writer));
         if (this.environmentVariables == null)
         {
             builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, string.Empty, writer));
         }
         else
         {
             string environmentVariables = this.environmentVariables as string;
             if (environmentVariables != null)
             {
                 builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, environmentVariables, writer));
             }
             else
             {
                 Hashtable table = this.environmentVariables as Hashtable;
                 if (table != null)
                 {
                     builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, this.CombineHashtable(table, writer), writer));
                 }
                 else
                 {
                     builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, string.Empty, writer));
                 }
             }
         }
         if (string.IsNullOrEmpty(this.author))
         {
             this.author = Environment.UserName;
         }
         builder.Append(ConfigFragment(ConfigFileContants.Author, RemotingErrorIdStrings.DISCAuthorComment, QuoteName(this.author), writer));
         if (string.IsNullOrEmpty(this.companyName))
         {
             this.companyName = Modules.DefaultCompanyName;
         }
         builder.Append(ConfigFragment(ConfigFileContants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment, QuoteName(this.companyName), writer));
         if (string.IsNullOrEmpty(this.copyright))
         {
             this.copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, this.author);
         }
         builder.Append(ConfigFragment(ConfigFileContants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment, QuoteName(this.copyright), writer));
         builder.Append(ConfigFragment(ConfigFileContants.Description, RemotingErrorIdStrings.DISCDescriptionComment, string.IsNullOrEmpty(this.description) ? string.Empty : QuoteName(this.description), writer));
         builder.Append(ConfigFragment(ConfigFileContants.PowerShellVersion, RemotingErrorIdStrings.DISCPowerShellVersionComment, (this.powerShellVersion != null) ? QuoteName(this.powerShellVersion.ToString()) : string.Empty, writer));
         builder.Append(ConfigFragment(ConfigFileContants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, (this.modulesToImport != null) ? this.CombineHashTableOrStringArray(this.modulesToImport, writer) : string.Empty, writer));
         builder.Append(ConfigFragment(ConfigFileContants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment, (this.assembliesToLoad != null) ? this.CombineStringArray(this.assembliesToLoad) : string.Empty, writer));
         builder.Append(ConfigFragment(ConfigFileContants.VisibleAliases, RemotingErrorIdStrings.DISCVisibleAliasesComment, this.GetVisibilityDefault(this.visibleAliases), writer));
         builder.Append(ConfigFragment(ConfigFileContants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment, this.GetVisibilityDefault(this.visibleCmdlets), writer));
         builder.Append(ConfigFragment(ConfigFileContants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment, this.GetVisibilityDefault(this.visibleFunctions), writer));
         builder.Append(ConfigFragment(ConfigFileContants.VisibleProviders, RemotingErrorIdStrings.DISCVisibleProvidersComment, this.GetVisibilityDefault(this.visibleProviders), writer));
         builder.Append(ConfigFragment(ConfigFileContants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment, (this.aliasDefinitions != null) ? this.CombineHashtableArray(this.aliasDefinitions, writer) : string.Empty, writer));
         if (this.functionDefinitions == null)
         {
             builder.Append(ConfigFragment(ConfigFileContants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, string.Empty, writer));
         }
         else
         {
             Hashtable[] tables = DISCPowerShellConfiguration.TryGetHashtableArray(this.functionDefinitions);
             if (tables != null)
             {
                 builder.Append(ConfigFragment(ConfigFileContants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, this.CombineHashtableArray(tables, writer), writer));
                 foreach (Hashtable hashtable2 in tables)
                 {
                     if (!hashtable2.ContainsKey(ConfigFileContants.FunctionNameToken))
                     {
                         PSArgumentException exception2 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.FunctionDefinitions, ConfigFileContants.FunctionNameToken, this.path }));
                         base.ThrowTerminatingError(exception2.ErrorRecord);
                     }
                     if (!hashtable2.ContainsKey(ConfigFileContants.FunctionValueToken))
                     {
                         PSArgumentException exception3 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.FunctionDefinitions, ConfigFileContants.FunctionValueToken, this.path }));
                         base.ThrowTerminatingError(exception3.ErrorRecord);
                     }
                     if (!(hashtable2[ConfigFileContants.FunctionValueToken] is ScriptBlock))
                     {
                         PSArgumentException exception4 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, new object[] { ConfigFileContants.FunctionValueToken, ConfigFileContants.FunctionDefinitions, this.path }));
                         base.ThrowTerminatingError(exception4.ErrorRecord);
                     }
                     foreach (string str4 in hashtable2.Keys)
                     {
                         if ((!string.Equals(str4, ConfigFileContants.FunctionNameToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str4, ConfigFileContants.FunctionValueToken, StringComparison.OrdinalIgnoreCase)) && !string.Equals(str4, ConfigFileContants.FunctionOptionsToken, StringComparison.OrdinalIgnoreCase))
                         {
                             PSArgumentException exception5 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, new object[] { str4, ConfigFileContants.FunctionDefinitions, this.path }));
                             base.ThrowTerminatingError(exception5.ErrorRecord);
                         }
                     }
                 }
             }
             else
             {
                 PSArgumentException exception6 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, ConfigFileContants.FunctionDefinitions, filePath));
                 base.ThrowTerminatingError(exception6.ErrorRecord);
             }
         }
         if (this.variableDefinitions == null)
         {
             builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, string.Empty, writer));
         }
         else
         {
             string variableDefinitions = this.variableDefinitions as string;
             if (variableDefinitions != null)
             {
                 builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, variableDefinitions, writer));
             }
             else
             {
                 Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.variableDefinitions);
                 if (hashtableArray2 != null)
                 {
                     builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, this.CombineHashtableArray(hashtableArray2, writer), writer));
                     foreach (Hashtable hashtable3 in hashtableArray2)
                     {
                         if (!hashtable3.ContainsKey(ConfigFileContants.VariableNameToken))
                         {
                             PSArgumentException exception7 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.VariableDefinitions, ConfigFileContants.VariableNameToken, this.path }));
                             base.ThrowTerminatingError(exception7.ErrorRecord);
                         }
                         if (!hashtable3.ContainsKey(ConfigFileContants.VariableValueToken))
                         {
                             PSArgumentException exception8 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.VariableDefinitions, ConfigFileContants.VariableValueToken, this.path }));
                             base.ThrowTerminatingError(exception8.ErrorRecord);
                         }
                         foreach (string str6 in hashtable3.Keys)
                         {
                             if (!string.Equals(str6, ConfigFileContants.VariableNameToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str6, ConfigFileContants.VariableValueToken, StringComparison.OrdinalIgnoreCase))
                             {
                                 PSArgumentException exception9 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, new object[] { str6, ConfigFileContants.VariableDefinitions, this.path }));
                                 base.ThrowTerminatingError(exception9.ErrorRecord);
                             }
                         }
                     }
                 }
                 else
                 {
                     PSArgumentException exception10 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, ConfigFileContants.VariableDefinitions, filePath));
                     base.ThrowTerminatingError(exception10.ErrorRecord);
                 }
             }
         }
         builder.Append(ConfigFragment(ConfigFileContants.TypesToProcess, RemotingErrorIdStrings.DISCTypesToProcessComment, (this.typesToProcess != null) ? this.CombineStringArray(this.typesToProcess) : string.Empty, writer));
         builder.Append(ConfigFragment(ConfigFileContants.FormatsToProcess, RemotingErrorIdStrings.DISCFormatsToProcessComment, (this.formatsToProcess != null) ? this.CombineStringArray(this.formatsToProcess) : string.Empty, writer));
         builder.Append(ConfigFragment(ConfigFileContants.ScriptsToProcess, RemotingErrorIdStrings.DISCScriptsToProcessComment, (this.scriptsToProcess != null) ? this.CombineStringArray(this.scriptsToProcess) : string.Empty, writer));
         builder.Append("}");
         builder.Append(writer.NewLine);
         builder.Append(writer.NewLine);
         writer.Write(builder.ToString());
     }
     finally
     {
         writer.Close();
     }
 }
Example #11
0
        /// <summary>
        /// Sets the digital signature on the specified file.
        /// </summary>
        /// <param name="filePath">
        /// The name of the file on which to perform the action.
        /// </param>
        /// <returns>
        /// The signature on the specified file.
        /// </returns>
        protected override Signature PerformAction(string filePath)
        {
            SigningOption option = GetSigningOption(IncludeChain);

            if (Certificate == null)
            {
                throw PSTraceSource.NewArgumentNullException("certificate");
            }

            //
            // if the cert is not good for signing, we cannot
            // process any more files. Exit the command.
            //
            if (!SecuritySupport.CertIsGoodForSigning(Certificate))
            {
                Exception e = PSTraceSource.NewArgumentException(
                        "certificate",
                        SignatureCommands.CertNotGoodForSigning);

                throw e;
            }

            if (!ShouldProcess(filePath))
                return null;

            FileInfo readOnlyFileInfo = null;
            try
            {
                if (this.Force)
                {
                    try
                    {
                        // remove readonly attributes on the file
                        FileInfo fInfo = new FileInfo(filePath);
                        if (fInfo != null)
                        {
                            // Save some disk write time by checking whether file is readonly..
                            if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                            {
                                // remember to reset the read-only attribute later
                                readOnlyFileInfo = fInfo;
                                //Make sure the file is not read only
                                fInfo.Attributes &= ~(FileAttributes.ReadOnly);
                            }
                        }
                    }
                    // These are the known exceptions for File.Load and StreamWriter.ctor
                    catch (ArgumentException e)
                    {
                        ErrorRecord er = new ErrorRecord(
                            e,
                            "ForceArgumentException",
                            ErrorCategory.WriteError,
                            filePath
                            );
                        WriteError(er);
                        return null;
                    }
                    catch (IOException e)
                    {
                        ErrorRecord er = new ErrorRecord(
                            e,
                            "ForceIOException",
                            ErrorCategory.WriteError,
                            filePath
                            );
                        WriteError(er);
                        return null;
                    }
                    catch (UnauthorizedAccessException e)
                    {
                        ErrorRecord er = new ErrorRecord(
                            e,
                            "ForceUnauthorizedAccessException",
                            ErrorCategory.PermissionDenied,
                            filePath
                            );
                        WriteError(er);
                        return null;
                    }
                    catch (NotSupportedException e)
                    {
                        ErrorRecord er = new ErrorRecord(
                            e,
                            "ForceNotSupportedException",
                            ErrorCategory.WriteError,
                            filePath
                            );
                        WriteError(er);
                        return null;
                    }
                    catch (System.Security.SecurityException e)
                    {
                        ErrorRecord er = new ErrorRecord(
                            e,
                            "ForceSecurityException",
                            ErrorCategory.PermissionDenied,
                            filePath
                            );
                        WriteError(er);
                        return null;
                    }
                }

                //
                // ProcessRecord() code in base class has already
                // ascertained that filePath really represents an existing
                // file. Thus we can safely call GetFileSize() below.
                //

                if (SecurityUtils.GetFileSize(filePath) < 4)
                {
                    // Note that the message param comes first
                    string message = String.Format(
                        System.Globalization.CultureInfo.CurrentCulture,
                        UtilsStrings.FileSmallerThan4Bytes, filePath);

                    PSArgumentException e = new PSArgumentException(message, "filePath");
                    ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord(
                            e,
                            "SignatureCommandsBaseFileSmallerThan4Bytes"
                            );

                    WriteError(er);

                    return null;
                }

                return SignatureHelper.SignFile(option,
                                                filePath,
                                                Certificate,
                                                TimestampServer,
                                                _hashAlgorithm);
            }
            finally
            {
                // reset the read-only attribute
                if (null != readOnlyFileInfo)
                {
                    readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly;
                }
            }
        }
Example #12
0
        /// <summary>
        /// BeginProcessing method.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (ParameterSetName.Equals(DefaultParameterSet, StringComparison.OrdinalIgnoreCase))
            {
                if (WsmanAuthentication != null && (_isDcomAuthenticationSpecified || _isImpersonationSpecified))
                {
                    string errorMsg = StringUtil.Format(ComputerResources.ParameterConfliction,
                                                        ComputerResources.ParameterUsage);
                    InvalidOperationException ex = new InvalidOperationException(errorMsg);
                    ThrowTerminatingError(new ErrorRecord(ex, "ParameterConfliction", ErrorCategory.InvalidOperation, null));
                }

                bool usingDcom = Protocol.Equals(ComputerWMIHelper.DcomProtocol, StringComparison.OrdinalIgnoreCase);
                bool usingWsman = Protocol.Equals(ComputerWMIHelper.WsmanProtocol, StringComparison.OrdinalIgnoreCase);

                if (_isProtocolSpecified && usingDcom && WsmanAuthentication != null)
                {
                    string errorMsg = StringUtil.Format(ComputerResources.InvalidParameterForDCOM,
                                                        ComputerResources.ParameterUsage);
                    InvalidOperationException ex = new InvalidOperationException(errorMsg);
                    ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForDCOM", ErrorCategory.InvalidOperation, null));
                }

                if (_isProtocolSpecified && usingWsman && (_isDcomAuthenticationSpecified || _isImpersonationSpecified))
                {
                    string errorMsg = StringUtil.Format(ComputerResources.InvalidParameterForWSMan,
                                                        ComputerResources.ParameterUsage);
                    InvalidOperationException ex = new InvalidOperationException(errorMsg);
                    ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForWSMan", ErrorCategory.InvalidOperation, null));
                }

                if (!_isProtocolSpecified && WsmanAuthentication != null)
                {
                    // Change the protocol to be WSMan if the WsmanAuthentication is specified
                    Protocol = ComputerWMIHelper.WsmanProtocol;
                }
            }

#if CORECLR
            if (this.MyInvocation.BoundParameters.ContainsKey("DcomAuthentication"))
            {
                string errMsg = StringUtil.Format(ComputerResources.InvalidParameterForCoreClr, "DcomAuthentication");
                PSArgumentException ex = new PSArgumentException(errMsg, ComputerResources.InvalidParameterForCoreClr);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForCoreClr", ErrorCategory.InvalidArgument, null));
            }

            if (this.MyInvocation.BoundParameters.ContainsKey("Impersonation"))
            {
                string errMsg = StringUtil.Format(ComputerResources.InvalidParameterForCoreClr, "Impersonation");
                PSArgumentException ex = new PSArgumentException(errMsg, ComputerResources.InvalidParameterForCoreClr);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForCoreClr", ErrorCategory.InvalidArgument, null));
            }

            // DCOM Authentication is not supported for CoreCLR. Throw an error
            // and request that the user specify WSMan Authentication.
            if (_isDcomAuthenticationSpecified || 
                Protocol.Equals(ComputerWMIHelper.DcomProtocol, StringComparison.OrdinalIgnoreCase))
            {
                InvalidOperationException ex = new InvalidOperationException(ComputerResources.InvalidParameterDCOMNotSupported);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterDCOMNotSupported", ErrorCategory.InvalidOperation, null));
            }

            // TODO:CORECLR This should be re-visited if we decide to add double hop remoting to CoreCLR (outgoing connections)
            if (ParameterSetName.Equals(AsJobParameterSet, StringComparison.OrdinalIgnoreCase))
            {
                InvalidOperationException ex = new InvalidOperationException(ComputerResources.InvalidParameterSetAsJob);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterSetAsJob", ErrorCategory.InvalidOperation, null));
            }
#endif

            // Timeout, For, Delay, Progress cannot be present if Wait is not present
            if ((_timeoutSpecified || _waitForSpecified || _delaySpecified) && !Wait)
            {
                InvalidOperationException ex = new InvalidOperationException(ComputerResources.RestartComputerInvalidParameter);
                ThrowTerminatingError(new ErrorRecord(ex, "RestartComputerInvalidParameter", ErrorCategory.InvalidOperation, null));
            }

            if (Wait)
            {
                _activityId = (new Random()).Next();
                if (_timeout == -1 || _timeout >= int.MaxValue / 1000)
                {
                    _timeoutInMilliseconds = int.MaxValue;
                }
                else
                {
                    _timeoutInMilliseconds = _timeout * 1000;
                }

                // We don't support combined service types for now
                switch (_waitFor)
                {
                    case WaitForServiceTypes.Wmi:
                    case WaitForServiceTypes.WinRM:
                        break;
                    case WaitForServiceTypes.PowerShell:
                        _powershell = System.Management.Automation.PowerShell.Create();
                        _powershell.AddScript(TestPowershellScript);
                        break;
                    default:
                        InvalidOperationException ex = new InvalidOperationException(ComputerResources.NoSupportForCombinedServiceType);
                        ErrorRecord error = new ErrorRecord(ex, "NoSupportForCombinedServiceType", ErrorCategory.InvalidOperation, (int)_waitFor);
                        ThrowTerminatingError(error);
                        break;
                }
            }
        }
 internal void Move(string[] path, string destinationPath, ProviderRuntime runtime)
 {
     ProviderInfo destinationProvider;
     var destination = Globber.GetProviderSpecificPath(destinationPath, runtime, out destinationProvider);
     GlobAndInvoke<NavigationCmdletProvider>(path, runtime,
         (curPath, provider) => {
             // TODO: I think Powershell checks whether we are currently in the path we want to remove
             //       (or a subpath). Check this and throw an error if it's true
             if (!runtime.PSDriveInfo.Provider.Equals(destinationProvider))
             {
                 var msg = "The source cannot be moved to the destination, because they're not from the same provider";
                 var error = new PSArgumentException(msg, "MoveItemSourceAndDestinationNotSameProvider",
                     ErrorCategory.InvalidArgument);
                 runtime.WriteError(error.ErrorRecord);
                 return;
             }
             provider.MoveItem(curPath, destination, runtime);
         }
     );
 }
Example #14
0
        /// <summary>
        /// Traces the Message and StackTrace properties of the exception
        /// and returns the new exception. This variant allows the caller to
        /// specify alternate template text, but only in assembly S.M.A.Core.
        /// </summary>
        /// <param name="paramName">
        /// The name of the parameter whose argument value was invalid
        /// </param>
        /// <param name="resourceString">
        /// The template string for this error
        /// </param>
        /// <param name="args">
        /// Objects corresponding to {0}, {1}, etc. in the resource string
        /// </param>
        /// <returns>Exception instance ready to throw</returns>
        internal static PSArgumentException NewArgumentException(
            string paramName, string resourceString, params object[] args)
        {
            if (String.IsNullOrEmpty(paramName))
            {
                throw NewArgumentNullException("paramName");
            }
            if (String.IsNullOrEmpty(resourceString))
            {
                throw NewArgumentNullException("resourceString");
            }

            string message = StringUtil.Format(resourceString, args);

            // Note that the message param comes first
            var e = new PSArgumentException(message, paramName);

            return e;
        }
		protected override Signature PerformAction(string filePath)
		{
			Signature signature;
			SigningOption signingOption = SetAuthenticodeSignatureCommand.GetSigningOption(this.IncludeChain);
			if (this.Certificate != null)
			{
				if (SecuritySupport.CertIsGoodForSigning(this.Certificate))
				{
					if (base.ShouldProcess(filePath))
					{
						FileInfo fileInfo = null;
						try
						{
							if (this.Force)
							{
								try
								{
									FileInfo fileInfo1 = new FileInfo(filePath);
									if (fileInfo1 != null && (fileInfo1.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
									{
										fileInfo = fileInfo1;
										FileInfo attributes = fileInfo1;
										attributes.Attributes = attributes.Attributes & (FileAttributes.Hidden | FileAttributes.System | FileAttributes.Directory | FileAttributes.Archive | FileAttributes.Device | FileAttributes.Normal | 
										                                                 FileAttributes.Temporary | FileAttributes.SparseFile | FileAttributes.ReparsePoint | FileAttributes.Compressed | FileAttributes.Offline | 
										                                                 FileAttributes.NotContentIndexed | FileAttributes.Encrypted
#if !MONO
										                                                 | FileAttributes.IntegrityStream | FileAttributes.NoScrubData
#endif
										                                                 );
									}
								}
								catch (ArgumentException argumentException1)
								{
									ArgumentException argumentException = argumentException1;
									ErrorRecord errorRecord = new ErrorRecord(argumentException, "ForceArgumentException", ErrorCategory.WriteError, filePath);
									base.WriteError(errorRecord);
									signature = null;
									return signature;
								}
								catch (IOException oException1)
								{
									IOException oException = oException1;
									ErrorRecord errorRecord1 = new ErrorRecord(oException, "ForceIOException", ErrorCategory.WriteError, filePath);
									base.WriteError(errorRecord1);
									signature = null;
									return signature;
								}
								catch (UnauthorizedAccessException unauthorizedAccessException1)
								{
									UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1;
									ErrorRecord errorRecord2 = new ErrorRecord(unauthorizedAccessException, "ForceUnauthorizedAccessException", ErrorCategory.PermissionDenied, filePath);
									base.WriteError(errorRecord2);
									signature = null;
									return signature;
								}
								catch (NotSupportedException notSupportedException1)
								{
									NotSupportedException notSupportedException = notSupportedException1;
									ErrorRecord errorRecord3 = new ErrorRecord(notSupportedException, "ForceNotSupportedException", ErrorCategory.WriteError, filePath);
									base.WriteError(errorRecord3);
									signature = null;
									return signature;
								}
								catch (SecurityException securityException1)
								{
									SecurityException securityException = securityException1;
									ErrorRecord errorRecord4 = new ErrorRecord(securityException, "ForceSecurityException", ErrorCategory.PermissionDenied, filePath);
									base.WriteError(errorRecord4);
									signature = null;
									return signature;
								}
							}
							if (SecurityUtils.GetFileSize(filePath) >= (long)4)
							{
								signature = SignatureHelper.SignFile(signingOption, filePath, this.Certificate, this.TimestampServer, this.hashAlgorithm);
							}
							else
							{
								object[] objArray = new object[1];
								objArray[0] = filePath;
								string str = string.Format(CultureInfo.CurrentCulture, UtilsStrings.FileSmallerThan4Bytes, objArray);
								PSArgumentException pSArgumentException = new PSArgumentException(str, "filePath");
								ErrorRecord errorRecord5 = SecurityUtils.CreateInvalidArgumentErrorRecord(pSArgumentException, "SignatureCommandsBaseFileSmallerThan4Bytes");
								base.WriteError(errorRecord5);
								signature = null;
							}
						}
						finally
						{
							if (fileInfo != null)
							{
								FileInfo attributes1 = fileInfo;
								attributes1.Attributes = attributes1.Attributes | FileAttributes.ReadOnly;
							}
						}
						return signature;
					}
					else
					{
						return null;
					}
				}
				else
				{
					Exception exception = PSTraceSource.NewArgumentException("certificate", "SignatureCommands", "CertNotGoodForSigning", new object[0]);
					throw exception;
				}
			}
			else
			{
				throw PSTraceSource.NewArgumentNullException("certificate");
			}
		}
Example #16
0
 /// <summary>
 /// Throw conflict parameter error
 /// </summary>
 /// <param name="operationName"></param>
 /// <param name="parameterName"></param>
 /// <param name="conflictParameterName"></param>
 internal void ThrowConflictParameterWasSet(
     string operationName,
     string parameterName,
     string conflictParameterName)
 {
     string message = String.Format(CultureInfo.CurrentUICulture,
         Strings.ConflictParameterWasSet,
         parameterName, conflictParameterName);
     PSArgumentException exception = new PSArgumentException(message, parameterName);
     ThrowTerminatingError(exception, operationName);
 }
        /// <summary>
        ///
        /// </summary>
        protected override void ProcessRecord()
        {
            Debug.Assert(!String.IsNullOrEmpty(_path));

            ProviderInfo provider = null;
            PSDriveInfo drive;
            string filePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_path, out provider, out drive);

            if (!provider.NameEquals(Context.ProviderNames.FileSystem) || !filePath.EndsWith(StringLiterals.PowerShellDISCFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                string message = StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, _path);
                InvalidOperationException ioe = new InvalidOperationException(message);
                ErrorRecord er = new ErrorRecord(ioe, "InvalidPSSessionConfigurationFilePath",
                    ErrorCategory.InvalidArgument, _path);
                ThrowTerminatingError(er);
            }

            FileStream fileStream;
            StreamWriter streamWriter;
            FileInfo readOnlyFileInfo;

            // Now open the output file...
            PathUtils.MasterStreamOpen(
                this,
                filePath,
                EncodingConversion.Unicode,
                /* defaultEncoding */ false,
                /* Append */ false,
                /* Force */ false,
                /* NoClobber */ false,
                out fileStream,
                out streamWriter,
                out readOnlyFileInfo,
                false
            );

            try
            {
                StringBuilder result = new StringBuilder();

                result.Append("@{");
                result.Append(streamWriter.NewLine);
                result.Append(streamWriter.NewLine);

                // Schema version
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.SchemaVersion, RemotingErrorIdStrings.DISCSchemaVersionComment,
                    SessionConfigurationUtils.QuoteName(_schemaVersion), streamWriter, false));

                // Guid
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Guid, RemotingErrorIdStrings.DISCGUIDComment, SessionConfigurationUtils.QuoteName(_guid), streamWriter, false));

                // Author
                if (String.IsNullOrEmpty(_author))
                {
                    _author = Environment.UserName;
                }
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Author, RemotingErrorIdStrings.DISCAuthorComment,
                    SessionConfigurationUtils.QuoteName(_author), streamWriter, false));

                // Description
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Description, RemotingErrorIdStrings.DISCDescriptionComment,
                    SessionConfigurationUtils.QuoteName(_description), streamWriter, String.IsNullOrEmpty(_description)));

                // Company name
                if (ShouldGenerateConfigurationSnippet("CompanyName"))
                {
                    if (String.IsNullOrEmpty(_companyName))
                    {
                        _companyName = Modules.DefaultCompanyName;
                    }
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment,
                        SessionConfigurationUtils.QuoteName(_companyName), streamWriter, false));
                }

                // Copyright
                if (ShouldGenerateConfigurationSnippet("Copyright"))
                {
                    if (String.IsNullOrEmpty(_copyright))
                    {
                        _copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, _author);
                    }
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment,
                        SessionConfigurationUtils.QuoteName(_copyright), streamWriter, false));
                }

                // Session type
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.SessionType, RemotingErrorIdStrings.DISCInitialSessionStateComment,
                    SessionConfigurationUtils.QuoteName(_sessionType), streamWriter, false));

                string resultData = null;

                // Transcript directory
                resultData = String.IsNullOrEmpty(_transcriptDirectory) ? "'C:\\Transcripts\\'" : SessionConfigurationUtils.QuoteName(_transcriptDirectory);
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.TranscriptDirectory, RemotingErrorIdStrings.DISCTranscriptDirectoryComment,
                    resultData, streamWriter, String.IsNullOrEmpty(_transcriptDirectory)));

                // Run as virtual account
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RunAsVirtualAccount, RemotingErrorIdStrings.DISCRunAsVirtualAccountComment,
                    SessionConfigurationUtils.WriteBoolean(true), streamWriter, RunAsVirtualAccount == false));

                // Run as virtual account groups
                if (ShouldGenerateConfigurationSnippet("RunAsVirtualAccountGroups"))
                {
                    bool haveVirtualAccountGroups = (RunAsVirtualAccountGroups != null) && (RunAsVirtualAccountGroups.Length > 0);
                    resultData = (haveVirtualAccountGroups) ? SessionConfigurationUtils.CombineStringArray(RunAsVirtualAccountGroups) : "'Remote Desktop Users', 'Remote Management Users'";
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RunAsVirtualAccountGroups, RemotingErrorIdStrings.DISCRunAsVirtualAccountGroupsComment,
                        resultData, streamWriter, !haveVirtualAccountGroups));
                }

                // Mount user drive
                if (ShouldGenerateConfigurationSnippet("MountUserDrive"))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.MountUserDrive, RemotingErrorIdStrings.DISCMountUserDriveComment,
                        SessionConfigurationUtils.WriteBoolean(true), streamWriter, MountUserDrive == false));
                }

                // User drive maximum size
                if (ShouldGenerateConfigurationSnippet("UserDriveMaximumSize"))
                {
                    long userDriveMaxSize = (UserDriveMaximumSize > 0) ? UserDriveMaximumSize : 50000000;
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.UserDriveMaxSize, RemotingErrorIdStrings.DISCUserDriveMaxSizeComment,
                        SessionConfigurationUtils.WriteLong(userDriveMaxSize), streamWriter, (UserDriveMaximumSize <= 0)));
                }

                // Temporarily removed until script input parameter validation is implemented.
                /*
                // Enforce input parameter validation
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnforceInputParameterValidation, RemotingErrorIdStrings.DISCEnforceInputParameterValidation,
                    SessionConfigurationUtils.WriteBoolean(true), streamWriter, EnforceInputParameterValidation == false));
                */

                // Group Managed Service Account Name
                if (ShouldGenerateConfigurationSnippet("GroupManagedServiceAccount"))
                {
                    bool haveGMSAAccountName = !string.IsNullOrEmpty(GroupManagedServiceAccount);
                    resultData = (!haveGMSAAccountName) ? "'CONTOSO\\GroupManagedServiceAccount'" : SessionConfigurationUtils.QuoteName(GroupManagedServiceAccount);
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.GMSAAccount, RemotingErrorIdStrings.DISCGMSAComment,
                        resultData, streamWriter, !haveGMSAAccountName));
                }

                // Scripts to process
                resultData = (_scriptsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_scriptsToProcess) : "'C:\\ConfigData\\InitScript1.ps1', 'C:\\ConfigData\\InitScript2.ps1'";
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ScriptsToProcess, RemotingErrorIdStrings.DISCScriptsToProcessComment,
                    resultData, streamWriter, (_scriptsToProcess.Length == 0)));

                // Role definitions
                if (_roleDefinitions == null)
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RoleDefinitions, RemotingErrorIdStrings.DISCRoleDefinitionsComment,
                        "@{ 'CONTOSO\\SqlAdmins' = @{ RoleCapabilities = 'SqlAdministration' }; 'CONTOSO\\ServerMonitors' = @{ VisibleCmdlets = 'Get-Process' } } ", streamWriter, true));
                }
                else
                {
                    DISCUtils.ValidateRoleDefinitions(_roleDefinitions);

                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RoleDefinitions, RemotingErrorIdStrings.DISCRoleDefinitionsComment,
                        SessionConfigurationUtils.CombineHashtable(_roleDefinitions, streamWriter), streamWriter, false));
                }

                // Required groups
                if (ShouldGenerateConfigurationSnippet("RequiredGroups"))
                {
                    if (_requiredGroups == null)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RequiredGroups, RemotingErrorIdStrings.DISCRequiredGroupsComment,
                            "@{ And = @{ Or = 'CONTOSO\\SmartCard-Logon1', 'CONTOSO\\SmartCard-Logon2' }, 'Administrators' }", streamWriter, true));
                    }
                    else
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RequiredGroups, RemotingErrorIdStrings.DISCRequiredGroupsComment,
                            SessionConfigurationUtils.CombineRequiredGroupsHash(_requiredGroups), streamWriter, false));
                    }
                }

                // PSLanguageMode languageMode
                if (ShouldGenerateConfigurationSnippet("LanguageMode"))
                {
                    if (!_isLanguageModeSpecified)
                    {
                        if (_sessionType == SessionType.Default)
                        {
                            _languageMode = PSLanguageMode.FullLanguage;
                        }
                    }
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.LanguageMode, RemotingErrorIdStrings.DISCLanguageModeComment,
                        SessionConfigurationUtils.QuoteName(_languageMode), streamWriter, false));
                }

                // ExecutionPolicy executionPolicy
                if (ShouldGenerateConfigurationSnippet("ExecutionPolicy"))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ExecutionPolicy, RemotingErrorIdStrings.DISCExecutionPolicyComment,
                        SessionConfigurationUtils.QuoteName(_executionPolicy), streamWriter, false));
                }

                // PowerShell version
                bool isExample = false;

                if (ShouldGenerateConfigurationSnippet("PowerShellVersion"))
                {
                    if (_powerShellVersion == null)
                    {
                        isExample = true;
                        _powerShellVersion = PSVersionInfo.PSVersion;
                    }
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.PowerShellVersion, RemotingErrorIdStrings.DISCPowerShellVersionComment,
                        SessionConfigurationUtils.QuoteName(_powerShellVersion), streamWriter, isExample));
                }

                // Modules to import
                if (_modulesToImport == null)
                {
                    if (Full)
                    {
                        string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }";
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true));
                    }
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment,
                        SessionConfigurationUtils.CombineHashTableOrStringArray(_modulesToImport, streamWriter, this), streamWriter, false));
                }

                // Visible aliases
                if (ShouldGenerateConfigurationSnippet("VisibleAliases"))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleAliases, RemotingErrorIdStrings.DISCVisibleAliasesComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleAliases, streamWriter, this), streamWriter, _visibleAliases.Length == 0));
                }

                // Visible cmdlets
                if ((_visibleCmdlets == null) || (_visibleCmdlets.Length == 0))
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment,
                            "'Invoke-Cmdlet1', @{ Name = 'Invoke-Cmdlet2'; Parameters = @{ Name = 'Parameter1'; ValidateSet = 'Item1', 'Item2' }, @{ Name = 'Parameter2'; ValidatePattern = 'L*' } }", streamWriter, true));
                    }
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleCmdlets, streamWriter, this), streamWriter, false));
                }

                // Visible functions
                if ((_visibleFunctions == null) || (_visibleFunctions.Length == 0))
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment,
                            "'Invoke-Function1', @{ Name = 'Invoke-Function2'; Parameters = @{ Name = 'Parameter1'; ValidateSet = 'Item1', 'Item2' }, @{ Name = 'Parameter2'; ValidatePattern = 'L*' } }", streamWriter, true));
                    }
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleFunctions, streamWriter, this), streamWriter, _visibleFunctions.Length == 0));
                }

                // Visible external commands (scripts, executables)
                if (ShouldGenerateConfigurationSnippet("VisibleExternalCommands"))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleExternalCommands, RemotingErrorIdStrings.DISCVisibleExternalCommandsComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleExternalCommands, streamWriter, this), streamWriter, _visibleExternalCommands.Length == 0));
                }

                // Visible providers
                if (ShouldGenerateConfigurationSnippet("VisibleProviders"))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleProviders, RemotingErrorIdStrings.DISCVisibleProvidersComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleProviders, streamWriter, this), streamWriter, _visibleProviders.Length == 0));
                }

                // Alias definitions
                if ((_aliasDefinitions == null) || (_aliasDefinitions.Length == 0))
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment,
                           "@{ Name = 'Alias1'; Value = 'Invoke-Alias1'}, @{ Name = 'Alias2'; Value = 'Invoke-Alias2'}", streamWriter, true));
                    }
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment,
                        SessionConfigurationUtils.CombineHashtableArray(_aliasDefinitions, streamWriter), streamWriter, false));
                }

                // Function definitions
                if (_functionDefinitions == null)
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment,
                            "@{ Name = 'MyFunction'; ScriptBlock = { param($MyInput) $MyInput } }", streamWriter, true));
                    }
                }
                else
                {
                    Hashtable[] funcHash = DISCPowerShellConfiguration.TryGetHashtableArray(_functionDefinitions);

                    if (funcHash != null)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment,
                            SessionConfigurationUtils.CombineHashtableArray(funcHash, streamWriter), streamWriter, false));

                        foreach (Hashtable hashtable in funcHash)
                        {
                            if (!hashtable.ContainsKey(ConfigFileConstants.FunctionNameToken))
                            {
                                PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                    ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionNameToken, _path));
                                ThrowTerminatingError(e.ErrorRecord);
                            }

                            if (!hashtable.ContainsKey(ConfigFileConstants.FunctionValueToken))
                            {
                                PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                    ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionValueToken, _path));
                                ThrowTerminatingError(e.ErrorRecord);
                            }

                            if ((hashtable[ConfigFileConstants.FunctionValueToken] as ScriptBlock) == null)
                            {
                                PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock,
                                    ConfigFileConstants.FunctionValueToken, ConfigFileConstants.FunctionDefinitions, _path));
                                ThrowTerminatingError(e.ErrorRecord);
                            }

                            foreach (string functionKey in hashtable.Keys)
                            {
                                if (!String.Equals(functionKey, ConfigFileConstants.FunctionNameToken, StringComparison.OrdinalIgnoreCase) &&
                                    !String.Equals(functionKey, ConfigFileConstants.FunctionValueToken, StringComparison.OrdinalIgnoreCase) &&
                                    !String.Equals(functionKey, ConfigFileConstants.FunctionOptionsToken, StringComparison.OrdinalIgnoreCase))
                                {
                                    PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey,
                                        functionKey, ConfigFileConstants.FunctionDefinitions, _path));
                                    ThrowTerminatingError(e.ErrorRecord);
                                }
                            }
                        }
                    }
                    else
                    {
                        PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray,
                            ConfigFileConstants.FunctionDefinitions, filePath));
                        ThrowTerminatingError(e.ErrorRecord);
                    }
                }

                // Variable definitions
                if (_variableDefinitions == null)
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment,
                            "@{ Name = 'Variable1'; Value = { 'Dynamic' + 'InitialValue' } }, @{ Name = 'Variable2'; Value = 'StaticInitialValue' }", streamWriter, true));
                    }
                }
                else
                {
                    string varString = _variableDefinitions as string;

                    if (varString != null)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment,
                            varString, streamWriter, false));
                    }
                    else
                    {
                        Hashtable[] varHash = DISCPowerShellConfiguration.TryGetHashtableArray(_variableDefinitions);

                        if (varHash != null)
                        {
                            result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment,
                                SessionConfigurationUtils.CombineHashtableArray(varHash, streamWriter), streamWriter, false));

                            foreach (Hashtable hashtable in varHash)
                            {
                                if (!hashtable.ContainsKey(ConfigFileConstants.VariableNameToken))
                                {
                                    PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                        ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableNameToken, _path));
                                    ThrowTerminatingError(e.ErrorRecord);
                                }

                                if (!hashtable.ContainsKey(ConfigFileConstants.VariableValueToken))
                                {
                                    PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                        ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableValueToken, _path));
                                    ThrowTerminatingError(e.ErrorRecord);
                                }

                                foreach (string variableKey in hashtable.Keys)
                                {
                                    if (!String.Equals(variableKey, ConfigFileConstants.VariableNameToken, StringComparison.OrdinalIgnoreCase) &&
                                        !String.Equals(variableKey, ConfigFileConstants.VariableValueToken, StringComparison.OrdinalIgnoreCase))
                                    {
                                        PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey,
                                            variableKey, ConfigFileConstants.VariableDefinitions, _path));
                                        ThrowTerminatingError(e.ErrorRecord);
                                    }
                                }
                            }
                        }
                        else
                        {
                            PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray,
                                ConfigFileConstants.VariableDefinitions, filePath));
                            ThrowTerminatingError(e.ErrorRecord);
                        }
                    }
                }

                // Environment variables
                if (_environmentVariables == null)
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment,
                            "@{ Variable1 = 'Value1'; Variable2 = 'Value2' }",
                            streamWriter, true));
                    }
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment,
                        SessionConfigurationUtils.CombineHashtable(_environmentVariables, streamWriter), streamWriter, false));
                }

                // Types to process
                if (ShouldGenerateConfigurationSnippet("TypesToProcess"))
                {
                    resultData = (_typesToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_typesToProcess) : "'C:\\ConfigData\\MyTypes.ps1xml', 'C:\\ConfigData\\OtherTypes.ps1xml'";
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.TypesToProcess, RemotingErrorIdStrings.DISCTypesToProcessComment,
                        resultData, streamWriter, (_typesToProcess.Length == 0)));
                }

                // Formats to process
                if (ShouldGenerateConfigurationSnippet("FormatsToProcess"))
                {
                    resultData = (_formatsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_formatsToProcess) : "'C:\\ConfigData\\MyFormats.ps1xml', 'C:\\ConfigData\\OtherFormats.ps1xml'";
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FormatsToProcess, RemotingErrorIdStrings.DISCFormatsToProcessComment,
                        resultData, streamWriter, (_formatsToProcess.Length == 0)));
                }

                // Assemblies to load
                if (ShouldGenerateConfigurationSnippet("AssembliesToLoad"))
                {
                    isExample = false;
                    if ((_assembliesToLoad == null) || (_assembliesToLoad.Length == 0))
                    {
                        isExample = true;
                        _assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" };
                    }
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment,
                        SessionConfigurationUtils.CombineStringArray(_assembliesToLoad), streamWriter, isExample));
                }

                result.Append("}");

                streamWriter.Write(result.ToString());
            }
            finally
            {
                streamWriter.Dispose();
            }
        }
        /// <summary>
        /// Combines an array of strings or hashtables into a single string block
        /// </summary>
        internal static string CombineHashTableOrStringArray(object[] values, StreamWriter writer, PSCmdlet caller)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < values.Length; i++)
            {
                string strVal = values[i] as string;
                if (!String.IsNullOrEmpty(strVal))
                {
                    sb.Append(QuoteName(strVal));
                }
                else
                {
                    Hashtable hashVal = values[i] as Hashtable;
                    if (null == hashVal)
                    {
                        string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray,
                                                           ConfigFileConstants.ModulesToImport);
                        PSArgumentException e = new PSArgumentException(message);
                        caller.ThrowTerminatingError(e.ErrorRecord);
                    }
                    sb.Append(CombineHashtable(hashVal, writer));
                }

                if (i < (values.Length - 1))
                {
                    sb.Append(", ");
                }
            }

            return sb.ToString();
        }
        /// <summary>
        /// 
        /// </summary>
        protected override void ProcessRecord()
        {
            Debug.Assert(!String.IsNullOrEmpty(_path));

            ProviderInfo provider = null;
            PSDriveInfo drive;
            string filePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_path, out provider, out drive);

            if (!provider.NameEquals(Context.ProviderNames.FileSystem) || !filePath.EndsWith(StringLiterals.PowerShellRoleCapabilityFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                string message = StringUtil.Format(RemotingErrorIdStrings.InvalidRoleCapabilityFilePath, _path);
                InvalidOperationException ioe = new InvalidOperationException(message);
                ErrorRecord er = new ErrorRecord(ioe, "InvalidRoleCapabilityFilePath",
                    ErrorCategory.InvalidArgument, _path);
                ThrowTerminatingError(er);
            }

            FileStream fileStream;
            StreamWriter streamWriter;
            FileInfo readOnlyFileInfo;

            // Now open the output file...
            PathUtils.MasterStreamOpen(
                this,
                filePath,
                EncodingConversion.Unicode,
                /* defaultEncoding */ false,
                /* Append */ false,
                /* Force */ false,
                /* NoClobber */ false,
                out fileStream,
                out streamWriter,
                out readOnlyFileInfo,
                false
            );

            try
            {
                StringBuilder result = new StringBuilder();

                result.Append("@{");
                result.Append(streamWriter.NewLine);
                result.Append(streamWriter.NewLine);

                // Guid
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Guid, RemotingErrorIdStrings.DISCGUIDComment, SessionConfigurationUtils.QuoteName(_guid), streamWriter, false));

                // Author
                if (String.IsNullOrEmpty(_author))
                {
                    _author = Environment.UserName;
                }
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Author, RemotingErrorIdStrings.DISCAuthorComment,
                    SessionConfigurationUtils.QuoteName(_author), streamWriter, false));

                // Description
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Description, RemotingErrorIdStrings.DISCDescriptionComment,
                    SessionConfigurationUtils.QuoteName(_description), streamWriter, String.IsNullOrEmpty(_description)));

                // Company name
                if (String.IsNullOrEmpty(_companyName))
                {
                    _companyName = Modules.DefaultCompanyName;
                }
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment,
                    SessionConfigurationUtils.QuoteName(_companyName), streamWriter, false));

                // Copyright
                if (String.IsNullOrEmpty(_copyright))
                {
                    _copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, _author);
                }
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment,
                    SessionConfigurationUtils.QuoteName(_copyright), streamWriter, false));

                // Modules to import
                if (_modulesToImport == null)
                {
                    string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }";
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true));
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment,
                        SessionConfigurationUtils.CombineHashTableOrStringArray(_modulesToImport, streamWriter, this), streamWriter, false));
                }

                // Visible aliases
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleAliases, RemotingErrorIdStrings.DISCVisibleAliasesComment,
                    SessionConfigurationUtils.GetVisibilityDefault(_visibleAliases, streamWriter, this), streamWriter, _visibleAliases.Length == 0));

                // Visible cmdlets
                if ((_visibleCmdlets == null) || (_visibleCmdlets.Length == 0))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment,
                        "'Invoke-Cmdlet1', @{ Name = 'Invoke-Cmdlet2'; Parameters = @{ Name = 'Parameter1'; ValidateSet = 'Item1', 'Item2' }, @{ Name = 'Parameter2'; ValidatePattern = 'L*' } }", streamWriter, true));
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleCmdlets, streamWriter, this), streamWriter, false));
                }

                // Visible functions
                if ((_visibleFunctions == null) || (_visibleFunctions.Length == 0))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment,
                        "'Invoke-Function1', @{ Name = 'Invoke-Function2'; Parameters = @{ Name = 'Parameter1'; ValidateSet = 'Item1', 'Item2' }, @{ Name = 'Parameter2'; ValidatePattern = 'L*' } }", streamWriter, true));
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleFunctions, streamWriter, this), streamWriter, _visibleFunctions.Length == 0));
                }

                // Visible external commands (scripts, executables)
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleExternalCommands, RemotingErrorIdStrings.DISCVisibleExternalCommandsComment,
                    SessionConfigurationUtils.GetVisibilityDefault(_visibleExternalCommands, streamWriter, this), streamWriter, _visibleExternalCommands.Length == 0));

                // Visible providers
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleProviders, RemotingErrorIdStrings.DISCVisibleProvidersComment,
                    SessionConfigurationUtils.GetVisibilityDefault(_visibleProviders, streamWriter, this), streamWriter, _visibleProviders.Length == 0));

                // Scripts to process
                string resultData = (_scriptsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_scriptsToProcess) : "'C:\\ConfigData\\InitScript1.ps1', 'C:\\ConfigData\\InitScript2.ps1'";
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ScriptsToProcess, RemotingErrorIdStrings.DISCScriptsToProcessComment,
                    resultData, streamWriter, (_scriptsToProcess.Length == 0)));

                // Alias definitions
                if ((_aliasDefinitions == null) || (_aliasDefinitions.Length == 0))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment,
                       "@{ Name = 'Alias1'; Value = 'Invoke-Alias1'}, @{ Name = 'Alias2'; Value = 'Invoke-Alias2'}", streamWriter, true));
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment,
                        SessionConfigurationUtils.CombineHashtableArray(_aliasDefinitions, streamWriter), streamWriter, false));
                }

                // Function definitions
                if (_functionDefinitions == null)
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment,
                        "@{ Name = 'MyFunction'; ScriptBlock = { param($MyInput) $MyInput } }", streamWriter, true));
                }
                else
                {
                    Hashtable[] funcHash = DISCPowerShellConfiguration.TryGetHashtableArray(_functionDefinitions);

                    if (funcHash != null)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment,
                            SessionConfigurationUtils.CombineHashtableArray(funcHash, streamWriter), streamWriter, false));

                        foreach (Hashtable hashtable in funcHash)
                        {
                            if (!hashtable.ContainsKey(ConfigFileConstants.FunctionNameToken))
                            {
                                PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                    ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionNameToken, _path));
                                ThrowTerminatingError(e.ErrorRecord);
                            }

                            if (!hashtable.ContainsKey(ConfigFileConstants.FunctionValueToken))
                            {
                                PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                    ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionValueToken, _path));
                                ThrowTerminatingError(e.ErrorRecord);
                            }

                            if ((hashtable[ConfigFileConstants.FunctionValueToken] as ScriptBlock) == null)
                            {
                                PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock,
                                    ConfigFileConstants.FunctionValueToken, ConfigFileConstants.FunctionDefinitions, _path));
                                ThrowTerminatingError(e.ErrorRecord);
                            }

                            foreach (string functionKey in hashtable.Keys)
                            {
                                if (!String.Equals(functionKey, ConfigFileConstants.FunctionNameToken, StringComparison.OrdinalIgnoreCase) &&
                                    !String.Equals(functionKey, ConfigFileConstants.FunctionValueToken, StringComparison.OrdinalIgnoreCase) &&
                                    !String.Equals(functionKey, ConfigFileConstants.FunctionOptionsToken, StringComparison.OrdinalIgnoreCase))
                                {
                                    PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey,
                                        functionKey, ConfigFileConstants.FunctionDefinitions, _path));
                                    ThrowTerminatingError(e.ErrorRecord);
                                }
                            }
                        }
                    }
                    else
                    {
                        PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray,
                            ConfigFileConstants.FunctionDefinitions, filePath));
                        ThrowTerminatingError(e.ErrorRecord);
                    }
                }

                // Variable definitions
                if (_variableDefinitions == null)
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment,
                        "@{ Name = 'Variable1'; Value = { 'Dynamic' + 'InitialValue' } }, @{ Name = 'Variable2'; Value = 'StaticInitialValue' }", streamWriter, true));
                }
                else
                {
                    string varString = _variableDefinitions as string;

                    if (varString != null)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment,
                            varString, streamWriter, false));
                    }
                    else
                    {
                        Hashtable[] varHash = DISCPowerShellConfiguration.TryGetHashtableArray(_variableDefinitions);

                        if (varHash != null)
                        {
                            result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment,
                                SessionConfigurationUtils.CombineHashtableArray(varHash, streamWriter), streamWriter, false));

                            foreach (Hashtable hashtable in varHash)
                            {
                                if (!hashtable.ContainsKey(ConfigFileConstants.VariableNameToken))
                                {
                                    PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                        ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableNameToken, _path));
                                    ThrowTerminatingError(e.ErrorRecord);
                                }

                                if (!hashtable.ContainsKey(ConfigFileConstants.VariableValueToken))
                                {
                                    PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                        ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableValueToken, _path));
                                    ThrowTerminatingError(e.ErrorRecord);
                                }

                                foreach (string variableKey in hashtable.Keys)
                                {
                                    if (!String.Equals(variableKey, ConfigFileConstants.VariableNameToken, StringComparison.OrdinalIgnoreCase) &&
                                        !String.Equals(variableKey, ConfigFileConstants.VariableValueToken, StringComparison.OrdinalIgnoreCase))
                                    {
                                        PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey,
                                            variableKey, ConfigFileConstants.VariableDefinitions, _path));
                                        ThrowTerminatingError(e.ErrorRecord);
                                    }
                                }
                            }
                        }
                        else
                        {
                            PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray,
                                ConfigFileConstants.VariableDefinitions, filePath));
                            ThrowTerminatingError(e.ErrorRecord);
                        }
                    }
                }

                // Environment variables
                if (_environmentVariables == null)
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment,
                        "@{ Variable1 = 'Value1'; Variable2 = 'Value2' }",
                        streamWriter, true));
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment,
                        SessionConfigurationUtils.CombineHashtable(_environmentVariables, streamWriter), streamWriter, false));
                }

                // Types to process
                resultData = (_typesToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_typesToProcess) : "'C:\\ConfigData\\MyTypes.ps1xml', 'C:\\ConfigData\\OtherTypes.ps1xml'";
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.TypesToProcess, RemotingErrorIdStrings.DISCTypesToProcessComment,
                    resultData, streamWriter, (_typesToProcess.Length == 0)));

                // Formats to process
                resultData = (_formatsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_formatsToProcess) : "'C:\\ConfigData\\MyFormats.ps1xml', 'C:\\ConfigData\\OtherFormats.ps1xml'";
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FormatsToProcess, RemotingErrorIdStrings.DISCFormatsToProcessComment,
                    resultData, streamWriter, (_formatsToProcess.Length == 0)));

                // Assemblies to load
                bool isExample = false;
                if ((_assembliesToLoad == null) || (_assembliesToLoad.Length == 0))
                {
                    isExample = true;
                    _assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" };
                }
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment,
                    SessionConfigurationUtils.CombineStringArray(_assembliesToLoad), streamWriter, isExample));

                result.Append("}");

                streamWriter.Write(result.ToString());
            }
            finally
            {
                streamWriter.Dispose();
            }
        }
        /// <summary>
        /// Processes a module with potential globbing
        /// </summary>
        /// <param name="name">module name with globbing</param>
        private void ProcessModuleWithGlobbing(string name)
        {
            if (String.IsNullOrEmpty(name))
            {
                PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ModuleNameNullOrEmpty));
                WriteError(e.ErrorRecord);
                return;
            }

            foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo(name, null, false))
            {
                ProcessModule(module.Value);
            }
        }
Example #21
0
 private void WriteErrorIfPerfectMatchNotFound(bool hadAMatch, string path, string requestedValueName)
 {
     if (!hadAMatch && !WildcardPattern.ContainsWildcardCharacters(requestedValueName))
     {
         string propertyNotAtPath = RegistryProviderStrings.PropertyNotAtPath;
         Exception exception = new PSArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, propertyNotAtPath, new object[] { requestedValueName, path }), (string)null);
         base.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, requestedValueName));
     }
 }
Example #22
0
 private void ProcessModuleWithGlobbing(string name)
 {
     if (string.IsNullOrEmpty(name))
     {
         PSArgumentException exception = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ModuleNameNullOrEmpty, new object[0]));
         base.WriteError(exception.ErrorRecord);
     }
     else
     {
         foreach (KeyValuePair<string, UpdatableHelpModuleInfo> pair in this.GetModuleInfo(name, false, false))
         {
             this.ProcessModule(pair.Value);
         }
     }
 }
Example #23
0
        protected override void ProcessRecord()
        {
            foreach (String curPath in Path)
            {
                var file = OpenFile(curPath);
                string typename = "";
                if (file.Peek() == '#')
                {
                    var typeline = file.ReadLine();
                    if (typeline.StartsWith("#TYPE"))
                    {
                        typename = typeline.Substring(5).Trim();
                    }
                }

                string[] useHeader;
                if (Header != null && Header.Length > 0)
                {
                    useHeader = Header;
                }
                else
                {
                    // first line is property names
                    useHeader = ParseRowValuesFromStream(file).ToArray();
                    if (useHeader.Length < 1 || file.EndOfStream) // empty file
                    {
                        file.Close();
                        return;
                    }
                }

                // validate header
                if (useHeader.Distinct().Count() != useHeader.Count() ||
                    useHeader.Contains("") ||
                    useHeader.Contains(null)
                    )
                {
                    file.Close();
                    var er = new PSArgumentException("Invalid CSV header with duplicate or empty values!").ErrorRecord;
                    ThrowTerminatingError(er);
                }

                while (!file.EndOfStream)
                {
                    var values = ParseRowValuesFromStream(file);
                    if (values.Count < 1)
                    {
                        continue;
                    }
                    PSObject obj = new PSObject();
                    if (!String.IsNullOrEmpty(typename))
                    {
                        obj.TypeNames.Add("CSV:" + typename);
                    }
                    for (int i = 0; i < useHeader.Length; i++)
                    {
                        string value = (i < values.Count) ? values[i] : null;
                        var psprop = new PSNoteProperty(useHeader[i], value);
                        obj.Properties.Add(psprop);
                        obj.Members.Add(psprop);
                    }
                    WriteObject(obj);
                }
                file.Close();
            }
        }
Example #24
0
 internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture)
 {
     Collection<string> collection = new Collection<string>();
     foreach (string str in this._path)
     {
         UpdatableHelpSystemDrive drive = null;
         using (drive)
         {
             if (string.IsNullOrEmpty(str))
             {
                 PSArgumentException exception = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.PathNullOrEmpty, new object[0]));
                 base.WriteError(exception.ErrorRecord);
                 return false;
             }
             string path = str;
             if (base._credential != null)
             {
                 if (str.Contains("*"))
                 {
                     int index = str.IndexOf("*", StringComparison.OrdinalIgnoreCase);
                     if (index == 0)
                     {
                         throw new UpdatableHelpSystemException("PathMustBeValidContainers", StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, str), ErrorCategory.InvalidArgument, null, new ItemNotFoundException());
                     }
                     int length = index;
                     while (length >= 0)
                     {
                         char ch = str[length];
                         if (ch.Equals('/'))
                         {
                             break;
                         }
                         char ch2 = str[length];
                         if (ch2.Equals('\\'))
                         {
                             break;
                         }
                         length--;
                     }
                     if (length == 0)
                     {
                         throw new UpdatableHelpSystemException("PathMustBeValidContainers", StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, str), ErrorCategory.InvalidArgument, null, new ItemNotFoundException());
                     }
                     drive = new UpdatableHelpSystemDrive(this, str.Substring(0, length), base._credential);
                     path = Path.Combine(drive.DriveName, str.Substring(length + 1, str.Length - (length + 1)));
                 }
                 else
                 {
                     drive = new UpdatableHelpSystemDrive(this, str, base._credential);
                     path = drive.DriveName;
                 }
             }
             if (this.isLiteralPath)
             {
                 string unresolvedProviderPathFromPSPath = base.GetUnresolvedProviderPathFromPSPath(path);
                 if (!Directory.Exists(unresolvedProviderPathFromPSPath))
                 {
                     throw new UpdatableHelpSystemException("PathMustBeValidContainers", StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, str), ErrorCategory.InvalidArgument, null, new ItemNotFoundException());
                 }
                 collection.Add(unresolvedProviderPathFromPSPath);
             }
             else
             {
                 try
                 {
                     foreach (string str4 in base.ResolvePath(path, false, false))
                     {
                         collection.Add(str4);
                     }
                 }
                 catch (ItemNotFoundException exception2)
                 {
                     throw new UpdatableHelpSystemException("PathMustBeValidContainers", StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, str), ErrorCategory.InvalidArgument, null, exception2);
                 }
             }
         }
     }
     if (collection.Count == 0)
     {
         return true;
     }
     bool flag = false;
     foreach (string str5 in collection)
     {
         UpdatableHelpInfo currentHelpInfo = null;
         UpdatableHelpInfo newHelpInfo = null;
         string xml = UpdatableHelpSystem.LoadStringFromPath(this, base.SessionState.Path.Combine(str5, module.GetHelpInfoName()), base._credential);
         if (xml != null)
         {
             currentHelpInfo = base._helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, null, null, false);
         }
         if (!this.alreadyCheckedOncePerDayPerModule && !base.CheckOncePerDayPerModule(module.ModuleName, str5, module.GetHelpInfoName(), DateTime.UtcNow, base._force))
         {
             return true;
         }
         this.alreadyCheckedOncePerDayPerModule = true;
         string str8 = base._helpSystem.GetHelpInfoUri(module, null).ResolvedUri + module.GetHelpInfoName();
         newHelpInfo = base._helpSystem.GetHelpInfo(base._commandType, str8, module.ModuleName, module.ModuleGuid, culture);
         if (newHelpInfo == null)
         {
             throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, null, null);
         }
         foreach (UpdatableHelpUri uri in newHelpInfo.HelpContentUriCollection)
         {
             if (!base.IsUpdateNecessary(module, currentHelpInfo, newHelpInfo, uri.Culture, base._force))
             {
                 base.WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, new object[] { module.ModuleName, HelpDisplayStrings.NewestContentAlreadyDownloaded, uri.Culture.Name, newHelpInfo.GetCultureVersion(uri.Culture) }));
                 flag = true;
             }
             else
             {
                 string resolvedUri = uri.ResolvedUri;
                 string helpContentName = module.GetHelpContentName(uri.Culture);
                 string str11 = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetTempFileName()));
                 UpdatableHelpSystemDrive drive2 = null;
                 using (drive2)
                 {
                     try
                     {
                         if (Directory.Exists(resolvedUri))
                         {
                             File.Copy(base.SessionState.Path.Combine(resolvedUri, helpContentName), base.SessionState.Path.Combine(str5, helpContentName), true);
                         }
                         else
                         {
                             if (base._credential != null)
                             {
                                 try
                                 {
                                     drive2 = new UpdatableHelpSystemDrive(this, str5, base._credential);
                                     if (!base._helpSystem.DownloadHelpContent(base._commandType, str11, resolvedUri, helpContentName, culture))
                                     {
                                         flag = false;
                                         goto Label_0641;
                                     }
                                     base.InvokeProvider.Item.Copy(new string[] { str11 }, drive2.DriveName, true, CopyContainers.CopyChildrenOfTargetContainer, true, true);
                                     goto Label_04C2;
                                 }
                                 catch (Exception exception3)
                                 {
                                     CommandProcessorBase.CheckForSevereException(exception3);
                                     base.ProcessException(module.ModuleName, uri.Culture.Name, exception3);
                                     flag = false;
                                     goto Label_0641;
                                 }
                             }
                             if (!base._helpSystem.DownloadHelpContent(base._commandType, str5, resolvedUri, helpContentName, culture))
                             {
                                 flag = false;
                                 goto Label_0641;
                             }
                         }
                     Label_04C2:
                         if (base._credential != null)
                         {
                             base._helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, uri.Culture.Name, newHelpInfo.GetCultureVersion(uri.Culture), str11, module.GetHelpInfoName(), base._force);
                             base.InvokeProvider.Item.Copy(new string[] { Path.Combine(str11, module.GetHelpInfoName()) }, Path.Combine(drive2.DriveName, module.GetHelpInfoName()), false, CopyContainers.CopyTargetContainer, true, true);
                         }
                         else
                         {
                             base._helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, uri.Culture.Name, newHelpInfo.GetCultureVersion(uri.Culture), str5, module.GetHelpInfoName(), base._force);
                         }
                         base.WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, new object[] { module.ModuleName, StringUtil.Format(HelpDisplayStrings.SavedHelpContent, Path.Combine(str5, helpContentName)), uri.Culture.Name, newHelpInfo.GetCultureVersion(uri.Culture) }));
                         base.LogMessage(StringUtil.Format(HelpDisplayStrings.SaveHelpCompleted, str5));
                     }
                     catch (Exception exception4)
                     {
                         CommandProcessorBase.CheckForSevereException(exception4);
                         base.ProcessException(module.ModuleName, uri.Culture.Name, exception4);
                     }
                 }
             Label_0641:;
             }
         }
         flag = true;
     }
     return flag;
 }
Example #25
0
		internal void ThrowConflictParameterWasSet(string operationName, string parameterName, string conflictParameterName)
		{
			object[] objArray = new object[2];
			objArray[0] = parameterName;
			objArray[1] = conflictParameterName;
			string str = string.Format(CultureInfo.CurrentUICulture, Strings.ConflictParameterWasSet, objArray);
			PSArgumentException pSArgumentException = new PSArgumentException(str, parameterName);
			this.ThrowTerminatingError(pSArgumentException, operationName);
		}
Example #26
0
        /// <summary>
        /// Terminating error.
        /// </summary>
        /// <param name="parameterName"></param>
        /// <param name="description"></param>
        /// <param name="reason"></param>
        /// <param name="pscxPath"></param>
        protected virtual void OnPscxPathError(string parameterName, string description, PscxPathState reason, PscxPathInfo pscxPath)
        {
            string errorMessage = String.Format("{0}'s {1} parameter has an invalid path of '{2}': {3}",
                this.CmdletName, parameterName, pscxPath.SourcePath, description);

            var exception = new PSArgumentException(errorMessage, parameterName);

            this.ThrowTerminatingError(
                new ErrorRecord(exception, reason.ToString(), ErrorCategory.InvalidArgument, parameterName));
        }
Example #27
0
        /// <summary>
        /// Main cmdlet logic
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                // Module and FullyQualifiedModule should not be specified at the same time.
                // Throw out terminating error if this is the case.
                if (Module != null && FullyQualifiedModule != null)
                {
                    string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Module", "FullyQualifiedModule");
                    ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null);
                    ThrowTerminatingError(error);
                }

                if (!_isInitialized)
                {
                    if (_path == null && Recurse.IsPresent)
                    {
                        PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyRecurseWithoutPath));
                        ThrowTerminatingError(e.ErrorRecord);
                    }
                    _isInitialized = true;
                }

                base.Process(_module, FullyQualifiedModule);

                // Reset the per-runspace help cache
                foreach (HelpProvider provider in Context.HelpSystem.HelpProviders)
                {
                    if (_stopping)
                    {
                        break;
                    }

                    provider.Reset();
                }
            }
            finally
            {
                ProgressRecord progress = new ProgressRecord(activityId, HelpDisplayStrings.UpdateProgressActivityForModule, HelpDisplayStrings.UpdateProgressInstalling);

                progress.PercentComplete = 100;
                progress.RecordType = ProgressRecordType.Completed;

                WriteProgress(progress);
            }
        }
Example #28
0
        /// <summary>
        /// Traces the Message and StackTrace properties of the exception
        /// and returns the new exception. This variant uses the default
        /// ArgumentException template text. This is not allowed to call
        /// other Throw*Exception variants, since they call this.
        /// </summary>
        /// <param name="paramName">
        /// The name of the parameter whose argument value was invalid
        /// </param>
        /// <returns>Exception instance ready to throw</returns>
        internal static PSArgumentException NewArgumentException(string paramName)
        {
            if (String.IsNullOrEmpty(paramName))
            {
                throw new ArgumentNullException("paramName");
            }
            string message = StringUtil.Format(AutomationExceptions.Argument, paramName);
            // Note that the message param comes first
            var e = new PSArgumentException(message, paramName);

            return e;
        }
        protected override void ProcessRecord()
        {
            try
            {
                /* Retrieve domain SID of the current user. */
                SecurityIdentifier domainSid;
                // TODO: Domain name to SID translation Cache
                // TODO: Get default domain from server
                switch(this.ParameterSetName)
                {
                    case ParameterSetByLogonName:
                        // TODO: Extract as resource:
                        this.WriteVerbose(string.Format("Setting password hash on account {0}\\{1}.", this.Domain, this.SamAccountName));
                        
                        if (this.Domain.Contains("."))
                        {
                            // This is not a hard check, because dots are actually allowed in NetBIOS names, although not recommended.
                            // TODO: Extract as a resource
                            this.WriteWarning("The domain name supplied appears to be a DNS name instead of NetBIOS name.");
                        }

                        // We need to translate domain name to SID:
                        domainSid = this.SamServer.LookupDomain(this.Domain);
                        break;
                    case ParameterSetBySid:
                        if (!this.Sid.IsAccountSid())
                        {
                            // Allow the processing to continue on this error:
                            // TODO: Extract as resource:
                            PSArgumentException ex = new PSArgumentException("The SID provided is not a account SID.", "Sid");
                            this.WriteError(ex.ErrorRecord);
                        }
                        // TODO: Extract as resource:
                        this.WriteVerbose(string.Format("Setting password hash on account {0}.", this.Sid));
                        // We already know the SID:
                        domainSid = this.Sid.AccountDomainSid;
                        break;
                    default:
                        // This should never happen:
                        throw new PSInvalidOperationException(Resources.InvalidParameterSetMessage);
                }
                /* Connect to the domain. */
                using (SamDomain domain = this.SamServer.OpenDomain(domainSid, SamDomainAccessMask.Lookup))
                {
                    /* Retrieve RID of the current user. */
                    int userId = (this.ParameterSetName == ParameterSetBySid) ? this.Sid.GetRid() : domain.LookupUser(this.SamAccountName);
                    /* Open the user account and reset password: */
                    using (SamUser user = domain.OpenUser(userId, SamUserAccessMask.ForcePasswordChange))
                    {
                        user.SetPasswordHash(this.NTHash, this.LMHash);
                    }
                }
            }
            catch (Win32Exception ex)
            {
                ErrorCategory category = ((Win32ErrorCode)ex.NativeErrorCode).ToPSCategory();
                object identity = (this.Sid != null) ? this.Sid.ToString() : this.SamAccountName;
                ErrorRecord error = new ErrorRecord(ex, "WinAPIErrorProcess", category, identity);
                // Allow the processing to continue on this error:
                this.WriteError(error);
            }
        }
 internal void Copy(string[] path, string destinationPath, bool recurse, CopyContainers copyContainers, ProviderRuntime runtime)
 {
     ProviderInfo destinationProvider;
     var destRuntime = new ProviderRuntime(runtime);
     var destination = Globber.GetProviderSpecificPath(destinationPath, destRuntime, out destinationProvider);
     // make sure we don't use the version of IsContainer that globs, or we will have unnecessary provider callbacks
     var destProvider = destinationProvider.CreateInstance() as ContainerCmdletProvider; // it's okay to be null
     var destIsContainer = IsContainer(destProvider, destination, destRuntime);
     GlobAndInvoke<ContainerCmdletProvider>(path, runtime,
         (curPath, provider) => {
             if (!runtime.PSDriveInfo.Provider.Equals(destinationProvider))
             {
                 var msg = "The source cannot be copied to the destination, because they're not from the same provider";
                 var error = new PSArgumentException(msg, "CopyItemSourceAndDestinationNotSameProvider",
                     ErrorCategory.InvalidArgument);
                 runtime.WriteError(error.ErrorRecord);
                 return;
             }
             // Affected by #trailingSeparatorAmbiguity
             // PS would make sure the trailing slash of curPath is removed
             // check if src is a container
             if (IsContainer(provider, curPath, runtime))
             {
                 // if we copy a container to another, invoke a special method for this
                 if (destIsContainer)
                 {
                     CopyContainerToContainer(provider, curPath, destination, recurse, copyContainers, runtime);
                     return;
                 }
                 // otherwise the destination doesn't exist or is a leaf. Copying a container to a leaf doesn't work
                 if (Exists(destination, destRuntime))
                 {
                     var error = new PSArgumentException("Cannot copy container to existing leaf", 
                         "CopyContainerItemToLeafError", ErrorCategory.InvalidArgument).ErrorRecord;
                     runtime.WriteError(error);
                     return;
                 }
                 // otherwise we just proceed as normal
             }
             // either leaf to leaf, leaf to container, or container to not-existing (i.e. copy the container)
             provider.CopyItem(curPath, destination, recurse, runtime);
         }
     );
 }
Example #31
0
        /// <summary>
        /// Process a single module with a given culture
        /// </summary>
        /// <param name="module">module to process</param>
        /// <param name="culture">culture to use</param>
        /// <returns>true if the module has been processed, false if not</returns>
        internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture)
        {
            Collection<string> resolvedPaths = new Collection<string>();

            // Search for the HelpInfo XML
            foreach (string path in _path)
            {
                UpdatableHelpSystemDrive helpInfoDrive = null;

                try
                {
                    if (String.IsNullOrEmpty(path))
                    {
                        PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.PathNullOrEmpty));
                        WriteError(e.ErrorRecord);
                        return false;
                    }

                    string destPath = path;

                    if (_credential != null)
                    {
                        if (path.Contains("*"))
                        {
                            // Deal with wildcards

                            int index = path.IndexOf("*", StringComparison.OrdinalIgnoreCase);

                            if (index == 0)
                            {
                                throw new UpdatableHelpSystemException("PathMustBeValidContainers",
                                    StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument,
                                    null, new ItemNotFoundException());
                            }
                            else
                            {
                                int i = index;
                                for (; i >= 0; i--)
                                {
                                    if (path[i].Equals('/') || path[i].Equals('\\'))
                                    {
                                        break;
                                    }
                                }

                                if (i == 0)
                                {
                                    throw new UpdatableHelpSystemException("PathMustBeValidContainers",
                                        StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument,
                                        null, new ItemNotFoundException());
                                }

                                helpInfoDrive = new UpdatableHelpSystemDrive(this, path.Substring(0, i), _credential);
                                destPath = Path.Combine(helpInfoDrive.DriveName, path.Substring(i + 1, path.Length - (i + 1)));
                            }
                        }
                        else
                        {
                            helpInfoDrive = new UpdatableHelpSystemDrive(this, path, _credential);
                            destPath = helpInfoDrive.DriveName;
                        }
                    }

                    if (_isLiteralPath)
                    {
                        string destinationPath = GetUnresolvedProviderPathFromPSPath(destPath);
                        if (!Directory.Exists(destinationPath))
                        {
                            throw new UpdatableHelpSystemException("PathMustBeValidContainers",
                                StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument,
                                null, new ItemNotFoundException());
                        }

                        resolvedPaths.Add(destinationPath);
                    }
                    else
                    {
                        try
                        {
                            // Expand wildcard characters
                            foreach (string tempPath in ResolvePath(destPath, false, false))
                            {
                                resolvedPaths.Add(tempPath);
                            }
                        }
                        catch (ItemNotFoundException e)
                        {
                            throw new UpdatableHelpSystemException("PathMustBeValidContainers",
                                StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument, null, e);
                        }
                    }
                }
                finally
                {
                    if (helpInfoDrive != null)
                    {
                        helpInfoDrive.Dispose();
                    }
                }
            }

            if (resolvedPaths.Count == 0)
            {
                return true;
            }


            bool installed = false;

            foreach (string path in resolvedPaths)
            {
                UpdatableHelpInfo currentHelpInfo = null;
                UpdatableHelpInfo newHelpInfo = null;
                string helpInfoUri = null;

                // if -force is specified, no need to read from the current HelpInfo.xml file
                // because it won't be used for checking "IsUpdateNecessary"
                string xml = _force
                                 ? null
                                 : UpdatableHelpSystem.LoadStringFromPath(this,
                                                                          SessionState.Path.Combine(path, module.GetHelpInfoName()),
                                                                          _credential);

                if (xml != null)
                {
                    // constructing the helpinfo object from previous update help log xml..
                    // no need to resolve the uri's in this case.
                    currentHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid,
                                                                 currentCulture: null, pathOverride: null, verbose: false,
                                                                 shouldResolveUri: false, ignoreValidationException: false);
                }

                // Don't update too frequently
                if (!_alreadyCheckedOncePerDayPerModule && !CheckOncePerDayPerModule(module.ModuleName, path, module.GetHelpInfoName(), DateTime.UtcNow, _force))
                {
                    return true;
                }

                _alreadyCheckedOncePerDayPerModule = true;

                // Form the actual HelpInfo.xml uri
                helpInfoUri = _helpSystem.GetHelpInfoUri(module, null).ResolvedUri;
                string uri = helpInfoUri + module.GetHelpInfoName();

                newHelpInfo = _helpSystem.GetHelpInfo(_commandType, uri, module.ModuleName, module.ModuleGuid, culture);

                if (newHelpInfo == null)
                {
                    throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml",
                        StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable,
                        null, null);
                }

                string tempPath = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetTempFileName()));
                foreach (UpdatableHelpUri contentUri in newHelpInfo.HelpContentUriCollection)
                {
                    if (!IsUpdateNecessary(module, currentHelpInfo, newHelpInfo, contentUri.Culture, _force))
                    {
                        WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, module.ModuleName, HelpDisplayStrings.NewestContentAlreadyDownloaded,
                            contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture)));

                        installed = true;
                        continue;
                    }
                    else
                    {
                        Debug.Assert(helpInfoUri != null, "If we are here, helpInfoUri must not be null");

                        string helpContentUri = contentUri.ResolvedUri;
                        string helpContentName = module.GetHelpContentName(contentUri.Culture);

                        UpdatableHelpSystemDrive helpContentDrive = null;

                        try
                        {
                            if (Directory.Exists(helpContentUri))
                            {
                                File.Copy(SessionState.Path.Combine(helpContentUri, helpContentName),
                                    SessionState.Path.Combine(path, helpContentName), true);
                            }
                            else
                            {
                                // Remote

                                if (_credential != null)
                                {
                                    try
                                    {
                                        helpContentDrive = new UpdatableHelpSystemDrive(this, path, _credential);

                                        if (!_helpSystem.DownloadHelpContent(_commandType, tempPath, helpContentUri, helpContentName, culture))
                                        {
                                            installed = false;
                                            continue;
                                        }

                                        InvokeProvider.Item.Copy(new string[1] { tempPath }, helpContentDrive.DriveName, true, CopyContainers.CopyChildrenOfTargetContainer,
                                            true, true);
                                    }
                                    catch (Exception e)
                                    {
                                        CommandProcessorBase.CheckForSevereException(e);

                                        ProcessException(module.ModuleName, contentUri.Culture.Name, e);
                                        installed = false;
                                        continue;
                                    }
                                }
                                else
                                {
                                    if (!_helpSystem.DownloadHelpContent(_commandType, path, helpContentUri, helpContentName, culture))
                                    {
                                        installed = false;
                                        continue;
                                    }
                                }
                            }

                            if (_credential != null)
                            {
                                _helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture), tempPath,
                                    module.GetHelpInfoName(), _force);

                                InvokeProvider.Item.Copy(new string[1] { Path.Combine(tempPath, module.GetHelpInfoName()) }, Path.Combine(helpContentDrive.DriveName, module.GetHelpInfoName()), false,
                                    CopyContainers.CopyTargetContainer, true, true);
                            }
                            else
                            {
                                _helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture), path,
                                    module.GetHelpInfoName(), _force);
                            }

                            WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, module.ModuleName,
                                StringUtil.Format(HelpDisplayStrings.SavedHelpContent, System.IO.Path.Combine(path, helpContentName)), contentUri.Culture.Name,
                                newHelpInfo.GetCultureVersion(contentUri.Culture)));

                            LogMessage(StringUtil.Format(HelpDisplayStrings.SaveHelpCompleted, path));
                        }
                        catch (Exception e)
                        {
                            CommandProcessorBase.CheckForSevereException(e);

                            ProcessException(module.ModuleName, contentUri.Culture.Name, e);
                        }
                        finally
                        {
                            if (helpContentDrive != null)
                            {
                                helpContentDrive.Dispose();
                            }
                        }
                    }
                }

                installed = true;
            }

            return installed;
        }
 void CopyContainerToContainer(ContainerCmdletProvider provider, string srcPath, string destPath, bool recurse,
                               CopyContainers copyContainers, ProviderRuntime runtime)
 {
     // the "usual" case: if we don't use recursion (empty container is copied) or we want to maintain the
     // original hierarchy
     if (!recurse || copyContainers.Equals(CopyContainers.CopyTargetContainer))
     {
         provider.CopyItem(srcPath, destPath, recurse, runtime);
         return;
     }
     // Otherwise we want a flat-hierachy copy of a folder (because copyContainers is CopyChildrenOfTargetContainer)
     // Make sure recurse is set
     if (!recurse)
     {
         var error = new PSArgumentException("Cannot copy container to existing leaf",
             "CopyContainerItemToLeafError", ErrorCategory.InvalidArgument).ErrorRecord;
         runtime.WriteError(error);
         return;
     }
     // otherwise do the flat copy. To do this: get all child names (recursively) and invoke copying without recursion
     var childNames = ChildItem.GetNames(srcPath, ReturnContainers.ReturnMatchingContainers, true);
     foreach (var child in childNames)
     {
         var childPath = Path.Combine(provider, srcPath, child, runtime);
         provider.CopyItem(childPath, destPath, false, runtime);
     }
 }
Example #33
0
        private void WriteErrorIfPerfectMatchNotFound(bool hadAMatch, string path, string requestedValueName)
        {
            if (!hadAMatch && !WildcardPattern.ContainsWildcardCharacters(requestedValueName))
            {
                // we did not have any match and the requested name did not have
                // any globbing characters (perfect match attempted)
                // we need to write an error

                string formatString = RegistryProviderStrings.PropertyNotAtPath;
                Exception e =
                    new PSArgumentException(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            formatString,
                            requestedValueName,
                            path),
                        (Exception)null);
                WriteError(new ErrorRecord(
                    e,
                    e.GetType().FullName,
                    ErrorCategory.InvalidArgument,
                    requestedValueName));
            }
        }
Example #34
0
        /// <summary>
        /// BeginProcessing
        /// </summary>
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            // Verify parameter set
            bool haveProtocolParam = this.MyInvocation.BoundParameters.ContainsKey("Protocol");
            bool haveWsmanAuthenticationParam = this.MyInvocation.BoundParameters.ContainsKey("WsmanAuthentication");
            bool haveDcomAuthenticationParam = this.MyInvocation.BoundParameters.ContainsKey("DcomAuthentication");
            bool haveDcomImpersonation = this.MyInvocation.BoundParameters.ContainsKey("Impersonation");
            _transportProtocol = (this.Protocol.Equals(ComputerWMIHelper.WsmanProtocol, StringComparison.OrdinalIgnoreCase) || (haveWsmanAuthenticationParam && !haveProtocolParam)) ?
                                 TransportProtocol.WSMan : TransportProtocol.DCOM;

            if (haveWsmanAuthenticationParam && (haveDcomAuthenticationParam || haveDcomImpersonation))
            {
                string errMsg = StringUtil.Format(ComputerResources.StopCommandParamWSManAuthConflict, ComputerResources.StopCommandParamMessage);
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSArgumentException(errMsg),
                        "InvalidParameter",
                        ErrorCategory.InvalidArgument,
                        this));
            }

            if ((_transportProtocol == TransportProtocol.DCOM) && haveWsmanAuthenticationParam)
            {
                string errMsg = StringUtil.Format(ComputerResources.StopCommandWSManAuthProtcolConflict, ComputerResources.StopCommandParamMessage);
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSArgumentException(errMsg),
                        "InvalidParameter",
                        ErrorCategory.InvalidArgument,
                        this));
            }

            if ((_transportProtocol == TransportProtocol.WSMan) && (haveDcomAuthenticationParam || haveDcomImpersonation))
            {
                string errMsg = StringUtil.Format(ComputerResources.StopCommandAuthProtcolConflict, ComputerResources.StopCommandParamMessage);
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSArgumentException(errMsg),
                        "InvalidParameter",
                        ErrorCategory.InvalidArgument,
                        this));
            }

#if CORECLR
            if (this.MyInvocation.BoundParameters.ContainsKey("DcomAuthentication"))
            {
                string errMsg = StringUtil.Format(ComputerResources.InvalidParameterForCoreClr, "DcomAuthentication");
                PSArgumentException ex = new PSArgumentException(errMsg, ComputerResources.InvalidParameterForCoreClr);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForCoreClr", ErrorCategory.InvalidArgument, null));
            }

            if (this.MyInvocation.BoundParameters.ContainsKey("Impersonation"))
            {
                string errMsg = StringUtil.Format(ComputerResources.InvalidParameterForCoreClr, "Impersonation");
                PSArgumentException ex = new PSArgumentException(errMsg, ComputerResources.InvalidParameterForCoreClr);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForCoreClr", ErrorCategory.InvalidArgument, null));
            }

            if(this.Protocol.Equals(ComputerWMIHelper.DcomProtocol , StringComparison.OrdinalIgnoreCase))
            {
                InvalidOperationException ex = new InvalidOperationException(ComputerResources.InvalidParameterDCOMNotSupported);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterDCOMNotSupported", ErrorCategory.InvalidOperation, null));
            }
#endif
        }
 private string CombineHashTableOrStringArray(object[] values, StreamWriter writer)
 {
     StringBuilder builder = new StringBuilder();
     for (int i = 0; i < values.Length; i++)
     {
         string str = values[i] as string;
         if (!string.IsNullOrEmpty(str))
         {
             builder.Append(QuoteName(str));
         }
         else
         {
             Hashtable table = values[i] as Hashtable;
             if (table == null)
             {
                 PSArgumentException exception = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileContants.ModulesToImport));
                 base.ThrowTerminatingError(exception.ErrorRecord);
             }
             builder.Append(this.CombineHashtable(table, writer));
         }
         if (i < (values.Length - 1))
         {
             builder.Append(", ");
         }
     }
     return builder.ToString();
 }
Example #36
0
        /// <summary>
        /// Process a single module with a given culture
        /// </summary>
        /// <param name="module">module to process</param>
        /// <param name="culture">culture to use</param>
        /// <returns>true if the module has been processed, false if not</returns>
        internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture)
        {
            UpdatableHelpInfo currentHelpInfo = null;
            UpdatableHelpInfo newHelpInfo = null;
            string helpInfoUri = null;

            // reading the xml file even if force is specified
            // Reason: we need the current version for ShouldProcess
            string xml = UpdatableHelpSystem.LoadStringFromPath(this,
                 SessionState.Path.Combine(module.ModuleBase, module.GetHelpInfoName()),
                 null);

            if (xml != null)
            {
                // constructing the helpinfo object from previous update help log xml..
                // no need to resolve the uri's in this case.
                currentHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid,
                                                             currentCulture: null, pathOverride: null, verbose: false,
                                                             shouldResolveUri: false,
                                                             // ignore validation exception if _force is true
                                                             ignoreValidationException: _force);
            }

            // Don't update too frequently
            if (!_alreadyCheckedOncePerDayPerModule && !CheckOncePerDayPerModule(module.ModuleName, module.ModuleBase, module.GetHelpInfoName(), DateTime.UtcNow, _force))
            {
                return true;
            }

            _alreadyCheckedOncePerDayPerModule = true;

            if (_path != null)
            {
                UpdatableHelpSystemDrive helpInfoDrive = null;
                try
                {
                    Collection<string> resolvedPaths = new Collection<string>();

                    // Search for the HelpInfo XML
                    foreach (string path in _path)
                    {
                        if (String.IsNullOrEmpty(path))
                        {
                            PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.PathNullOrEmpty));
                            WriteError(e.ErrorRecord);
                            return false;
                        }

                        try
                        {
                            string sourcePath = path;

                            if (_credential != null)
                            {
                                UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(this, path, _credential);
                                sourcePath = drive.DriveName;
                            }

                            // Expand wildcard characters
                            foreach (string tempPath in ResolvePath(sourcePath, _recurse, _isLiteralPath))
                            {
                                resolvedPaths.Add(tempPath);
                            }
                        }
                        catch (System.Management.Automation.DriveNotFoundException e)
                        {
                            ThrowPathMustBeValidContainersException(path, e);
                        }
                        catch (ItemNotFoundException e)
                        {
                            ThrowPathMustBeValidContainersException(path, e);
                        }
                    }

                    if (resolvedPaths.Count == 0)
                    {
                        return true;
                    }

                    // Everything in resolvedPaths is a container
                    foreach (string resolvedPath in resolvedPaths)
                    {
                        string literalPath = SessionState.Path.Combine(resolvedPath, module.GetHelpInfoName());

                        xml = UpdatableHelpSystem.LoadStringFromPath(this, literalPath, _credential);

                        if (xml != null)
                        {
                            newHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, culture, resolvedPath,
                                                                     verbose: false, shouldResolveUri: true, ignoreValidationException: false);
                            helpInfoUri = resolvedPath;
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    CommandProcessorBase.CheckForSevereException(e);

                    throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml",
                        StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable,
                        null, e);
                }
                finally
                {
                    if (helpInfoDrive != null)
                    {
                        helpInfoDrive.Dispose();
                    }
                }
            }
            else
            {
                // Form the actual HelpInfo.xml uri
                helpInfoUri = _helpSystem.GetHelpInfoUri(module, null).ResolvedUri;
                string uri = helpInfoUri + module.GetHelpInfoName();

                newHelpInfo = _helpSystem.GetHelpInfo(UpdatableHelpCommandType.UpdateHelpCommand, uri, module.ModuleName, module.ModuleGuid, culture);
            }

            if (newHelpInfo == null)
            {
                throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml",
                    StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable,
                    null, null);
            }

            bool installed = false;

            foreach (UpdatableHelpUri contentUri in newHelpInfo.HelpContentUriCollection)
            {
                Version currentHelpVersion = (currentHelpInfo != null) ? currentHelpInfo.GetCultureVersion(contentUri.Culture) : null;
                string updateHelpShouldProcessAction = string.Format(CultureInfo.InvariantCulture,
                    HelpDisplayStrings.UpdateHelpShouldProcessActionMessage,
                    module.ModuleName,
                    (currentHelpVersion != null) ? currentHelpVersion.ToString() : "0.0.0.0",
                    newHelpInfo.GetCultureVersion(contentUri.Culture),
                    contentUri.Culture);
                if (!this.ShouldProcess(updateHelpShouldProcessAction, "Update-Help"))
                {
                    continue;
                }

                if (Utils.IsUnderProductFolder(module.ModuleBase) && (!Utils.IsAdministrator()))
                {
                    string message = StringUtil.Format(HelpErrors.UpdatableHelpRequiresElevation);
                    ProcessException(module.ModuleName, null, new UpdatableHelpSystemException("UpdatableHelpSystemRequiresElevation",
                            message, ErrorCategory.InvalidOperation, null, null));
                    return false;
                }

                if (!IsUpdateNecessary(module, _force ? null : currentHelpInfo, newHelpInfo, contentUri.Culture, _force))
                {
                    WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, module.ModuleName, HelpDisplayStrings.NewestContentAlreadyInstalled,
                        contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture)));

                    installed = true;
                    continue;
                }
                else
                {
                    try
                    {
                        Debug.Assert(helpInfoUri != null, "If we are here, helpInfoUri must not be null");

                        string helpContentUri = contentUri.ResolvedUri;
                        string xsdPath = SessionState.Path.Combine(Utils.GetApplicationBase(Context.ShellID), "Schemas\\PSMaml\\maml.xsd"); // TODO: Edit the maml XSDs and change this

                        // Gather destination paths
                        Collection<string> destPaths = new Collection<string>();

                        destPaths.Add(module.ModuleBase);

#if !CORECLR // Side-By-Side directories are not present in OneCore environments.
                        if (IsSystemModule(module.ModuleName) && ClrFacade.Is64BitOperatingSystem())
                        {
                            string path = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID).Replace("System32", "SysWOW64");

                            destPaths.Add(path);
                        }
#endif

                        Collection<string> filesInstalled;

                        if (Directory.Exists(helpContentUri))
                        {
                            if (_credential != null)
                            {
                                string helpContentName = module.GetHelpContentName(contentUri.Culture);
                                string tempContentPath = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));

                                try
                                {
                                    using (UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(this, helpContentUri, _credential))
                                    {
                                        if (!Directory.Exists(tempContentPath))
                                        {
                                            Directory.CreateDirectory(tempContentPath);
                                        }

                                        InvokeProvider.Item.Copy(new string[1] { Path.Combine(drive.DriveName, helpContentName) },
                                            Path.Combine(tempContentPath, helpContentName), false, CopyContainers.CopyTargetContainer, true, true);

                                        // Local
                                        _helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, tempContentPath,
                                            destPaths, module.GetHelpContentName(contentUri.Culture),
                                            Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())),
                                            contentUri.Culture, xsdPath, out filesInstalled);
                                    }
                                }
                                catch (Exception e)
                                {
                                    CommandProcessorBase.CheckForSevereException(e);

                                    throw new UpdatableHelpSystemException("HelpContentNotFound", StringUtil.Format(HelpDisplayStrings.HelpContentNotFound),
                                        ErrorCategory.ResourceUnavailable, null, e);
                                }
                            }
                            else
                            {
                                _helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, helpContentUri,
                                    destPaths, module.GetHelpContentName(contentUri.Culture),
                                    Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())),
                                    contentUri.Culture, xsdPath, out filesInstalled);
                            }
                        }
                        else
                        {
                            // Remote

                            // Download and install help content
                            if (!_helpSystem.DownloadAndInstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context,
                                destPaths, module.GetHelpContentName(contentUri.Culture), contentUri.Culture, helpContentUri, xsdPath, out filesInstalled))
                            {
                                installed = false;
                                continue;
                            }
                        }

                        _helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture),
                            module.ModuleBase, module.GetHelpInfoName(), _force);

                        foreach (string fileInstalled in filesInstalled)
                        {
                            WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, module.ModuleName,
                                StringUtil.Format(HelpDisplayStrings.UpdatedHelpContent, fileInstalled), contentUri.Culture.Name,
                                newHelpInfo.GetCultureVersion(contentUri.Culture)));
                        }

                        LogMessage(StringUtil.Format(HelpDisplayStrings.UpdateHelpCompleted));

                        installed = true;
                    }
                    catch (Exception e)
                    {
                        CommandProcessorBase.CheckForSevereException(e);

                        ProcessException(module.ModuleName, contentUri.Culture.Name, e);
                    }
                }
            }

            return installed;
        }
Example #37
0
 internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture)
 {
     if (((InitialSessionState.IsEngineModule(module.ModuleName) || InitialSessionState.IsNestedEngineModule(module.ModuleName)) || module.ModuleName.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase)) && !UpdatableHelpSystem.IsAdministrator())
     {
         string message = StringUtil.Format(HelpErrors.UpdatableHelpRequiresElevation, new object[0]);
         base.ProcessException(module.ModuleName, null, new UpdatableHelpSystemException("UpdatableHelpSystemRequiresElevation", message, ErrorCategory.InvalidOperation, null, null));
         return false;
     }
     UpdatableHelpInfo currentHelpInfo = null;
     UpdatableHelpInfo newHelpInfo = null;
     string str2 = null;
     string xml = UpdatableHelpSystem.LoadStringFromPath(this, base.SessionState.Path.Combine(module.ModuleBase, module.GetHelpInfoName()), null);
     if (xml != null)
     {
         currentHelpInfo = base._helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, null, null, false);
     }
     if (!this.alreadyCheckedOncePerDayPerModule && !base.CheckOncePerDayPerModule(module.ModuleName, module.ModuleBase, module.GetHelpInfoName(), DateTime.UtcNow, base._force))
     {
         return true;
     }
     this.alreadyCheckedOncePerDayPerModule = true;
     if (this._path != null)
     {
         //using (null)
         {
             try
             {
                 Collection<string> collection = new Collection<string>();
                 foreach (string str4 in this._path)
                 {
                     if (string.IsNullOrEmpty(str4))
                     {
                         PSArgumentException exception = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.PathNullOrEmpty, new object[0]));
                         base.WriteError(exception.ErrorRecord);
                         return false;
                     }
                     try
                     {
                         string path = str4;
                         if (base._credential != null)
                         {
                             UpdatableHelpSystemDrive drive2 = new UpdatableHelpSystemDrive(this, str4, base._credential);
                             path = drive2.DriveName;
                         }
                         foreach (string str6 in base.ResolvePath(path, this._recurse, this.isLiteralPath))
                         {
                             collection.Add(str6);
                         }
                     }
                     catch (System.Management.Automation.DriveNotFoundException exception2)
                     {
                         this.ThrowPathMustBeValidContainersException(str4, exception2);
                     }
                     catch (ItemNotFoundException exception3)
                     {
                         this.ThrowPathMustBeValidContainersException(str4, exception3);
                     }
                 }
                 if (collection.Count == 0)
                 {
                     return true;
                 }
                 foreach (string str7 in collection)
                 {
                     string str8 = base.SessionState.Path.Combine(str7, module.GetHelpInfoName());
                     xml = UpdatableHelpSystem.LoadStringFromPath(this, str8, base._credential);
                     if (xml != null)
                     {
                         newHelpInfo = base._helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, culture, str7, false);
                         str2 = str7;
                         goto Label_02DD;
                     }
                 }
             }
             catch (Exception exception4)
             {
                 CommandProcessorBase.CheckForSevereException(exception4);
                 throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, null, exception4);
             }
             goto Label_02DD;
         }
     }
     string str9 = base._helpSystem.GetHelpInfoUri(module, null).ResolvedUri + module.GetHelpInfoName();
     newHelpInfo = base._helpSystem.GetHelpInfo(UpdatableHelpCommandType.UpdateHelpCommand, str9, module.ModuleName, module.ModuleGuid, culture);
 Label_02DD:
     if (newHelpInfo == null)
     {
         throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, null, null);
     }
     bool flag = false;
     foreach (UpdatableHelpUri uri in newHelpInfo.HelpContentUriCollection)
     {
         if (!base.IsUpdateNecessary(module, currentHelpInfo, newHelpInfo, uri.Culture, base._force))
         {
             base.WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, new object[] { module.ModuleName, HelpDisplayStrings.NewestContentAlreadyInstalled, uri.Culture.Name, newHelpInfo.GetCultureVersion(uri.Culture) }));
             flag = true;
         }
         else
         {
             try
             {
                 Collection<string> collection3;
                 string resolvedUri = uri.ResolvedUri;
                 string xsdPath = base.SessionState.Path.Combine(Utils.GetApplicationBase(base.Context.ShellID), @"Schemas\PSMaml\maml.xsd");
                 Collection<string> destPaths = new Collection<string> {
                     module.ModuleBase
                 };
                 if (UpdatableHelpCommandBase.IsSystemModule(module.ModuleName) && Environment.Is64BitOperatingSystem)
                 {
                     string item = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID).Replace("System32", "SysWOW64");
                     destPaths.Add(item);
                 }
                 if (Directory.Exists(resolvedUri))
                 {
                     if (base._credential != null)
                     {
                         string helpContentName = module.GetHelpContentName(uri.Culture);
                         string str14 = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
                         try
                         {
                             using (UpdatableHelpSystemDrive drive3 = new UpdatableHelpSystemDrive(this, resolvedUri, base._credential))
                             {
                                 if (!Directory.Exists(str14))
                                 {
                                     Directory.CreateDirectory(str14);
                                 }
                                 base.InvokeProvider.Item.Copy(new string[] { Path.Combine(drive3.DriveName, helpContentName) }, Path.Combine(str14, helpContentName), false, CopyContainers.CopyTargetContainer, true, true);
                                 base._helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, base.Context, str14, destPaths, module.GetHelpContentName(uri.Culture), Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())), uri.Culture, xsdPath, out collection3);
                             }
                             goto Label_0593;
                         }
                         catch (Exception exception5)
                         {
                             CommandProcessorBase.CheckForSevereException(exception5);
                             throw new UpdatableHelpSystemException("HelpContentNotFound", StringUtil.Format(HelpDisplayStrings.HelpContentNotFound, new object[0]), ErrorCategory.ResourceUnavailable, null, exception5);
                         }
                     }
                     base._helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, base.Context, resolvedUri, destPaths, module.GetHelpContentName(uri.Culture), Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())), uri.Culture, xsdPath, out collection3);
                 }
                 else if (!base._helpSystem.DownloadAndInstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, base.Context, destPaths, module.GetHelpContentName(uri.Culture), uri.Culture, resolvedUri, xsdPath, out collection3))
                 {
                     flag = false;
                     goto Label_069B;
                 }
             Label_0593:
                 base._helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, uri.Culture.Name, newHelpInfo.GetCultureVersion(uri.Culture), module.ModuleBase, module.GetHelpInfoName(), base._force);
                 foreach (string str15 in collection3)
                 {
                     base.WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, new object[] { module.ModuleName, StringUtil.Format(HelpDisplayStrings.UpdatedHelpContent, str15), uri.Culture.Name, newHelpInfo.GetCultureVersion(uri.Culture) }));
                 }
                 base.LogMessage(StringUtil.Format(HelpDisplayStrings.UpdateHelpCompleted, new object[0]));
                 flag = true;
             }
             catch (Exception exception6)
             {
                 CommandProcessorBase.CheckForSevereException(exception6);
                 base.ProcessException(module.ModuleName, uri.Culture.Name, exception6);
             }
         Label_069B:;
         }
     }
     return flag;
 }