Home > Mobile >  Get Column values from text file
Get Column values from text file

Time:10-01

Below is the text file data I have

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
  Disk 0    Online          100 GB  1024 KB         
  Disk 1    Online         6144 MB  1024 KB         
  Disk 2    Online          200 GB  1024 KB         
  Disk 3    Online           10 GB  1024 KB         


I want to put this data in csv like below, removing the last 2 columns and adding the server value


server  Disk ###  Status         Size     Free     
------  --------  -------------  -------  ------- 
s1      Disk 0    Online          100 GB  1024 KB         
s1      Disk 1    Online         6144 MB  1024 KB         
s1      Disk 2    Online          200 GB  1024 KB         
s1      Disk 3    Online           10 GB  1024 KB         


below is the code

$list = Get-Content -Path "C:\server.txt"
foreach($server in $list)
{

    $diskpart = cmd /c 'echo list disk | diskpart'
    
}

$Lines = $diskpart
$Out = $False
$Line=@()
ForEach ($Line In $Lines)
{
    If ($Line -match 'DISKPART>') 
    {
        $Out = $False
    }
    If ($Out -eq $True) 
    {
        $Line | Out-File "C:\d.txt" -Append
    }
    If ($Line -match 'DISKPART>') 
    {
        $Out = $True
    }
}

$data  = Import-Csv -Path C:\d.txt

I tried reading line using foreach,but getting output with headers and ---

Disk ###  Status         Size     Free     Dyn  Gpt
---------------------------------------------------
Disk 0    Online          100 GB  1024 KB          

Please let me know how can I extract columns from text file and append the servername to it. Need some idea to do this

CodePudding user response:

One way of converting this into a CSV file is like below.

Assuming you have the output from diskpart in a string array $lines and the current server is called 's1' :

$result = switch -Regex ($lines) {
    '^\s*Disk \d'  {
        $disk,$status,$size,$free = $_.Trim() -split '\s{2,}'
        [PsCustomObject]@{
           'Server'   = $server  # 's1' in this example
           'Disk ###' = $disk
           'Status'   = $status
           'Size'     = $size
           'Free'     = $free
        }
    }
}

# output on console screen
$result | Format-Table -AutoSize

# output to CSV file
$result | Export-Csv -Path 'C:\diskinfo.csv' -NoTypeInformation

Result on screen:

Server Disk ### Status Size    Free   
------ -------- ------ ----    ----   
s1     Disk 0   Online 100 GB  1024 KB
s1     Disk 1   Online 6144 MB 1024 KB
s1     Disk 2   Online 200 GB  1024 KB
s1     Disk 3   Online 10 GB   1024 KB

P.S. It is strongly not recommended to use Out-File to build a CSV file. Use that only if other options are not available. To create CSV use Export-Csv

  • Related