0

I'm not very knowledgeable with PowerShell, but I was wondering how you could write the output of the script (excerpt below) to a file in my local directory, instead of to the screen?

{
    $userEntry = $result.GetDirectoryEntry()
    Write-Host "User Name = " $userEntry.name
    foreach ($SPN in $userEntry.servicePrincipalName)
    {
        Write-Host "SPN = " $SPN       
    }
    Write-Host ""    
}
3

1 Answer 1

0

Replace Write-Host with Out-File with the -Append parameter:

{
    $userEntry = $result.GetDirectoryEntry()
    "User Name = $($userEntry.name)" | Out-File Output.txt -Append
    foreach ($SPN in $userEntry.servicePrincipalName)
    {
        "SPN = $SPN" | Out-File Output.txt -Append
    }
    "" | Out-File Output.txt -Append  
}

Out-File will write straight to the file, the Tee-Object will output both to the screen and to the file.

Sign up to request clarification or add additional context in comments.

4 Comments

Hello HAL9256. I tried your code, but get the following error:
Unexpected token 'userEntry' in expression or statement. + "User Name = "$userEntry <<<< .name | Out-File Output.txt -Append + CategoryInfo :ParserError: <userEntry:String> [], ParseException + FullyQualifiedErrorId : UnexpectedToken
Agh. I forgot to add a + so that it should be: "User Name = " + $userEntry.name The other way (imo better way) to do it is to wrap the object in a $() and put it inside the string, as you can better control the formatting. I have edited the Answer to show this method.
Worked like a charm!!!!!! Much thanks HAL9256!!!! Take care. Cheers, John.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.