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");
3

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.