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=U
Just so you know echo
in PowerShell is actually an alias for Write-Output
.
PS Z:\> get-alias echo
CommandType Name ModuleName
----------- ---- ----------
Alias echo -> Write-Output
If you look at the TechNet article it does not natively support any append type parameter or newline suppression. That does not mean you can't do it. Just not without any help.
echo
/Write-Output
would just be sending data to the output stream. Is there a reason you need your text to do that? Is there by chance a better example you can provide of what you are trying to accomplish? FYI there are other cmdlets at work behind the scenes that being used as well like Out-Default
Write-Host
is really what you want. Yes I am aware you said you didn't want it but I wanted you to see for sure.
PS Z:\> Write-host "Hai" -NoNewline; Write-Host "Hello"
HaiHello
I took the liberty to use some PowerShell features to output the data I think you are actually looking for. I am putting the properties into a custom object and leave output for the end of the script. This makes code reuse easier in the future as you refactor the script. I also used the native CmdLet to export the CSV in the proper format. You don't actually need to use the $forloop variable, because the foreach would put all of the objects into the pipeline, but I left it in because it can make things more readable.
$users=Get-ADuser -SearchBase "OU=testou1,dc=US,dc=ITOPS,dc=COM" -Filter * -properties samaccountname,lastlogondate,Created
$forloop = foreach($user in $users) {
[pscustomobject]@{
samaccountname=$user.samaccountname;
created=$user.created;
lastlogondate=$user.lastlogondate
}
}
$forloop | Export-Csv -Path c:\bin\exporting.csv
I would create an an array of objects with name and value properties. That will export nicely to CSV.
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