Usando o Powershell OUT-FILE muda dados

1

Aqui está um código de exemplo que exibe informações do disco físico no console (com muito obrigado a [email protected]):

Get-WmiObject Win32_DiskDrive | % {
  $disk = $_
  $partitions = "ASSOCIATORS OF " +
                "{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " +
                "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
  Get-WmiObject -Query $partitions | % {
    $partition = $_
    $drives = "ASSOCIATORS OF " +
              "{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " +
              "WHERE AssocClass = Win32_LogicalDiskToPartition"
    Get-WmiObject -Query $drives | % {
      New-Object -Type PSCustomObject -Property @{
        Disk        = $disk.DeviceID
        DiskModel   = $disk.Model
        Partition   = $partition.Name
        DriveLetter = $_.DeviceID
        VolumeName  = $_.VolumeName
        Size        = "{0:N}" -f ($_.Size/1GB) -as [float]
            FreeSpace   = "{0:N}" -f ($_.FreeSpace/1GB) -as [float]
      }
    }
  }
}

Mas eu quero que a saída do console vá para um arquivo TXT. Quando eu introduzo "Out-File", nada acontece no console, mas a saída é diferente. Não divide (em GB) e exibe campos diferentes do que eu selecionei. Aqui está o que eu mudei:

Get-WmiObject Win32_DiskDrive | % {
  $disk = $_
  $partitions = "ASSOCIATORS OF " +
                "{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " +
                "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
  Get-WmiObject -Query $partitions | % {
    $partition = $_
    $drives = "ASSOCIATORS OF " +
              "{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " +
              "WHERE AssocClass = Win32_LogicalDiskToPartition"
    Get-WmiObject -Query $drives | **Out-File -filepath "d:\DiskInfo.txt" -append** | % {
      New-Object -Type PSCustomObject -Property @{
        Disk        = $disk.DeviceID
        DiskModel   = $disk.Model
        Partition   = $partition.Name
        DriveLetter = $_.DeviceID
        VolumeName  = $_.VolumeName
        Size        = "{0:N}" -f ($_.Size/1GB) -as [float]
        FreeSpace   = "{0:N}" -f ($_.FreeSpace/1GB) -as [float]
      }
    }
  }
}

Então eu mudei como eu implementei o OUT-FILE (colocando-o em cada linha de saída):

Get-WmiObject Win32_DiskDrive | % {
  $disk = $_
  $partitions = "ASSOCIATORS OF " +
                "{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " +
                "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
  Get-WmiObject -Query $partitions | % {
    $partition = $_
    $drives = "ASSOCIATORS OF " +
              "{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " +
              "WHERE AssocClass = Win32_LogicalDiskToPartition"
    Get-WmiObject -Query $drives | % {
      New-Object -Type PSCustomObject -Property @{
        Disk        = $disk.DeviceID | Out-File -filepath "d:\DiskInfo.txt" -append  
        DiskModel   = $disk.Model | Out-File -filepath "d:\DiskInfo.txt" -append 
        Partition   = $partition.Name | Out-File -filepath "d:\DiskInfo.txt" -append 
        DriveLetter = $_.DeviceID | Out-File -filepath "d:\DiskInfo.txt" -append 
        VolumeName  = $_.VolumeName | Out-File -filepath "d:\DiskInfo.txt" -append 
        Size        = "{0:N}" -f ($_.Size/1GB) -as [float] | Out-File -filepath "d:\DiskInfo.txt" -append 
        FreeSpace   = "{0:N}" -f ($_.FreeSpace/1GB) -as [float] | Out-File -filepath "d:\DiskInfo.txt" -append 
      }
    }
  }
}

Agora, ele não apenas divide entre o console (títulos) e o arquivo TXT (valores), mas também exibe variáveis diferentes de antes, e não faz a divisão, apenas mostra o número de bytes, não GB.

Alguém pode me definir diretamente usando OUT-FILE - ou uma opção melhor?

Obrigado!

    
por JCauble 24.05.2016 / 23:15

1 resposta

1

Alguém pode me definir diretamente usando out-file ? Existem outras opções?

Você pode usar o redirecionamento do operador do PowerShell >> no final do script .

    } >> DiskInfo.txt

Se você quiser usar out-file , coloque-o no final do script.

    } | out-file Diskinfo.txt

Notas:

  • Altere DiskInfo.txt conforme apropriado.
  • A vantagem de usar out-file é que os parâmetros podem ser adicionados a out-file , mas não >>

Get-Disk.ps1:

Get-WmiObject Win32_DiskDrive | % {
  $disk = $_
  $partitions = "ASSOCIATORS OF " +
                "{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " +
                "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
  Get-WmiObject -Query $partitions | % {
    $partition = $_
    $drives = "ASSOCIATORS OF " +
              "{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " +
              "WHERE AssocClass = Win32_LogicalDiskToPartition"
    Get-WmiObject -Query $drives | % {
      New-Object -Type PSCustomObject -Property @{
        Disk        = $disk.DeviceID
        DiskModel   = $disk.Model
        Partition   = $partition.Name
        DriveLetter = $_.DeviceID
        VolumeName  = $_.VolumeName
        Size        = "{0:N}" -f ($_.Size/1GB) -as [float]
            FreeSpace   = "{0:N}" -f ($_.FreeSpace/1GB) -as [float]
      }
    }
  }
} >> DiskInfo.txt

Exemplo de saída:

PS F:\test> .\Get-Disk
PS F:\test> type .\DiskInfo.txt


Size        : 449.46
Partition   : Disk #0, Partition #2
FreeSpace   : 65.36
Disk        : \.\PHYSICALDRIVE0
DiskModel   : WDC WD5000LPVX-08V0TT5
VolumeName  :
DriveLetter : C:

Size        : 59.61
Partition   : Disk #2, Partition #0
FreeSpace   : 37.13
Disk        : \.\PHYSICALDRIVE2
DiskModel   : SanDisk Cruzer USB Device
VolumeName  : SANDISK
DriveLetter : E:

Size        : 2794.51
Partition   : Disk #1, Partition #0
FreeSpace   : 1648.17
Disk        : \.\PHYSICALDRIVE1
DiskModel   : Seagate Expansion Desk USB Device
VolumeName  : Expansion
DriveLetter : F:



PS F:\test>

about_Redirection

The Windows PowerShell redirection operators are as follows.

Operator  Description                Example  
--------  ----------------------     ------------------------------
>         Sends output to the        Get-Process > Process.txt
          specified file.

>>        Appends the output to      dir *.ps1 >> Scripts.txt
          the contents of the  
          specified file.

2>        Sends errors to the        Get-Process none 2> Errors.txt
          specified file.

2>>       Appends errors to          Get-Process none 2>> Save-Errors.txt
          the contents of the 
          specified file.

2>&1      Sends errors (2) and       Get-Process none, Powershell 2>&1
          success output (1) 
          to the success 
          output stream.

3>        Sends warnings to the      Write-Warning "Test!" 3> Warnings.txt
          specified file.

3>>       Appends warnings to        Write-Warning "Test!" 3>> Save-Warnings.txt
          the contents of the 
          specified file.

3>&1      Sends warnings (3) and     function Test-Warning 
          success output (1)         {  Get-Process PowerShell; 
          to the success                Write-Warning "Test!" }
          output stream.             Test-Warning 3>&1

4>        Sends verbose output to    Import-Module * -Verbose 4> Verbose.txt
          the specified file.

4>>       Appends verbose output     Import-Module * -Verbose 4>> Save-Verbose.txt
          to the contents of the 
          specified file.

4>&1      Sends verbose output (4)   Import-Module * -Verbose 4>&1
          and success output (1)    
          to the success output
          stream.              

5>        Sends debug messages to    Write-Debug "Starting" 5> Debug.txt
          the specified file.

5>>       Appends debug messages     Write-Debug "Saving" 5>> Save-Debug.txt
          to the contents of the 
          specified file.

5>&1      Sends debug messages (5)   function Test-Debug 
          and success output (1)     { Get-Process PowerShell 
          to the success output        Write-Debug "PS" }
          stream.                    Test-Debug 5>&1

*>        Sends all output types     function Test-Output
          to the specified file.     { Get-Process PowerShell, none  
                                       Write-Warning "Test!"
*>>       Appends all output types     Write-Verbose "Test Verbose"
          to the contents of the       Write-Debug "Test Debug" } 
          specified file.            
                                     Test-Output *> Test-Output.txt
*>&1      Sends all output types     Test-Output *>> Test-Output.txt
          (*) to the success output  Test-Output *>&1      
          stream.     

Fonte about_Redirection

    
por 24.05.2016 / 23:46

Tags