AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / server / Perguntas / 722526
Accepted
Caynadian
Caynadian
Asked: 2015-09-16 10:57:33 +0800 CST2015-09-16 10:57:33 +0800 CST 2015-09-16 10:57:33 +0800 CST

Forçar saída do script Powershell em formato tabular

  • 772

Existe alguma maneira de forçar a saída de um script do PowerShell v3 para a forma tabular? Meu script está gerando uma lista de serviços em formato linear, embora haja apenas 6 campos no objeto de saída (get-process gera 8 campos em formato tabular). Aqui está o meu código:

<#
.SYNOPSIS
Gets a list of services on a given computer that are supposed to automatically start but are not currently running.
.PARAMETER ComputerName
The computer name(s) to retrieve the info from.
.PARAMETER IgnoreList
The path and filename of a text file containing a list of service names to ignore.  This file has to list actual service names and not display names.  Defaults to "StoppedServices-Ignore.txt" in the current directory.
.PARAMETER StartServices
Optional switch that when specified will cause this function to attempt to start all of the services it finds stopped.
.EXAMPLE
Get-StoppedServices -ComputerName Computer01 -IgnoreList '.\IgnoredServices.txt' -StartServices
.EXAMPLE
Get-StoppedServices –ComputerName Computer01,Computer02,Computer03
.EXAMPLE
"Computer01" | Get-StoppedServices
.EXAMPLE
Get-StoppedServices –ComputerName (Get-Content ComputerList.txt)
.EXAMPLE
Get-Content ComputerList.txt | Get-StoppedServices -IgnoreList '.\IgnoredServices.txt' -StartServices
#>
Function Get-StoppedServices {
  [CmdletBinding()]
  param(
    [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [String[]]$ComputerName,
    [string]$IgnoreList,
    [switch]$StartServices
  )
  PROCESS {
    # Load the list of services to ignore (if specified).
    if ($IgnoreList) {
      if (Test-Path $IgnoreList) {
        $ignore = import-csv -header Service $IgnoreList
        Write-Verbose "Ignoring the following services:"
        Write-Verbose $ignore.ToString()
      } else {
        Write-Warning "Could not find ignore list $IgnoreList."
      }
    }

    # Get a list of stopped services that are set to run automatically (ie: that should be running)
    foreach ($c in $ComputerName) {
      Write-Verbose "Getting services from $($c.Name)"
      if (Test-Connection -ComputerName $c -Count 1 -Quiet) {
        Try {
          $serv += get-wmiobject -query "Select __Server,Name,DisplayName,State,StartMode,ExitCode,Status FROM Win32_Service WHERE StartMode='Auto' AND State!='Running'" -computername $c -erroraction stop
        } catch {
          Write-Warning "Could not get service list from $($c)"
        }
      }
    }

    # Create the resulting list of services by removing any that are in the ignore list.
    $results = @()
    foreach ($s in $serv) {
      Write-Verbose "Checking if $($s.name) in ignore list."
      if ($ignore -match $s.name) { 
        Write-Verbose "  *Service in ignore list."
      } else {
        Write-Verbose "  Service OK."
        $obj = New-Object -typename PSObject
        $obj | Add-Member -membertype NoteProperty -name ComputerName -value ($s.PSComputerName) -passthru |
               Add-Member -membertype NoteProperty -name ServiceName  -value ($s.Name)           -passthru |
               Add-Member -membertype NoteProperty -name DisplayName  -value ($s.DisplayName)    -passthru |
               Add-Member -membertype NoteProperty -name Status       -value ($s.Status)         -passthru |
               Add-Member -membertype NoteProperty -name State        -value ($s.State)          -passthru |
               Add-Member -membertype NoteProperty -name ExitCode     -value ($s.ExitCode)
        $results += $obj
      }
    }

    # Try and start each of the stopped services that hasn't been ignored.
    if ($StartServices) {
      foreach ($s in $results) {
        Write-Verbose "Starting '$($s.DisplayName)' ($($s.name)) on '$($s.ComputerName)..."
        Try {
          Get-Service -Name $s.name -ComputerName $s.ComputerName -erroraction stop | Start-service -erroraction stop
        } Catch {
          Write-Warning "Could not start service $($s.name) on $($s.ComputerName)."
        }
      }  
    }

    # Output the list of filtered services to the pipeline.
    write-output $results
  }
}
powershell
  • 1 1 respostas
  • 1208 Views

1 respostas

  • Voted
  1. Best Answer
    Mathias R. Jessen
    2015-09-21T07:23:25+08:002015-09-21T07:23:25+08:00

    Quando um ou mais objetos se aproximam do host, o PowerShell verifica o número de propriedades que o objeto possui.

    Se o tipo de um objeto puder ser resolvido para um Format.ps1xmlarquivo correspondente (voltaremos a isso em um minuto), a convenção de formatação descrita naquele documento será usada - caso contrário, dependerá do número de propriedades que um objeto possui.


    Se um objeto tiver menos de 5 propriedades, o padrão é usar Format-Tablepara formatação de saída:

    PS C:\> New-Object psobject -Property ([ordered]@{PropA=1;PropB=2;PropC=3;PropD=4})
    
    PropA PropB PropC PropD
    ----- ----- ----- -----
        1     2     3     4
    

    Se um objeto tiver mais propriedades, o padrão é Format-List(que é o que você experimenta):

    PS C:\> New-Object psobject -Property ([ordered]@{PropA=1;PropB=2;PropC=3;PropD=4;PropE=5})
    
    
    PropA : 1
    PropB : 2
    PropC : 3
    PropD : 4
    PropE : 5
    

    Agora, a razão pela qual os objetos retornados do cmdlet Get-Serviceor Get-Processparecem formatar em uma tabela agradável, contextualmente relevante e com mais de 5 colunas é que o PowerShell conseguiu encontrar um documento de formatação específico do tipo para eles.

    Esses arquivos de formatação estão todos localizados no diretório de instalação do PowerShell, você pode localizar os arquivos padrão com:

    Get-ChildItem $PSHome *.Format.ps1xml
    

    Veja Get-Help about_Format.ps1xmlse você deseja criar seus próprios arquivos de formato.


    A maneira como o PowerShell estabelece um vínculo entre o tipo de um objeto e as exibições de formatação definidas é inspecionando a pstypenamespropriedade oculta:

    PS C:\> $obj.pstypenames
    System.Management.Automation.PSCustomObject
    System.Object
    

    O PowerShell simplesmente examina essa lista ancestral de tipos para ver se ela possui uma exibição de formatação correspondente para esse tipo.

    Isso significa que você pode enganar o PowerShell para formatar um objeto como se fosse de outro tipo, sem realmente interferir no sistema de tipo .NET subjacente.

    Para mostrar isso, vamos criar um controlador de serviço falso - um objeto que parece que algo Get-Servicepoderia ter retornado, mas na verdade não é:

    PS C:\> $FauxService = New-Object psobject -Property @{
    >>>   "Name"        = "FakeService3000"
    >>>   "Status"      = "Faking"
    >>>   "DisplayName" = "TrustworthyService"
    >>>   "TrueName"    = "Really a fake"
    >>>   "Author"="Clever Genius"
    >>> }
    PS C:\> $FauxService
    
    
    Status      : Faking
    Name        : FakeService3000
    Author      : Clever Genius
    DisplayName : TrustworthyService
    TrueName    : Really a fake
    

    Conforme descrito acima, o PowerShell mostra a saída de Format-Listdesde que psobjecttem 5 propriedades.

    Agora, vamos tentar injetar um nome de tipo:

    PS C:\> $FauxService.pstypenames.Insert(0,"System.ServiceProcess.ServiceController")
    PS C:\> $FauxService
    
    Status   Name               DisplayName
    ------   ----               -----------
    Faking   FakeService3000    TrustworthyService
    

    Voilá!

    • 5

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Você pode passar usuário/passar para autenticação básica HTTP em parâmetros de URL?

    • 5 respostas
  • Marko Smith

    Ping uma porta específica

    • 18 respostas
  • Marko Smith

    Verifique se a porta está aberta ou fechada em um servidor Linux?

    • 7 respostas
  • Marko Smith

    Como automatizar o login SSH com senha?

    • 10 respostas
  • Marko Smith

    Como posso dizer ao Git para Windows onde encontrar minha chave RSA privada?

    • 30 respostas
  • Marko Smith

    Qual é o nome de usuário/senha de superusuário padrão para postgres após uma nova instalação?

    • 5 respostas
  • Marko Smith

    Qual porta o SFTP usa?

    • 6 respostas
  • Marko Smith

    Linha de comando para listar usuários em um grupo do Windows Active Directory?

    • 9 respostas
  • Marko Smith

    O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL?

    • 3 respostas
  • Marko Smith

    Como determinar se uma variável bash está vazia?

    • 15 respostas
  • Martin Hope
    Davie Ping uma porta específica 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    kernel O scp pode copiar diretórios recursivamente? 2011-04-29 20:24:45 +0800 CST
  • Martin Hope
    Robert ssh retorna "Proprietário incorreto ou permissões em ~/.ssh/config" 2011-03-30 10:15:48 +0800 CST
  • Martin Hope
    Eonil Como automatizar o login SSH com senha? 2011-03-02 03:07:12 +0800 CST
  • Martin Hope
    gunwin Como lidar com um servidor comprometido? 2011-01-03 13:31:27 +0800 CST
  • Martin Hope
    Tom Feiner Como posso classificar a saída du -h por tamanho 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent Como determinar se uma variável bash está vazia? 2009-05-13 09:54:48 +0800 CST

Hot tag

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve