0

I am using a script to update the data of Active Directory users

Import-Csv -Path $Path | foreach-object {Set-ADUser -Identity ($_.user) -Department $_.Department -Title $_.Title -Company $_.Company -MobilePhone $_.MobilePhone ...etc (the required data to modify)}

I want the script to write the errors in the update of an "x" user's, to see whose user wasn't updated.

I'm creating a C# app to write a personalized script, and still need to make the error log.

The idea is to create this log in a specified path. I don't know if this can be made in the script it self.

I'm using this PowerShell method I have found here:

PowerShell ps = PowerShell.Create();
ps.AddScript(script);

IAsyncResult result = ps.BeginInvoke();

// do something else until execution has completed.
// this could be sleep/wait, or perhaps some other work
while (result.IsCompleted == false)
{
  //think i can make that here, but can´t see how
}   
MessageBox.Show("Complete");
double-beep
  • 5,031
  • 17
  • 33
  • 41
BensYi
  • 23
  • 6
  • https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.powershell.streams?view=pscore-6.2.0#System_Management_Automation_PowerShell_Streams - Grab the error stream – Michael Jones Feb 12 '20 at 14:39
  • Does this answer your question? [Import-CSV for Active Directory Object Already Exists Error](https://stackoverflow.com/questions/32377668/import-csv-for-active-directory-object-already-exists-error) – Jimmy Smith Feb 12 '20 at 14:41
  • 1
    Welcome to stackoverflow. Please ensure to ask clear questions. I'm not sure if you are asking how to log errors in powershell or c# – CarComp Feb 12 '20 at 14:51

2 Answers2

0

Perhaps something like this can be used to get you going quickly. Without seeing the script, i'll have to simply assume that you have a ps1 file, and you want the errors it generates:

.\myhugescript.ps1 | Out-File -Path D:\log.log -Append
$(.\myhugescript.ps1) | Out-File -Path D:\log.log
CarComp
  • 1,929
  • 1
  • 21
  • 47
0

You can write errors to a file like this:

$logFilePath = "..."
Import-Csv -Path $Path | foreach-object {
    Try {
        $user = $_.user
        Set-ADUser -Identity $user -Department $_.Department -Title $_.Title -Company $_.Company -MobilePhone $_.MobilePhone ...etc (the required data to modify)
    } Catch [system.exception] {
        $t = get-date -format "yyyy-MM-dd HH:mm:ss"
        $msg = "$t -- Error updating user $user: $($_.Exception.Message)`n"
        $msg | Out-File -Append $logFilePath
    }
}

You could also replace Out-File with Write-Error to write to the stderr stream and then read that stream directly in the C# code, to save the disk I/O. There's an example of what that looks like here:

Get Powershell command's output when invoked through code

Replace the Progress stream in that example with the Error stream.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794