如何使用两个 echo 命令使用 PowerShell 在一行上打印数据 [英] How to use two echo commands to print data on one line using PowerShell

查看:382
本文介绍了如何使用两个 echo 命令使用 PowerShell 在一行上打印数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我用来查找用户创建日期和上次登录日期的代码,然后将其写入 .csv 文件.

Below is the code I'm using to find users created date and last logon date which is then written to a .csv file.

$users=Get-ADuser -SearchBase "OU=testou1,dc=US,dc=ITOPS,dc=COM" -Filter * -properties samaccountname,lastlogondate,Created    
$forloop = foreach($user in $users) {    
         echo $user.samaccountname    
          echo $user.created    
        echo $user.lastlogondate    
        }    
$forloop | Out-file c:\bin\exporting.csv -Append 

此代码在新行上打印每个项目,如下所示:

This code prints each item on a new line like this:

username  
created date  
last logon date  

但我希望所有内容都在具有不同列的同一行上:

But I want it all on the same line with different columns:

username createdDate lastLogonDate

推荐答案

我将创建一个具有名称和值属性的对象数组.这将很好地导出为 CSV.

I would create an an array of objects with name and value properties. That will export nicely to CSV.

请记住,我是在手机上写的,稍后我会在我的 ISE 中检查它,但我已经在下面修改了您的代码:

Bear in mind I'm writing this on a phone, I'll check it in my ISE later, but I've amended your code below:

$users=Get-ADuser -SearchBase "OU=testou1,dc=US,dc=ITOPS,dc=COM" -Filter * -properties samaccountname,lastlogondate,Created    

$array = @() #declare the array outside the loop

$forloop = foreach($user in $users) {    
$arrayrow = New-Object System.Object
     $arrayrow | Add-Member -type NoteProperty -name User -value $user.samaccountname    
      $arrayrow | Add-Member -type NoteProperty -name Created -value  $user.created    
    $arrayrow | Add-Member -type NoteProperty -name LastLogonDate -value $user.lastlogondate    
  $array += $arrayrow
    }    
$array | export-csv  -notype c:\bin\exporting.csv 

这篇关于如何使用两个 echo 命令使用 PowerShell 在一行上打印数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆