删除powershell中输出的命令之间的空格

时间:2015-02-17 12:28:56

标签: powershell

我有一个脚本,我想删除输出结果中默认为powershell put的空格。这有什么办法吗?

=======Computer1=======
Microsoft Windows 8.1 Pro


Name         : Computer1
Model        : Vostro 200
Manufacturer : Dell Inc.





SerialNumber : 012345

这就是我想要的:

=======Computer1=======
Microsoft Windows 8.1 Pro
Name         : Computer1
Model        : Vostro 200
Manufacturer : Dell Inc.
SerialNumber : 012345

这是我的剧本:

$Computers=Import-Csv C:\Powershell\test.csv
$ResultsPath="C:\Powershell\test.txt"


foreach ($i in $Computers.Name) {
         "="*7 + $i + "="*7 
         if (Test-Connection $i -quiet) {
         (Get-WmiObject -class Win32_OperatingSystem -ComputerName $i).Caption
         Get-WmiObject -class Win32_Computersystem -ComputerName $i | Select-Object Name, Model, Manufacturer | Format-List
         Get-WmiObject win32_SystemEnclosure -ComputerName $i | Select-Object SerialNumber | Format-List }
         else { "nothing" }
         }

2 个答案:

答案 0 :(得分:0)

将输出转换为字符串并修剪它:

     "="*7 + $i + "="*7 
     if (Test-Connection $i -quiet) {
         (Get-WmiObject -class Win32_OperatingSystem -ComputerName $i).Caption
         (Get-WmiObject -class Win32_Computersystem -ComputerName $i | Select-Object Name, Model, Manufacturer | Format-List | Out-String).Trim()
         (Get-WmiObject win32_SystemEnclosure -ComputerName $i | Select-Object SerialNumber | Format-List | Out-String).Trim() }
     else { "nothing" }

答案 1 :(得分:0)

虽然Trim会做你需要的,但这不是PowerShell方式。这是经过修改的脚本,它在内部处理对象并以您希望的方式写入输出。

$Computers = Import-Csv 'C:\Powershell\test.csv'
$ResultsPath = 'C:\Powershell\test.txt'

foreach ($i in $Computers.Name) {
    $Header = '='*7 + $i + '='*7
    Write-Output $Header

    if (Test-Connection $i -quiet)
    {
        $Os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $i | Select-Object -ExpandProperty Caption
        $Info = Get-WmiObject -Class Win32_Computersystem -ComputerName $i  | Select-Object Name, Model, Manufacturer
        $Sn = Get-WmiObject -Class Win32_SystemEnclosure -ComputerName $i | Select-Object -ExpandProperty SerialNumber

        $PC = New-Object -TypeName psobject -Property @{
            OperatingSystem = $Os
            Name = $Info.Name
            Model = $Info.Model
            Manufacturer = $Info.Manufacturer
            SerialNumber = $Sn
        }   | Select-Object OperatingSystem, Name, Model, Manufacturer, SerialNumber

        Write-Output ($PC | Format-List | Out-String).Trim()
    }
    else
    {
        Write-Output 'nothing'
    }
}