31 March 2015

Fix "System.Object[]" output when exporting to csv

export data to csv is sometimes broken because everything that is passed to Export-Csv cmdlet is casted as a string before the export.

one solution is to create a pscustomobject and use -Join operator on the troubeling property:


$user = Get-ADUser username -Properties memberof
[pscustomobject]@{
    DN = $user .DistinguishedName
    GivenName = $user .GivenName
    MemberOf = $user .MemberOf -Join ','
    Name = $user .Name
    SamAccountName = $user .SamAccountName
    UserPrincipalName = $user .UserPrincipalName
} | Export-Csv -NoTypeInformation .\user.csv





for a better arrangment Out-String cmdlet can be use in replace of Join operator

$user = Get-ADUser user  -Properties memberof
[pscustomobject]@{
    DN = $user.DistinguishedName
    GivenName = $user.GivenName
    MemberOf = ($user.MemberOf | Out-String).Trim()
    Name = $user.Name
    SamAccountName = $user.SamAccountName
    UserPrincipalName = $user.UserPrincipalName
} | Export-Csv -NoTypeInformation .\user.csv


Find domain controller with user replicated

When i'm creating a new user at the same time i'm trying to modify different properties on him like setup a manager, job title, include him in some groups ...and so on.

Sometimes the user is not replicated on all domain controllers in domain fast enough and any command after the New-ADUser will fail (with ADIdentityNotFoundException).

To overcome this problem i created a function that will find a domain controller on witch the user was replicated and used in the next commands as an argument for the Server parameter.


function Find-ReplicatedDC{
    param([string]$UserName)

    $AllDCinDomain = Get-ADDomainController -Filter *

    do{
        foreach( $DC in $AllDCinDomain){
                try{
                    $ADUser = Get-ADUser -Identity $username -Server $DC.HostName
                    $ReplicatedDC = $DC.HostName
                    break
                }
                catch{
                    Start-Sleep -Seconds 1
                }
        }
    }
    while(!$ReplicatedDC)

    return $ReplicatedDC
}

18 March 2015

Show tcp connections

netsh interface ipv4 show tcpconnections