1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

One Liner

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

  1. Nelix
    Honorary Member

    Nelix Gigabyte Poster

    1,415
    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, 70-410, 70-411, 70-337, 70-347
    WIP: 74-409
  2. Shadowrunner

    Shadowrunner Nibble Poster Premium Member

    62
    1
    32
    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
     
    Certifications: GCSE IT
    WIP: VCP6-DCV

Share This Page

Loading...