Exemplo n.º 1
0
 private static bool AliasDefinitionsTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
 {
     Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(obj);
     if (hashtableArray == null)
     {
         cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path));
         return false;
     }
     foreach (Hashtable hashtable in hashtableArray)
     {
         if (!hashtable.ContainsKey(AliasNameToken))
         {
             cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { key, AliasNameToken, path }));
             return false;
         }
         if (!hashtable.ContainsKey(AliasValueToken))
         {
             cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { key, AliasValueToken, path }));
             return false;
         }
         foreach (string str in hashtable.Keys)
         {
             if ((!string.Equals(str, AliasNameToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str, AliasValueToken, StringComparison.OrdinalIgnoreCase)) && (!string.Equals(str, AliasDescriptionToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str, AliasOptionsToken, StringComparison.OrdinalIgnoreCase)))
             {
                 cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, new object[] { str, key, path }));
                 return false;
             }
         }
     }
     return true;
 }
Exemplo n.º 2
0
        // Keep in sync:
        // S.M.A.CommandProcessorBase.CheckForSevereException
        // S.M.A.Internal.ConsoleHost.CheckForSevereException
        // S.M.A.Commands.CommandsCommon.CheckForSevereException
        // S.M.A.Commands.UtilityCommon.CheckForSevereException
        /// <summary>
        /// Checks whether the exception is a severe exception which should
        /// cause immediate process failure.
        /// </summary>
        /// <param name="cmdlet">can be null</param>
        /// <param name="e"></param>
        /// <remarks>
        /// CB says 02/23/2005: I personally would err on the side
        /// of treating OOM like an application exception, rather than
        /// a critical system failure.I think this will be easier to justify
        /// in Orcas, if we tease apart the two cases of OOM better.
        /// But even in Whidbey, how likely is it that we couldnt JIT
        /// some backout code?  At that point, the process or possibly
        /// the machine is likely to stop executing soon no matter
        /// what you do in this routine.  So I would just consider
        /// AccessViolationException.  (I understand why you have SO here,
        /// at least temporarily).
        /// </remarks>
        internal static void CheckForSevereException(PSCmdlet cmdlet, Exception e)
        {
            if (e is AccessViolationException || e is StackOverflowException)
            {
                try
                {
                    if (!alreadyFailing)
                    {
                        alreadyFailing = true;

                        // Get the ExecutionContext from the thread.
                        ExecutionContext context =
                            (null != cmdlet)
                                ? cmdlet.Context
                                : LocalPipeline.GetExecutionContextFromTLS();

                        // Log a command health event for this critical error.
                        MshLog.LogCommandHealthEvent(context, e, Severity.Critical);
                    }
                }
                finally
                {
                    if (!designForTestability_SkipFailFast)
                        WindowsErrorReporting.FailFast(e);
                }
            }
        }
Exemplo n.º 3
0
        internal static void MasterStreamOpen(
			PSCmdlet cmdlet,
			string filePath,
			string encoding,
			bool defaultEncoding,
			bool append,
			bool force,
			bool noClobber,
			out FileStream fileStream,
			out StreamWriter streamWriter,
			out FileInfo readOnlyFileInfo,
			bool isLiteralPath)
        {
            var resolvedEncoding = EncodingConversion.Convert(cmdlet, encoding);
            MasterStreamOpen(
                cmdlet,
                filePath,
                resolvedEncoding,
                defaultEncoding,
                append,
                force,
                noClobber,
                out fileStream,
                out streamWriter,
                out readOnlyFileInfo,
                isLiteralPath);
        }
        public DomainDispatcher(PSCmdlet cmdlet)
        {
            Contract.Requires(cmdlet != null);

            _cmdlet = cmdlet;
            _dte = (DTE)cmdlet.GetVariableValue("DTE");
        }
Exemplo n.º 5
0
        /// <summary>
        /// Writes a collection of format view definitions to XML file
        /// </summary>
        /// <param name="typeDefinitions">collection of PSTypeDefinition</param>
        /// <param name="filepath">path to XML file</param>
        /// <param name="cmdlet">cmdlet from which this si used</param>
        /// <param name="force">true - to force write the file</param>
        /// <param name="writeScriptBlock">true - to export scriptblocks</param>
        /// <param name="noclobber">true - do not overwrite the file</param>
        /// <param name="isLiteralPath">true - bypass wildcard expansion on the file name</param>
        internal static void WriteToPs1Xml(PSCmdlet cmdlet, List<ExtendedTypeDefinition> typeDefinitions,
            string filepath, bool force, bool noclobber, bool writeScriptBlock, bool isLiteralPath)
        {
            StreamWriter streamWriter;
            FileStream fileStream;
            FileInfo fileInfo;
            PathUtils.MasterStreamOpen(cmdlet, filepath, "ascii", true, false, force, noclobber,
                out fileStream, out streamWriter, out fileInfo, isLiteralPath);

            try
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(streamWriter))
                {
                    var writer = new FormatXmlWriter
                    {
                        _writer = xmlWriter,
                        _exportScriptBlock = writeScriptBlock
                    };
                    writer.WriteToXml(typeDefinitions);
                }
            }
            finally
            {
                streamWriter.Dispose();
                fileStream.Dispose();
            }
        }
Exemplo n.º 6
0
 internal UpdatableHelpSystemDrive(PSCmdlet cmdlet, string path, PSCredential credential)
 {
     for (int i = 0; i < 6; i++)
     {
         this._driveName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
         this._cmdlet = cmdlet;
         if (path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase) || path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
         {
             path = path.Remove(path.Length - 1);
         }
         PSDriveInfo atScope = cmdlet.SessionState.Drive.GetAtScope(this._driveName, "local");
         if (atScope != null)
         {
             if (atScope.Root.Equals(path))
             {
                 return;
             }
             if (i < 5)
             {
                 continue;
             }
             cmdlet.SessionState.Drive.Remove(this._driveName, true, "local");
         }
         atScope = new PSDriveInfo(this._driveName, cmdlet.SessionState.Internal.GetSingleProvider("FileSystem"), path, string.Empty, credential);
         cmdlet.SessionState.Drive.New(atScope, "local");
         return;
     }
 }
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            ManagementService client = CreateManagementServiceClient();
            var relyingParties = client.RelyingParties;

            List<string> relyingPartyRelayAddresses = new List<string>();

            long relyingPartyId = -1;

            foreach (var relyingParty in relyingParties)
            {
                string name = relyingParty.Name;

                if (name == RelyingParty)
                {
                    relyingPartyId = relyingParty.Id;
                }
            }

            foreach (RelyingPartyAddress address in client.RelyingPartyAddresses)
            {
                if (address.RelyingPartyId == relyingPartyId)
                {
                    relyingPartyRelayAddresses.Add(address.Address);
                }
            }

            callingCmdlet.WriteObject(relyingPartyRelayAddresses, true); ;
        }
Exemplo n.º 8
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="files"></param>
        /// <param name="errorId"></param>
        /// <param name="cmdlet"></param>
        /// <returns></returns>
        internal static Collection<string> Glob(string[] files, string errorId, PSCmdlet cmdlet)
        {
            Collection<string> retValue = new Collection<string>();
            foreach (string file in files)
            {
                Collection<string> providerPaths;
                ProviderInfo provider = null;
                try
                {
                    providerPaths = cmdlet.SessionState.Path.GetResolvedProviderPathFromPSPath(file, out provider);
                }
                catch (SessionStateException e)
                {
                    cmdlet.WriteError(new ErrorRecord(e, errorId, ErrorCategory.InvalidOperation, file));
                    continue;
                }
                if (!provider.NameEquals(cmdlet.Context.ProviderNames.FileSystem))
                {
                    ReportWrongProviderType(provider.FullName, errorId, cmdlet);
                    continue;
                }
                foreach (string providerPath in providerPaths)
                {
                    if (!providerPath.EndsWith(".ps1xml", StringComparison.OrdinalIgnoreCase))
                    {
                        ReportWrongExtension(providerPath, "WrongExtension", cmdlet);
                        continue;
                    }
                    retValue.Add(providerPath);
                }
            }

            return retValue;
        }
Exemplo n.º 9
0
        private static void ShowHelpWindow(PSObject helpObj, PSCmdlet cmdlet)
        {
            Window ownerWindow = ShowCommandHelper.GetHostWindow(cmdlet);
            if (ownerWindow != null)
            {
                ownerWindow.Dispatcher.Invoke(
                    new SendOrPostCallback(
                        delegate(object ignored)
                        {
                            HelpWindow helpWindow = new HelpWindow(helpObj);
                            helpWindow.Owner = ownerWindow;
                            helpWindow.Show();

                            helpWindow.Closed += new EventHandler(delegate(object sender, EventArgs e) { ownerWindow.Focus(); });
                        }),
                        String.Empty);
                return;
            }

            Thread guiThread = new Thread(
            (ThreadStart)delegate
            {
                HelpWindow helpWindow = new HelpWindow(helpObj);
                helpWindow.ShowDialog();
            });
            guiThread.SetApartmentState(ApartmentState.STA);
            guiThread.Start();
        }
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            ManagementService client = CreateManagementServiceClient();
            var relyingParties = client.RelyingParties;

            if (relyingParties != null)
            {
                foreach (var relyingParty in relyingParties)
                {
                    string name = relyingParty.Name;

                    if (name == RelyingParty)
                    {
                        RelyingPartyAddress address = new RelyingPartyAddress();
                        address.Address = RelyingPartyRelayAddress;
                        address.EndpointType = "Reply";

                        client.AddRelatedObject(relyingParty, "RelyingPartyAddresses", address);
                        client.SaveChanges(SaveChangesOptions.Batch);
                    }
                }
            }
            else
            {
                throw new Exception("Failed to get the Relying Parties list from the ACS Management Service.");
            }
        }
Exemplo n.º 11
0
        internal static char SetDelimiter(PSCmdlet Cmdlet, string ParameterSetName, char Delimiter, bool UseCulture)
        {
            switch (ParameterSetName)
            {
                case "Delimiter":
                    if (Delimiter == '\0')
                    {
                        Delimiter = ',';
                    }
                    return Delimiter;

                case "UseCulture":
                    if (UseCulture)
                    {
                        string str = Registry.CurrentUser.OpenSubKey(@"Control Panel\International").GetValue("sList").ToString();
                        if (string.IsNullOrEmpty(str))
                        {
                            Delimiter = ',';
                            return Delimiter;
                        }
                        Delimiter = str[0];
                    }
                    return Delimiter;
            }
            Delimiter = ',';
            return Delimiter;
        }
Exemplo n.º 12
0
 internal ImportCsvHelper(PSCmdlet cmdlet, char delimiter, IList<string> header, string typeName, StreamReader streamReader)
 {
     this._cmdlet = cmdlet;
     this._delimiter = delimiter;
     this._header = header;
     this._typeName = typeName;
     this._sr = streamReader;
 }
Exemplo n.º 13
0
 internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken)
 {
     this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2;
     this.originalThread         = System.Threading.Thread.CurrentThread;
     this.cancellationToken      = cancellationToken;
     this.cmdlet           = cmdlet;
     cmdlet.CommandRuntime = this;
 }
Exemplo n.º 14
0
 internal TerminatingErrorContext(PSCmdlet command)
 {
     if (command == null)
     {
         throw PSTraceSource.NewArgumentNullException("command");
     }
     this._command = command;
 }
Exemplo n.º 15
0
 internal PSHostTraceListener(PSCmdlet cmdlet) : base("")
 {
     this.cachedWrite = new StringBuilder();
     if (cmdlet == null)
     {
         throw new PSArgumentNullException("cmdlet");
     }
     this.ui = cmdlet.Host.UI as InternalHostUserInterface;
 }
        public object GetVariable(PSCmdlet cmdlet, string name)
        {
            if (_variables.ContainsKey(name))
            {
                return _variables[name];
            }

            return null;
        }
Exemplo n.º 17
0
 private static void ReportWrongProviderType(string providerId, string errorId, PSCmdlet cmdlet)
 {
     ErrorRecord errorRecord = new ErrorRecord(
         PSTraceSource.NewInvalidOperationException(UpdateDataStrings.UpdateData_WrongProviderError, providerId),
         errorId,
         ErrorCategory.InvalidArgument,
         null);
     cmdlet.WriteError(errorRecord);
 }
Exemplo n.º 18
0
 private static void ReportWrongExtension(string file, string errorId, PSCmdlet cmdlet)
 {
     ErrorRecord errorRecord = new ErrorRecord(
         PSTraceSource.NewInvalidOperationException(UpdateDataStrings.UpdateData_WrongExtension, file, "ps1xml"),
         errorId,
         ErrorCategory.InvalidArgument,
         null);
     cmdlet.WriteError(errorRecord);
 }
Exemplo n.º 19
0
        public GlymaConfiguration(object identity, PSCmdlet cmdlet)
        {
            Identity = identity;

            Load(cmdlet);
            FindTransactionDbConnectionParameters();
            FindMapDbConnectionParameters();
            FindSecurityDbConnectionParameters();
        }
Exemplo n.º 20
0
        internal static IOctopusRepository RetrieveSession(PSCmdlet cmdlet)
        {
            var octopus = (IOctopusRepository) cmdlet.SessionState.PSVariable.GetValue("OctopusRepository");
            if (octopus == null)
                throw new Exception(
                    "Connection not established. Please connect to your Octopus Deploy instance with Connect-OctoServer");

            return octopus;
        }
Exemplo n.º 21
0
 internal string ResolveProviderAndPath(string path, bool isLiteralPath, PSCmdlet cmdlet, bool allowNonexistingPaths, string resourceBaseName, string multipeProviderErrorId)
 {
     PathInfo info = this.ResolvePath(path, isLiteralPath, allowNonexistingPaths, cmdlet);
     if (info.Provider.ImplementingType != typeof(FileSystemProvider))
     {
         throw PSTraceSource.NewInvalidOperationException(resourceBaseName, multipeProviderErrorId, new object[] { info.Provider.Name });
     }
     return info.ProviderPath;
 }
Exemplo n.º 22
0
 internal CommandInvocationIntrinsics(System.Management.Automation.ExecutionContext context, PSCmdlet cmdlet)
 {
     this._context = context;
     if (cmdlet != null)
     {
         this._cmdlet = cmdlet;
         this.commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
     }
 }
        /// <summary>
        /// Gets a sql auth connection context.
        /// </summary>
        /// <param name="cmdlet">The cmdlet requesting the context</param>
        /// <param name="serverName">The name of the server to connect to</param>
        /// <param name="manageUrl">The manage url of the server</param>
        /// <param name="credentials">The credentials to connect to the server</param>
        /// <param name="sessionActivityId">The session activity ID</param>
        /// <param name="managementServiceUri">The URI for management service</param>
        /// <returns>The connection context</returns>
        public static IServerDataServiceContext GetContext(
            PSCmdlet cmdlet,
            string serverName,
            Uri manageUrl,
            SqlAuthenticationCredentials credentials,
            Guid sessionActivityId,
            Uri managementServiceUri)
        {
            Version version;
            
            // If a version was specified (by tests) us it.
            if (sqlVersion == SqlVersion.v2)
            {
                version = new Version(11, 0);
            }
            else if (sqlVersion == SqlVersion.v12)
            {
                version = new Version(12, 0);
            }
            else // If no version specified, determine the version by querying the server.
            {
                version = GetVersion(manageUrl, credentials);
            }
            sqlVersion = SqlVersion.None;

            IServerDataServiceContext context = null;

            if (version.Major >= 12)
            {
                context = new TSqlConnectionContext(
                    sessionActivityId,
                    manageUrl.Host,
                    credentials,
                    serverName);
            }
            else
            {
                context = ServerDataServiceSqlAuth.Create(
                    managementServiceUri,
                    sessionActivityId,
                    credentials,
                    serverName);

                // Retrieve $metadata to verify model version compatibility
                XDocument metadata = ((ServerDataServiceSqlAuth)context).RetrieveMetadata();
                XDocument filteredMetadata = DataConnectionUtility.FilterMetadataDocument(metadata);
                string metadataHash = DataConnectionUtility.GetDocumentHash(filteredMetadata);
                if (!((ServerDataServiceSqlAuth)context).metadataHashes.Any(knownHash => metadataHash == knownHash))
                {
                    cmdlet.WriteWarning(Resources.WarningModelOutOfDate);
                }

                ((ServerDataServiceSqlAuth)context).MergeOption = MergeOption.PreserveChanges;
            }

            return context;
        }
Exemplo n.º 24
0
        public object GetVariable(PSCmdlet cmdlet, string name)
        {
            PSVariable psVariable = cmdlet.SessionState.PSVariable.Get(name);
            if (psVariable != null)
            {
                return psVariable.Value;
            }

            return null;
        }
        public DomainDispatcher(PSCmdlet cmdlet)
        {
            // Not using Check here because this assembly is very small and without resources
            if (cmdlet == null)
            {
                throw new ArgumentNullException("cmdlet");
            }

            _cmdlet = cmdlet;
            _dte = (DTE)cmdlet.GetVariableValue("DTE");
        }
Exemplo n.º 26
0
 internal static MemoryStream ReadStream(Stream stream, long contentLength, PSCmdlet cmdlet)
 {
     MemoryStream stream3;
     if (stream == null)
     {
         throw new ArgumentNullException("stream");
     }
     if (!stream.CanRead)
     {
         throw new ArgumentOutOfRangeException("stream");
     }
     if (0L >= contentLength)
     {
         contentLength = 0x186a0L;
     }
     int capacity = (int)Math.Min(contentLength, 0x7fffffffL);
     MemoryStream stream2 = new MemoryStream(capacity);
     try
     {
         long o = 0L;
         byte[] buffer = new byte[0x2710];
         int count = 1;
         while (0 < count)
         {
             if (cmdlet != null)
             {
                 ProgressRecord progressRecord = new ProgressRecord(0xa681412, "Reading Web Response", string.Format("Reading response stream... (Number of bytes read: {0})", o));
                 cmdlet.WriteProgress(progressRecord);
             }
             count = stream.Read(buffer, 0, buffer.Length);
             if (0 < count)
             {
                 stream2.Write(buffer, 0, count);
             }
             o += count;
         }
         if (cmdlet != null)
         {
             ProgressRecord record2 = new ProgressRecord(0xa681412, "Reading Web Response", string.Format("Reading web response completed. (Number of bytes read: {0})", o))
             {
                 RecordType = ProgressRecordType.Completed
             };
             cmdlet.WriteProgress(record2);
         }
         stream2.SetLength(o);
         stream3 = stream2;
     }
     catch (Exception)
     {
         stream2.Close();
         throw;
     }
     return stream3;
 }
Exemplo n.º 27
0
 internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken)
 {
     this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2;
     this.originalThread         = System.Threading.Thread.CurrentThread;
     this.cancellationToken      = cancellationToken;
     this.cmdlet = cmdlet;
     if (cmdlet.PagingParameters != null)
     {
         WriteDebug("Client side pagination is enabled for this cmdlet");
     }
     cmdlet.CommandRuntime = this;
 }
Exemplo n.º 28
0
		internal static string GetFilePathOfExistingFile(PSCmdlet cmdlet, string path)
		{
			string unresolvedProviderPathFromPSPath = cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
			if (!File.Exists(unresolvedProviderPathFromPSPath))
			{
				return null;
			}
			else
			{
				return unresolvedProviderPathFromPSPath;
			}
		}
Exemplo n.º 29
0
 internal static void WriteToPS1XML(PSCmdlet cmdlet, List<ExtendedTypeDefinition> typeDefinitions, string filepath, bool force, bool noclobber, bool writeScritBlock, bool isLiteralPath)
 {
     StreamWriter writer;
     FileStream stream;
     FileInfo info;
     PathUtils.MasterStreamOpen(cmdlet, filepath, "ascii", true, false, force, noclobber, out stream, out writer, out info, isLiteralPath);
     XmlWriter writer2 = XmlWriter.Create(writer);
     FormatXMLHelper.WriteToXML(writer2, typeDefinitions, writeScritBlock);
     writer2.Close();
     writer.Close();
     stream.Close();
 }
 internal static void RestartWinRMService(PSCmdlet cmdlet, bool isErrorReported, bool force, bool noServiceRestart)
 {
     if (!isErrorReported && !noServiceRestart)
     {
         string restartWSManServiceAction = RemotingErrorIdStrings.RestartWSManServiceAction;
         string target = StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceTarget, "WinRM");
         if (force || cmdlet.ShouldProcess(target, restartWSManServiceAction))
         {
             cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceMessageV, new object[0]));
             cmdlet.InvokeCommand.NewScriptBlock("restart-service winrm -force -confirm:$false").InvokeUsingCmdlet(cmdlet, true, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, new object[0], AutomationNull.Value, new object[0]);
         }
     }
 }
Exemplo n.º 31
0
 internal ImportXmlHelper(string fileName, PSCmdlet cmdlet, bool isLiteralPath)
 {
     if (fileName == null)
     {
         throw PSTraceSource.NewArgumentNullException("fileName");
     }
     if (cmdlet == null)
     {
         throw PSTraceSource.NewArgumentNullException("cmdlet");
     }
     this._path = fileName;
     this._cmdlet = cmdlet;
     this.isLiteralPath = isLiteralPath;
 }
Exemplo n.º 32
0
        /// <summary>
        /// Default constructor used if no.
        /// </summary>
        internal PSHostTraceListener(PSCmdlet cmdlet)
            : base("")
        {
            if (cmdlet == null)
            {
                throw new PSArgumentNullException("cmdlet");
            }

            Diagnostics.Assert(
                cmdlet.Host.UI is InternalHostUserInterface,
                "The internal host must be available to trace");

            _ui = cmdlet.Host.UI as InternalHostUserInterface;
        }
Exemplo n.º 33
0
        public void Dispose()
        {
            if (cmdlet != null)
            {
                cmdlet.CommandRuntime = this.originalCommandRuntime;
                cmdlet = null;
            }

            semaphore?.Dispose();
            semaphore = null;
            readyToRun?.Dispose();
            readyToRun = null;
            completed?.Dispose();
            completed = null;
        }
 internal CommandInvocationIntrinsics(System.Management.Automation.ExecutionContext context, PSCmdlet cmdlet)
 {
     this._context = context;
     if (cmdlet != null)
     {
         this._cmdlet        = cmdlet;
         this.commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
     }
 }
        /**
         * This function takes in a CommandInfo (CmdletInfo or FunctionInfo)
         * And reads all the deprecation attributes attached to it
         * Prints a message on the cmdline For each of the attribute found
         *
         * the boundParameterNames is a list of parameters bound to the cmdlet at runtime,
         * We only process the Parameter beaking change attributes attached only params listed in this list (if present)
         * */
        public static void ProcessCustomAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet)
        {
            bool supressWarningOrError = false;

            try
            {
                supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME));
            }
            catch (Exception)
            {
                //no action
            }

            if (supressWarningOrError)
            {
                //Do not process the attributes at runtime... The env variable to override the warning messages is set
                return;
            }

            List <GenericBreakingChangeAttribute> attributes = new List <GenericBreakingChangeAttribute>(GetAllBreakingChangeAttributesInType(commandInfo, invocationInfo, parameterSet));
            StringBuilder   sb = new StringBuilder();
            Action <string> appendBreakingChangeInfo = (string s) => sb.Append(s);

            if (attributes != null && attributes.Count > 0)
            {
                appendBreakingChangeInfo(string.Format(Resources.BreakingChangesAttributesHeaderMessage, commandInfo.Name.Split('_')[0]));

                foreach (GenericBreakingChangeAttribute attribute in attributes)
                {
                    attribute.PrintCustomAttributeInfo(appendBreakingChangeInfo);
                }

                appendBreakingChangeInfo(string.Format(Resources.BreakingChangesAttributesFooterMessage, BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK));

                psCmdlet.WriteWarning(sb.ToString());
            }

            List <PreviewMessageAttribute> previewAttributes = new List <PreviewMessageAttribute>(GetAllPreviewAttributesInType(commandInfo, invocationInfo));

            if (previewAttributes != null && previewAttributes.Count > 0)
            {
                foreach (PreviewMessageAttribute attribute in previewAttributes)
                {
                    attribute.PrintCustomAttributeInfo(psCmdlet);
                }
            }
        }
Exemplo n.º 36
0
 internal static void ExportModuleMembers(PSCmdlet cmdlet, SessionStateInternal sessionState, List <WildcardPattern> functionPatterns, List <WildcardPattern> cmdletPatterns, List <WildcardPattern> aliasPatterns, List <WildcardPattern> variablePatterns, List <string> doNotExportCmdlets)
 {
     sessionState.UseExportList = true;
     if (functionPatterns != null)
     {
         foreach (KeyValuePair <string, FunctionInfo> pair in sessionState.ModuleScope.FunctionTable)
         {
             if (((pair.Value.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && SessionStateUtilities.MatchesAnyWildcardPattern(pair.Key, functionPatterns, false))
             {
                 string str;
                 if (pair.Value.CommandType == CommandTypes.Workflow)
                 {
                     str = StringUtil.Format(Modules.ExportingWorkflow, pair.Key);
                     sessionState.ExportedWorkflows.Add((WorkflowInfo)pair.Value);
                 }
                 else
                 {
                     str = StringUtil.Format(Modules.ExportingFunction, pair.Key);
                     sessionState.ExportedFunctions.Add(pair.Value);
                 }
                 cmdlet.WriteVerbose(str);
             }
         }
         SortAndRemoveDuplicates <FunctionInfo>(sessionState.ExportedFunctions, ci => ci.Name);
         SortAndRemoveDuplicates <WorkflowInfo>(sessionState.ExportedWorkflows, ci => ci.Name);
     }
     if (cmdletPatterns != null)
     {
         IDictionary <string, List <CmdletInfo> > cmdletTable = sessionState.ModuleScope.CmdletTable;
         if (sessionState.Module.CompiledExports.Count > 0)
         {
             CmdletInfo[] infoArray = sessionState.Module.CompiledExports.ToArray();
             sessionState.Module.CompiledExports.Clear();
             CmdletInfo[] infoArray2 = infoArray;
             for (int i = 0; i < infoArray2.Length; i++)
             {
                 Predicate <string> match   = null;
                 CmdletInfo         element = infoArray2[i];
                 if (doNotExportCmdlets != null)
                 {
                     if (match == null)
                     {
                         match = cmdletName => string.Equals(element.FullName, cmdletName, StringComparison.OrdinalIgnoreCase);
                     }
                     if (doNotExportCmdlets.Exists(match))
                     {
                         continue;
                     }
                 }
                 if (SessionStateUtilities.MatchesAnyWildcardPattern(element.Name, cmdletPatterns, false))
                 {
                     string text = StringUtil.Format(Modules.ExportingCmdlet, element.Name);
                     cmdlet.WriteVerbose(text);
                     CmdletInfo item = new CmdletInfo(element.Name, element.ImplementingType, element.HelpFile, null, element.Context);
                     item.SetModule(sessionState.Module);
                     sessionState.Module.CompiledExports.Add(item);
                 }
             }
         }
         foreach (KeyValuePair <string, List <CmdletInfo> > pair2 in cmdletTable)
         {
             CmdletInfo cmdletToImport = pair2.Value[0];
             if (((doNotExportCmdlets == null) || !doNotExportCmdlets.Exists(cmdletName => string.Equals(cmdletToImport.FullName, cmdletName, StringComparison.OrdinalIgnoreCase))) && SessionStateUtilities.MatchesAnyWildcardPattern(pair2.Key, cmdletPatterns, false))
             {
                 string str3 = StringUtil.Format(Modules.ExportingCmdlet, pair2.Key);
                 cmdlet.WriteVerbose(str3);
                 CmdletInfo info2 = new CmdletInfo(cmdletToImport.Name, cmdletToImport.ImplementingType, cmdletToImport.HelpFile, null, cmdletToImport.Context);
                 info2.SetModule(sessionState.Module);
                 sessionState.Module.CompiledExports.Add(info2);
             }
         }
         SortAndRemoveDuplicates <CmdletInfo>(sessionState.Module.CompiledExports, ci => ci.Name);
     }
     if (variablePatterns != null)
     {
         foreach (KeyValuePair <string, PSVariable> pair3 in sessionState.ModuleScope.Variables)
         {
             if ((!pair3.Value.IsAllScope && (Array.IndexOf <string>(PSModuleInfo._builtinVariables, pair3.Key) == -1)) && SessionStateUtilities.MatchesAnyWildcardPattern(pair3.Key, variablePatterns, false))
             {
                 string str4 = StringUtil.Format(Modules.ExportingVariable, pair3.Key);
                 cmdlet.WriteVerbose(str4);
                 sessionState.ExportedVariables.Add(pair3.Value);
             }
         }
         SortAndRemoveDuplicates <PSVariable>(sessionState.ExportedVariables, v => v.Name);
     }
     if (aliasPatterns != null)
     {
         foreach (AliasInfo info3 in sessionState.ModuleScope.AliasTable)
         {
             if (((info3.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && SessionStateUtilities.MatchesAnyWildcardPattern(info3.Name, aliasPatterns, false))
             {
                 string str5 = StringUtil.Format(Modules.ExportingAlias, info3.Name);
                 cmdlet.WriteVerbose(str5);
                 sessionState.ExportedAliases.Add(info3);
             }
         }
         SortAndRemoveDuplicates <AliasInfo>(sessionState.ExportedAliases, ci => ci.Name);
     }
 }
Exemplo n.º 37
0
        internal static void MasterStreamOpen(PSCmdlet cmdlet, string filePath, string encoding, bool defaultEncoding, bool Append, bool Force, bool NoClobber, out FileStream fileStream, out StreamWriter streamWriter, out FileInfo readOnlyFileInfo, bool isLiteralPath)
        {
            Encoding resolvedEncoding = EncodingConversion.Convert(cmdlet, encoding);

            MasterStreamOpen(cmdlet, filePath, resolvedEncoding, defaultEncoding, Append, Force, NoClobber, out fileStream, out streamWriter, out readOnlyFileInfo, isLiteralPath);
        }
Exemplo n.º 38
0
 public void PrintCustomAttributeInfo(System.Management.Automation.PSCmdlet psCmdlet)
 {
     psCmdlet.WriteWarning(this._message);
 }
Exemplo n.º 39
0
 internal CommandInvocationIntrinsics(ExecutionContext context, PSCmdlet cmdlet)
 {
     this._context       = context;
     this._cmdlet        = cmdlet;
     this.commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
 }
Exemplo n.º 40
0
        internal static void MasterStreamOpen(PSCmdlet cmdlet, string filePath, Encoding resolvedEncoding, bool defaultEncoding, bool Append, bool Force, bool NoClobber, out FileStream fileStream, out StreamWriter streamWriter, out FileInfo readOnlyFileInfo, bool isLiteralPath)
        {
            fileStream       = null;
            streamWriter     = null;
            readOnlyFileInfo = null;
            string path = ResolveFilePath(filePath, cmdlet, isLiteralPath);

            try
            {
                FileMode create = FileMode.Create;
                if (Append)
                {
                    create = FileMode.Append;
                }
                else if (NoClobber)
                {
                    create = FileMode.CreateNew;
                }
                if ((Force && (Append || !NoClobber)) && File.Exists(path))
                {
                    FileInfo info = new FileInfo(path);
                    if ((info.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                    {
                        readOnlyFileInfo = info;
                        info.Attributes &= ~System.IO.FileAttributes.ReadOnly;
                    }
                }
                FileShare share = Force ? FileShare.ReadWrite : FileShare.Read;
                fileStream = new FileStream(path, create, FileAccess.Write, share);
                if (defaultEncoding)
                {
                    streamWriter = new StreamWriter(fileStream);
                }
                else
                {
                    streamWriter = new StreamWriter(fileStream, resolvedEncoding);
                }
            }
            catch (ArgumentException exception)
            {
                ReportFileOpenFailure(cmdlet, path, exception);
            }
            catch (IOException exception2)
            {
                if (NoClobber && File.Exists(path))
                {
                    ErrorRecord errorRecord = new ErrorRecord(exception2, "NoClobber", ErrorCategory.ResourceExists, path)
                    {
                        ErrorDetails = new ErrorDetails(cmdlet, "PathUtilsStrings", "UtilityFileExistsNoClobber", new object[] { filePath, "NoClobber" })
                    };
                    cmdlet.ThrowTerminatingError(errorRecord);
                }
                ReportFileOpenFailure(cmdlet, path, exception2);
            }
            catch (UnauthorizedAccessException exception3)
            {
                ReportFileOpenFailure(cmdlet, path, exception3);
            }
            catch (NotSupportedException exception4)
            {
                ReportFileOpenFailure(cmdlet, path, exception4);
            }
            catch (SecurityException exception5)
            {
                ReportFileOpenFailure(cmdlet, path, exception5);
            }
        }
Exemplo n.º 41
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)");

            DirectoryInfo directoryInfo = null;

            try
            {
                string rootedPath = Microsoft.PowerShell.Commands.ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith(".", StringComparison.OrdinalIgnoreCase))
                {
                    PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem);
                    rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath);
                }
                if (string.IsNullOrEmpty(rootedPath))
                {
                    string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath();
                    rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath);
                }

                directoryInfo = new DirectoryInfo(rootedPath);
                if (directoryInfo.Exists)
                {
                    if (!force)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                            PathUtilsStrings.ExportPSSession_ErrorDirectoryExists,
                            directoryInfo.FullName);
                        ErrorDetails details     = new ErrorDetails(errorMessage);
                        ErrorRecord  errorRecord = new ErrorRecord(
                            new ArgumentException(details.Message),
                            "ExportProxyCommand_OutputDirectoryExists",
                            ErrorCategory.ResourceExists,
                            directoryInfo);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                else
                {
                    directoryInfo.Create();
                }
            }
            catch (Exception e)
            {
                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                    PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory,
                    moduleNameOrPath,
                    e.Message);
                ErrorDetails details     = new ErrorDetails(errorMessage);
                ErrorRecord  errorRecord = new ErrorRecord(
                    new ArgumentException(details.Message, e),
                    "ExportProxyCommand_CannotCreateOutputDirectory",
                    ErrorCategory.ResourceExists,
                    moduleNameOrPath);
                cmdlet.ThrowTerminatingError(errorRecord);
            }

            return(directoryInfo);
        }
Exemplo n.º 42
0
 internal static void ExportModuleMembers(
     PSCmdlet cmdlet,
     SessionStateInternal sessionState,
     List <WildcardPattern> functionPatterns,
     List <WildcardPattern> cmdletPatterns,
     List <WildcardPattern> aliasPatterns,
     List <WildcardPattern> variablePatterns)
 {
     sessionState.UseExportList = true;
     if (functionPatterns != null)
     {
         foreach (KeyValuePair <string, FunctionInfo> keyValuePair in (IEnumerable <KeyValuePair <string, FunctionInfo> >)sessionState.ModuleScope.FunctionTable)
         {
             if (SessionStateUtilities.MatchesAnyWildcardPattern(keyValuePair.Key, (IEnumerable <WildcardPattern>)functionPatterns, false))
             {
                 string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingFunction", (object)keyValuePair.Key);
                 cmdlet.WriteVerbose(text);
                 sessionState.ExportedFunctions.Add(keyValuePair.Value);
             }
         }
         ModuleIntrinsics.SortAndRemoveDuplicates <FunctionInfo>(sessionState.ExportedFunctions, (Converter <FunctionInfo, string>)(ci => ci.Name));
     }
     if (cmdletPatterns != null)
     {
         IDictionary <string, List <CmdletInfo> > cmdletCache = (IDictionary <string, List <CmdletInfo> >)sessionState.CmdletCache;
         if (sessionState.Module.CompiledExports.Count > 0)
         {
             CmdletInfo[] array = sessionState.Module.CompiledExports.ToArray();
             sessionState.Module.CompiledExports.Clear();
             foreach (CmdletInfo cmdletInfo1 in array)
             {
                 if (SessionStateUtilities.MatchesAnyWildcardPattern(cmdletInfo1.Name, (IEnumerable <WildcardPattern>)cmdletPatterns, false))
                 {
                     string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingCmdlet", (object)cmdletInfo1.Name);
                     cmdlet.WriteVerbose(text);
                     CmdletInfo cmdletInfo2 = new CmdletInfo(cmdletInfo1.Name, cmdletInfo1.ImplementingType, cmdletInfo1.HelpFile, (PSSnapInInfo)null, cmdletInfo1.Context);
                     cmdletInfo2.SetModule(sessionState.Module);
                     sessionState.Module.CompiledExports.Add(cmdletInfo2);
                 }
             }
         }
         foreach (KeyValuePair <string, List <CmdletInfo> > keyValuePair in (IEnumerable <KeyValuePair <string, List <CmdletInfo> > >)cmdletCache)
         {
             if (SessionStateUtilities.MatchesAnyWildcardPattern(keyValuePair.Key, (IEnumerable <WildcardPattern>)cmdletPatterns, false))
             {
                 string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingCmdlet", (object)keyValuePair.Key);
                 cmdlet.WriteVerbose(text);
                 CmdletInfo cmdletInfo1 = keyValuePair.Value[0];
                 CmdletInfo cmdletInfo2 = new CmdletInfo(cmdletInfo1.Name, cmdletInfo1.ImplementingType, cmdletInfo1.HelpFile, (PSSnapInInfo)null, cmdletInfo1.Context);
                 cmdletInfo2.SetModule(sessionState.Module);
                 sessionState.Module.CompiledExports.Add(cmdletInfo2);
             }
         }
         ModuleIntrinsics.SortAndRemoveDuplicates <CmdletInfo>(sessionState.Module.CompiledExports, (Converter <CmdletInfo, string>)(ci => ci.Name));
     }
     if (variablePatterns != null)
     {
         foreach (KeyValuePair <string, PSVariable> variable in (IEnumerable <KeyValuePair <string, PSVariable> >)sessionState.ModuleScope.Variables)
         {
             if (!variable.Value.IsAllScope && Array.IndexOf <string>(PSModuleInfo.builtinVariables, variable.Key) == -1 && SessionStateUtilities.MatchesAnyWildcardPattern(variable.Key, (IEnumerable <WildcardPattern>)variablePatterns, false))
             {
                 string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingVariable", (object)variable.Key);
                 cmdlet.WriteVerbose(text);
                 sessionState.ExportedVariables.Add(variable.Value);
             }
         }
         ModuleIntrinsics.SortAndRemoveDuplicates <PSVariable>(sessionState.ExportedVariables, (Converter <PSVariable, string>)(v => v.Name));
     }
     if (aliasPatterns == null)
     {
         return;
     }
     foreach (AliasInfo aliasInfo in sessionState.ModuleScope.AliasTable)
     {
         if ((aliasInfo.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None && SessionStateUtilities.MatchesAnyWildcardPattern(aliasInfo.Name, (IEnumerable <WildcardPattern>)aliasPatterns, false))
         {
             string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingAlias", (object)aliasInfo.Name);
             cmdlet.WriteVerbose(text);
             sessionState.ExportedAliases.Add(aliasInfo);
         }
     }
     ModuleIntrinsics.SortAndRemoveDuplicates <AliasInfo>(sessionState.ExportedAliases, (Converter <AliasInfo, string>)(ci => ci.Name));
 }
Exemplo n.º 43
0
        internal static StreamReader OpenStreamReader(PSCmdlet command, string filePath, Encoding encoding, bool isLiteralPath)
        {
            FileStream fileStream = OpenFileStream(filePath, command, isLiteralPath);

            return(new StreamReader(fileStream, encoding));
        }
Exemplo n.º 44
0
 /// <summary>
 /// Resolve a user provided file name or path (including globbing characters)
 /// to a fully qualified file path, using the file system provider.
 /// </summary>
 /// <param name="filePath"></param>
 /// <param name="command"></param>
 /// <returns></returns>
 internal static string ResolveFilePath(string filePath, PSCmdlet command)
 {
     return(ResolveFilePath(filePath, command, false));
 }
Exemplo n.º 45
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)");

            DirectoryInfo directoryInfo = null;

            try
            {
                // Even if 'moduleNameOrPath' is a rooted path, 'ResolveRootedFilePath' may return null when the path doesn't exist yet,
                // or when it contains wildcards but cannot be resolved to a single path.
                string rootedPath = ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith('.'))
                {
                    PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem);
                    rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath);
                }

                if (string.IsNullOrEmpty(rootedPath))
                {
                    if (Path.IsPathRooted(moduleNameOrPath))
                    {
                        rootedPath = moduleNameOrPath;
                    }
                    else
                    {
                        string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath();
                        if (string.IsNullOrEmpty(personalModuleRoot))
                        {
                            cmdlet.ThrowTerminatingError(
                                new ErrorRecord(
                                    new ArgumentException(StringUtil.Format(PathUtilsStrings.ExportPSSession_ErrorModuleNameOrPath, moduleNameOrPath)),
                                    "ExportPSSession_ErrorModuleNameOrPath",
                                    ErrorCategory.InvalidArgument,
                                    cmdlet));
                        }

                        rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath);
                    }
                }

                directoryInfo = new DirectoryInfo(rootedPath);
                if (directoryInfo.Exists)
                {
                    if (!force)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                            PathUtilsStrings.ExportPSSession_ErrorDirectoryExists,
                            directoryInfo.FullName);
                        ErrorDetails details     = new ErrorDetails(errorMessage);
                        ErrorRecord  errorRecord = new ErrorRecord(
                            new ArgumentException(details.Message),
                            "ExportProxyCommand_OutputDirectoryExists",
                            ErrorCategory.ResourceExists,
                            directoryInfo);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                else
                {
                    directoryInfo.Create();
                }
            }
            catch (Exception e)
            {
                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                    PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory,
                    moduleNameOrPath,
                    e.Message);
                ErrorDetails details     = new ErrorDetails(errorMessage);
                ErrorRecord  errorRecord = new ErrorRecord(
                    new ArgumentException(details.Message, e),
                    "ExportProxyCommand_CannotCreateOutputDirectory",
                    ErrorCategory.ResourceExists,
                    moduleNameOrPath);
                cmdlet.ThrowTerminatingError(errorRecord);
            }

            return(directoryInfo);
        }
Exemplo n.º 46
0
        /// <summary>
        /// THE method for opening a file for writing.
        /// Should be used by all cmdlets that write to a file.
        /// </summary>
        /// <param name="cmdlet">Cmdlet that is opening the file (used mainly for error reporting).</param>
        /// <param name="filePath">Path to the file (as specified on the command line - this method will resolve the path).</param>
        /// <param name="resolvedEncoding">Encoding (this method will convert the command line string to an Encoding instance).</param>
        /// <param name="defaultEncoding">If <see langword="true"/>, then we will use default .NET encoding instead of the encoding specified in <paramref name="encoding"/> parameter.</param>
        /// <param name="Append"></param>
        /// <param name="Force"></param>
        /// <param name="NoClobber"></param>
        /// <param name="fileStream">Result1: <see cref="FileStream"/> opened for writing.</param>
        /// <param name="streamWriter">Result2: <see cref="StreamWriter"/> (inherits from <see cref="TextWriter"/>) opened for writing.</param>
        /// <param name="readOnlyFileInfo">Result3: file info that should be used to restore file attributes after done with the file (<see langword="null"/> is this is not needed).</param>
        /// <param name="isLiteralPath">True if wildcard expansion should be bypassed.</param>
        internal static void MasterStreamOpen(
            PSCmdlet cmdlet,
            string filePath,
            Encoding resolvedEncoding,
            bool defaultEncoding,
            bool Append,
            bool Force,
            bool NoClobber,
            out FileStream fileStream,
            out StreamWriter streamWriter,
            out FileInfo readOnlyFileInfo,
            bool isLiteralPath)
        {
            fileStream       = null;
            streamWriter     = null;
            readOnlyFileInfo = null;

            // resolve the path and the encoding
            string resolvedPath = ResolveFilePath(filePath, cmdlet, isLiteralPath);

            try
            {
                // variable to track file open mode
                // this is controlled by append/force parameters
                FileMode mode = FileMode.Create;
                if (Append)
                {
                    mode = FileMode.Append;
                }
                else if (NoClobber)
                {
                    // throw IOException if file exists
                    mode = FileMode.CreateNew;
                }

                if (Force && (Append || !NoClobber))
                {
                    if (File.Exists(resolvedPath))
                    {
                        FileInfo fInfo = new FileInfo(resolvedPath);
                        if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                        {
                            // remember to reset the read-only attribute later
                            readOnlyFileInfo = fInfo;
                            // Clear the read-only attribute
                            fInfo.Attributes &= ~(FileAttributes.ReadOnly);
                        }
                    }
                }

                // if the user knows what he/she is doing and uses "-Force" switch,
                // then we let more than 1 process write to the same file at the same time
                FileShare fileShare = Force ? FileShare.ReadWrite : FileShare.Read;

                // mode is controlled by force and ShouldContinue()
                fileStream = new FileStream(resolvedPath, mode, FileAccess.Write, fileShare);

                // create stream writer
                // NTRAID#Windows Out Of Band Releases-931008-2006/03/27
                // For some reason, calling this without specifying
                // the encoding is different from passing Encoding.Default.
                if (defaultEncoding)
                {
                    streamWriter = new StreamWriter(fileStream);
                }
                else
                {
                    streamWriter = new StreamWriter(fileStream, resolvedEncoding);
                }
            }
            // These are the known exceptions for File.Load and StreamWriter.ctor
            catch (ArgumentException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (IOException e)
            {
                if (NoClobber && File.Exists(resolvedPath))
                {
                    // This probably happened because the file already exists
                    ErrorRecord errorRecord = new ErrorRecord(
                        e, "NoClobber", ErrorCategory.ResourceExists, resolvedPath);
                    errorRecord.ErrorDetails = new ErrorDetails(
                        cmdlet,
                        "PathUtilsStrings",
                        "UtilityFileExistsNoClobber",
                        filePath,
                        "NoClobber"); // prevents localization

                    // NOTE: this call will throw
                    cmdlet.ThrowTerminatingError(errorRecord);
                }
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (UnauthorizedAccessException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (NotSupportedException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (System.Security.SecurityException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
        }
Exemplo n.º 47
0
        private static IEnumerable <PSObject> InvokeTopLevelPowerShell(
            PowerShell powerShell,
            CancellationToken cancellationToken,
            PSCmdlet cmdlet,
            PSInvocationSettings invocationSettings,
            string errorMessageTemplate)
        {
            using (var mergedOutput = new BlockingCollection <Func <PSCmdlet, IEnumerable <PSObject> > >(s_blockingCollectionCapacity))
            {
                var asyncOutput = new PSDataCollection <PSObject>();
                EventHandler <DataAddedEventArgs> outputHandler = GetStreamForwarder <PSObject>(
                    output => mergedOutput.Add(_ => new[] { output }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> errorHandler = GetStreamForwarder <ErrorRecord>(
                    errorRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate);
                    HandleErrorFromPipeline(c, errorRecord, powerShell);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> warningHandler = GetStreamForwarder <WarningRecord>(
                    warningRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteWarning(warningRecord.Message);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> verboseHandler = GetStreamForwarder <VerboseRecord>(
                    verboseRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteVerbose(verboseRecord.Message);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> debugHandler = GetStreamForwarder <DebugRecord>(
                    debugRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteDebug(debugRecord.Message);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> informationHandler = GetStreamForwarder <InformationRecord>(
                    informationRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteInformation(informationRecord);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                asyncOutput.DataAdded += outputHandler;
                powerShell.Streams.Error.DataAdded       += errorHandler;
                powerShell.Streams.Warning.DataAdded     += warningHandler;
                powerShell.Streams.Verbose.DataAdded     += verboseHandler;
                powerShell.Streams.Debug.DataAdded       += debugHandler;
                powerShell.Streams.Information.DataAdded += informationHandler;

                try
                {
                    // TODO/FIXME: ETW event for PowerShell invocation

                    var asyncResult = powerShell.BeginInvoke <PSObject, PSObject>(
                        input: null,
                        output: asyncOutput,
                        settings: invocationSettings,
                        callback: delegate
                    {
                        try
                        {
                            mergedOutput.CompleteAdding();
                        }
                        catch (InvalidOperationException)
                        // ignore exceptions thrown because mergedOutput.CompleteAdding was called
                        {
                        }
                    },
                        state: null);

                    using (cancellationToken.Register(powerShell.Stop))
                    {
                        try
                        {
                            foreach (Func <PSCmdlet, IEnumerable <PSObject> > mergedOutputItem in mergedOutput.GetConsumingEnumerable())
                            {
                                foreach (PSObject outputObject in mergedOutputItem(cmdlet))
                                {
                                    yield return(outputObject);
                                }
                            }
                        }
                        finally
                        {
                            mergedOutput.CompleteAdding();
                            powerShell.EndInvoke(asyncResult);
                        }
                    }
                }
                finally
                {
                    asyncOutput.DataAdded -= outputHandler;
                    powerShell.Streams.Error.DataAdded       -= errorHandler;
                    powerShell.Streams.Warning.DataAdded     -= warningHandler;
                    powerShell.Streams.Verbose.DataAdded     -= verboseHandler;
                    powerShell.Streams.Debug.DataAdded       -= debugHandler;
                    powerShell.Streams.Information.DataAdded -= informationHandler;
                }
            }
        }