El uso de Powershell OUT-FILE cambia los datos


1

Aquí hay un código de muestra que muestra información del disco físico en la consola (con muchas gracias a guyc@computerperformance.co.uk):

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]
      }
    }
  }
}

Pero quiero que la salida de la consola vaya a un archivo TXT. Cuando presento "Out-File", no sale nada en la consola, pero el resultado es diferente. No se divide (en GB) y muestra campos diferentes a los que seleccioné. Esto es lo que cambié:

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]
      }
    }
  }
}

Así que cambié la forma en que implementé el OUT-FILE (poniéndolo en cada línea de salida):

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 
      }
    }
  }
}

Ahora no solo se divide entre la consola (encabezados) y el archivo TXT (valores), sino que también muestra diferentes variables que antes, y no hace la división, solo muestra el número de bytes, no GB.

¿Alguien puede aclararme el uso de OUT-FILE, o una mejor opción?

¡Gracias!

Respuestas:


1

¿Alguien me puede dejar de usar out-file? ¿hay otras opciones?

Simplemente puede usar el operador de redirección de PowerShell >>al final del script.

    } >> DiskInfo.txt

Si quiere usarlo out-file, póngalo también al final del guión.

    } | out-file Diskinfo.txt

Notas:

  • Cambiar DiskInfo.txtsegún corresponda.
  • La ventaja de usar out-filees que los parámetros se pueden agregar out-filepero no>>

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

Salida de ejemplo:

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.     

Fuente about_Redirection


Wow, eso fue casi demasiado fácil. Ojalá hubiera visto eso. Muchas gracias, realmente lo aprecio. Y, he aprendido, la manera fácil es la mejor.
— JCauble

No veo ningún lugar donde pueda "aceptar la respuesta" en ningún lugar de la pantalla. Apúntame y obtendrás los puntos, con mi agradecimiento.
— JCauble

ahh, lo tengo no es obvio. Pero entonces, soy un novato en el foro. Gracias.
— JCauble

en lugar de >> DiskInfo.txtusted también puede usar | out-file D:\diskinfo.txtpara seguir con la forma más "poderosa". Otra ventaja de esto es que usted puede añadir parámetros a out-file, pero no se puede añadir parámetros a>>
— Simons

@SimonS Hmm. Pensé que lo intenté y obtuve un error. Debo haber hecho algo mal. Gracias por la nota, actualizaré la respuesta.
— DavidPostill
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.