Powershell使用三个coumns导出为CSV

时间:2016-02-17 22:43:04

标签: csv powershell invoke-command

函数getServerInfo {     $ serverList = Get-Content -Path“C:\ Users \ username \ Desktop \ list.txt”

$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。请帮忙。谢谢!

2 个答案:

答案 0 :(得分:0)

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

var AcceptedItems = [];
for (var i = 0, len = arr.length; i < len; i++) {
  var match = arr[i].match(/[a-zA-Z]{3,}/);
  if (match) {
    AcceptedItems.push(match[0]);
  }
}

答案 1 :(得分:0)

要使用Export-CSV cmdlet导出到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