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 ""    
}
John
  • 1
  • 1
    I commend your attention to the [`Out-File`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/out-file?view=powershell-6) and [`Tee-Object`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/tee-object?view=powershell-6) cmdlets, and also [Microsoft Docs on PowerShell redirection](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-6). – Jeff Zeitlin May 03 '19 at 15:52
  • Possible duplicate of [How to output something in PowerShell](https://stackoverflow.com/questions/2038181/how-to-output-something-in-powershell) – akokskis May 03 '19 at 15:56
  • @akokskis - Definitely closely related; I'm not sure I'd class it as a duplicate. – Jeff Zeitlin May 03 '19 at 17:23

1 Answers1

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.

HAL9256
  • 12,384
  • 1
  • 34
  • 46
  • Hello HAL9256. I tried your code, but get the following error: – John May 03 '19 at 16:04
  • Unexpected token 'userEntry' in expression or statement. + "User Name = "$userEntry <<<< .name | Out-File Output.txt -Append + CategoryInfo :ParserError: [], ParseException + FullyQualifiedErrorId : UnexpectedToken – John May 03 '19 at 16:12
  • 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. – HAL9256 May 03 '19 at 16:19
  • Worked like a charm!!!!!! Much thanks HAL9256!!!! Take care. Cheers, John. – John May 03 '19 at 16:32