2016-02-17 33 views
0

功能getServerInfo {$ SERVERLIST =获取内容-Path “C:\ Users \用户名\桌面\ LIST.TXT”Powershell的导出为CSV三个coumns

$cred = Get-Credential -Credential "username" 
foreach($server in $serverList) 
{ 

    $osVersion = gwmi win32_operatingSystem -ComputerName $server -ErrorAction SilentlyContinue 
    if($osVersion -eq $null) 
    { 
     $osVersion = "cannot find osversion" 

    } 

    $psv = Invoke-Command -ComputerName $server -ScriptBlock {$PSVersionTable.PSVersion.Major} -ErrorAction Ignore 

    if($psv -eq $null) 
    { 

     $psv2 = Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock {$PSVersionTable.PSVersion.Major} -ErrorAction Ignore 
     Write "$server has $($osVersion.Caption)and PSVersion is $psv2" 
    } 
    else{ 

    Write "$server has $($osVersion.Caption)and PSVersion is $psv" 

    } 

} 

}

我我试图创建一个3列csv文件。
第一列将有$ server,第二列将有$ osVersion,第三列将有$ psv。请帮忙。谢谢!

+0

如果提供了一个解决问题的方法的两个答案之一,请把它标记为接受的答案,使用户未来可以找到它,如果他们有类似的问题。 – TheMadTechnician

回答

0

而不是使用foreach循环,请考虑使用ForEach-Object cmdlet,以便可以将结果传送到其他命令。在ForEach-Object脚本块的内部,您可以计算出您需要的3个值,然后使用字符串插值可以轻松创建CSV字符串。然后可以将结果传送到相应的输出文件。

Get-Content -Path C:\Users\username\Desktop\list.txt | ForEach-Object { 
    $Server = $_ 
    $OSVersion = gwmi Win32_OperatingSystem -ComputerName $Server -ErrorAction SilentlyContinue 
    $PSVersion = Invoke-Command -ComputerName $Server -ScriptBlock { $PSVersionTable.PSVersion.Major } 

    "$Server,$OSVersion,$PSVersion" 
} | Out-File outputFilename.csv 
+0

感谢您的反馈! – Ninja

0

要使用Export-CSV小命令导出到CSV,PowerShell的期望对象的一组相同的属性,以输出的阵列。对于你的情况,你可以做到这一点相当简单的,例如:

$cred = Get-Credential -Credential "username" 
$AllServers=foreach($server in $serverList) 
{ 
    [PSCustomObject]@{ 
     'Server' = $Server 
     'osVersion' = gwmi win32_operatingSystem -ComputerName $server -ErrorAction SilentlyContinue | Select -Expand Caption 
     'psv' = Invoke-Command -ComputerName $server -ScriptBlock {$PSVersionTable.PSVersion.Major} -ErrorAction Ignore -Credential $cred 
    } 

} 

$AllServers | Export-Csv c:\path\to\output.csv -notype 
+0

感谢您的反馈! – Ninja