2008-12-15 8 views

Respuesta

13

Sí y sí.

Puede usar el objeto incorporado $host si todo lo que quiere hacer es cambiar el color del texto. Sin embargo, no puede cambiar el mensaje de error en sí, eso está codificado.

Lo que podría hacer es (a) suprimir los mensajes de error, y en su lugar (b) atrapar los errores y mostrar el suyo.

Realice (a) configurando $ErrorActionPreference = "SilentlyContinue" - esto NO PARARÁ el error, pero suprime los mensajes.

Lograr (b) requiere un poco más de trabajo. De manera predeterminada, la mayoría de los comandos de PowerShell no producen una excepción detectable. Por lo tanto, deberá aprender a ejecutar comandos y agregar el parámetro -EA "Stop" para generar una excepción interceptable si algo sale mal. Una vez que hayas hecho esto, se puede crear una trampa en el shell escribiendo:

trap { 
# handle the error here 
} 

Se puede poner esto en su script de perfil en lugar de escribir cada vez. Dentro de la trampa, puede generar el texto de error que desee utilizando el cmdlet Write-Error.

Probablemente más trabajo de lo que querías hacer, pero eso es básicamente cómo harías lo que pedías.

7

Aquí hay un montón de cosas que te permitirán personalizar la salida de tu consola. Puede establecer estas configuraciones como desee en su perfil, o crear funciones/scripts para cambiarlas para diferentes propósitos. Tal vez quieras un modo "No me molestes" a veces, o un "Demuéstrame que todo va mal" a otros. Podría hacer una función/script para cambiar entre esos.

## Change colors of regular text 
$Host.UI.RawUI.BackGroundColor = "DarkMagenta" 
$Host.UI.RawUI.ForeGroundColor = "DarkYellow" 

## Change colors of special messages (defaults shown) 
$Host.PrivateData.DebugBackgroundColor = "Black" 
$Host.PrivateData.DebugForegroundColor = "Yellow" 
$Host.PrivateData.ErrorBackgroundColor = "Black" 
$Host.PrivateData.ErrorForegroundColor = "Red" 
$Host.PrivateData.ProgressBackgroundColor = "DarkCyan" 
$Host.PrivateData.ProgressForegroundColor = "Yellow" 
$Host.PrivateData.VerboseBackgroundColor = "Black" 
$Host.PrivateData.VerboseForegroundColor = "Yellow" 
$Host.PrivateData.WarningBackgroundColor = "Black" 
$Host.PrivateData.WarningForegroundColor = "Yellow" 

## Set the format for displaying Exceptions (default shown) 
## Set this to "CategoryView" to get less verbose, more structured output 
## http://blogs.msdn.com/powershell/archive/2006/06/21/641010.aspx 
$ErrorView = "NormalView" 

## NOTE: This section is only for PowerShell 1.0, it is not used in PowerShell 2.0 and later 
## More control over display of Exceptions (defaults shown), if you want more output 
$ReportErrorShowExceptionClass = 0 
$ReportErrorShowInnerException = 0 
$ReportErrorShowSource = 1 
$ReportErrorShowStackTrace = 0 

## Set display of special messages (defaults shown) 
## http://blogs.msdn.com/powershell/archive/2006/07/04/Use-of-Preference-Variables-to-control-behavior-of-streams.aspx 
## http://blogs.msdn.com/powershell/archive/2006/12/15/confirmpreference.aspx 
$ConfirmPreference = "High" 
$DebugPreference = "SilentlyContinue" 
$ErrorActionPreference = "Continue" 
$ProgressPreference = "Continue" 
$VerbosePreference = "SilentlyContinue" 
$WarningPreference = "Continue" 
$WhatIfPreference = 0 

También puede utilizar el -ErrorAction y parámetros -ErrorVariable de cmdlets para afectar sólo a esa llamada cmdlet. El segundo enviará errores a la variable especificada en lugar del $ Error predeterminado.

+0

Tenga en cuenta que las variables $ ReportErrorShow * en realidad no tienen ningún efecto en PowerShell 2.0. Consulte http://technet.microsoft.com/en-us/library/dd347675.aspx – Timbo

+0

Buen punto, la PS v2.0 tiene un sistema diferente ahora. Actualizaré mi respuesta. – JasonMArcher

1

Además, se puede hacer esto de escribir una línea específica de texto de error:

$Host.UI.WriteErrorLine("This is an error") 

(apoyos a Chris Sears para esta respuesta)

1

Esto puede o no puede ser lo que quiera, pero hay una variable de $ ErrorView preferencia que se puede establecer:

$ErrorView = "CategoryView" 

Esto da un mensaje de error de una sola línea más corta, por ejemplo:

[PS]> get-item D:\blah 
ObjectNotFound: (D:\blah:String) [Get-Item], ItemNotFoundException 
Cuestiones relacionadas