如何在PowerShell中格式化文件

时间:2013-07-31 10:23:03

标签: powershell

我正在尝试格式化一个文件,如下所示。

IPAddresss    HostName                  Result
none sinuiy01.infra.go2uti.com                NotValid
none  sinuid20.devtst.go2uti.com                NotValid
172.21.40.204  USEM9999.essilor.res                  Success
172.21.40.204  webmail.nscorp.com                NotValid
172.21.40.204  nsc.nscorp.com                Unsuccess
172.21.40.204  bp-nsc.nscorp.com                NotValid

但需要如下结果: -

IPAddresss         HostName                                Result
none               sinuiy01.infra.go2uti.com               NotValid
none               sinuid20.devtst.go2uti.com              NotValid
172.21.40.204      USEM9999.essilor.res                    Success
172.21.40.204      webmail.nscorp.com                      NotValid
172.21.40.204      nsc.nscorp.com                          Unsuccess
172.21.40.204      bp-nsc.nscorp.com                       NotValid

您能否建议我应该使用哪些功能来获得上述结果?

以下是剧本: -

这是我正在处理的脚本

"IPAddresss    HostName                  Result" | Out-File -Append D:\CEP\testlogging.txt 
$lines = Get-Content myfile.txt | Where {$_ -notmatch "((^#)|(^\s+$))"}
foreach ($line in $lines) {
    $fields = $line -split '\s+'
    $ip = $fields[0]
    for ($i = 1; $i -lt $fields.Length; $i++) {
        $ESXHost = $fields[$i]
    echo "Host $ESXHOST"
    try
        {
        $currentConnection = Test-Connection $ESXHost -ErrorAction stop

        if($currentConnection.Count -gt 0)
            {
            $hostIP = ($currentConnection)[$i].IPV4Address.IPAddressToString

            echo "hostIp $hostIP"
                if ($hostIP -eq $ip) 
                { 

                "$hostIP  $ESXHost                  Success" | Format-Table -Wrap -AutoSize | Out-File -Append D:\CEP\testlogging.txt 



                }
                else 
                {

                "$hostIP  $ESXHost                  Unsuccessful" | Format-Table -Wrap -AutoSize | Out-File -Append D:\CEP\testlogging.txt
                }
            }

        }

2 个答案:

答案 0 :(得分:1)

当您使用字符串将数据输出到文本文件时,您可以尝试以下字符串格式化以均匀地分隔字符串中的变量。在下面的示例中,每个值之间的间距为25个字符:

[string]::Format("{0,-25}{1,-25}{2,-25}",$hostIP,$ESXHost,"Success") | Out-File -Append D:\CEP\testlogging.txt

语法:

$I - This is the parameter number to be inserted (0 or more)
$C - The number of total characters before the next variable.
(Negative numbers make the word start from the left)

[string]::Format("{$I,$C}",Parameter1,Parameter2)

还有一种使用-f运算符执行相同操作的简便方法:

"{0,-25}{1,-25}{2,-25}" -f $hostIP,$ESXHost,"Success" | Out-File -Append D:\CEP\testlogging.txt

答案 1 :(得分:1)

你可以尝试:

Get-Content C:\temp\t1.txt | % {$_ -replace ' +',' ' }| % { $parts = $_.split(' '); Write-output ("{0,-15}{1,-30}{2,-8}" -f $parts[0],$parts[1],$parts[2])} | Out-File  C:\temp\t2.txt