One Liner

Discussion in 'Scripting & Programming' started by Nelix, May 16, 2017.

  1. Nelix
    Honorary Member

    Nelix Gigabyte Poster

    1,416
    3
    82
    I really must brush up on my powershell.

    I have the following one-liner commandlet:

    Import-Csv D:\Temp\AUP.csv | Foreach-Object {Get-ADUser $_.SamAccountName | Select -Property SamAccountName, Enabled} | export-csv D:\Temp\AUPRESULT.csv –notype –append

    IT works great, however when it comes across a SamAccountName that does not exist, it throws an error on screen but writes nothing to the output file.

    I would like it to add something like "SamAccountName does not exist" to the output file, I would also like to keep it to a commandlet rather than a script.

    Can anyone help?

    Cheers
     
    Certifications: A+, 70-210, 70-290, 70-291, 74-409, 70-410, 70-411, 70-337, 70-347
    WIP: 70-346
  2. Shadowrunner

    Shadowrunner Nibble Poster Premium Member

    68
    7
    37
    I don't think it's something you can do in a one liner unfortunately. You need a script with a Try/Catch block, something like:


    Import-Module ActiveDirectory
    $Users = Import-CSV c:\Temp\aup.csv

    $Output = Foreach ($User in $Users){

    Try
    {Get-ADUser $User.SamAccountName | Select -Property SamAccountName, Enabled}

    Catch
    {Write-Host "User $($User.SamAccountName) does not exist"}

    }

    $Output | Export-Csv C:\Temp\AUPResult.csv -NoTypeInformation



    I don't think you can include the caught errors in the output CSV though, as they don't fit the format. It might be possible with a much longer script to manipulate the data, but that's probably unnecessary here.

    SR
     

Share This Page

Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.