1

I need to run a powershell command from C++ application. This powershell command need to redirect powershell script output to a file using UFT16 encoding.

I run the following command, but out.txt is not in UFT16, but seems in UTF8.

powershell.exe -File  myps.ps1 > out.txt

I also tried the following. But the error is "'out-file' is not recognized as an internal or external command operable program or batch file."

powershell.exe -File myps.ps1 | out-file "enctest.txt" -encoding unicode

Maybe should use -Command? How to do this?

2
  • Maybe you should include the relevant code so we have a better chance of pointing out the problem. Commented Nov 30, 2015 at 23:30
  • Write-Host “Hello, World!” is the content of my powershell script Commented Dec 1, 2015 at 1:15

1 Answer 1

1

As you already know, Out-File is a PowerShell cmdlet, so it won't make sense in the context of a process argument (if you're trying to launch powershell.exe as a new process directly), nor will it make sense to cmd.exe (default shell when you invoke a system() call).

Maybe should use "-Command"? How to do this?

Absolutely!

Something like this should do:

powershell.exe -Command "& C:\path\to\my.ps1 | Out-File enctest.txt -Encoding unicode"

The > operator would also work with -Command, as output redirection encoding defaults to UTF16LE (inside PowerShell at least):

powershell.exe -Command "& C:\path\to\my.ps1 > enctest.txt"
Sign up to request clarification or add additional context in comments.

3 Comments

powershell.exe -Command "& C:\path\to\my.ps1 | Out-File enctest.txt -Encoding unicode" didn't redirect the output of the script to enctest.txt, it output to the console instead. C:\temp>powershell.exe -Command "& C:\temp\myps.ps1 | Out-File enctest.txt -Encoding unicode" Hello, World!
Does myps.ps1 contain something like Write-Host "Hello World!"? Write-Host writes directly to the host application (ie. the console screen buffer), not to stdout. It won't work. Use Write-Output (echo) instead of Write-Host
I tried "Write-Output" and it works. Thanks! But the problem is that in reality, I don't have control of the script. I only write code to redirect the output of the script to file. What if myps.ps1 contains Write-Host instead of Write-Output, is there anyway to do the same thing? "powershell.exe -File myps.ps1 > out.txt" works for Write-Host except it doesn't do unicode.

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.