powershellencodingimportappcmd

Use Powershell to import website with Chinese domain


I’m trying use PowerShell to add website from xml file.

When I just use CMD command

appcmd  add site /in < test.xml

The binding of website is 「測試.com.tw」and everything be fine.

But when I use Powershell

Get-Content test.xml | appcmd add site /in 

The binding will be 「???.com.tw」

Even if I change chcp to 65001 or use “-encoding utf8” when get-content, but nothing change and still can’t correct import a website with Chinese domain.

My server is 2008 R2 and Powershell 1.0

Does anyone know how I can fix it?


Solution

  • PowerShell uses the $OutputEncoding preference variable to determine the character encoding to use when sending data to external programs (such as appcmd) via the pipeline (what the external program receives via stdin, the standard input stream).

    In Windows PowerShell, $OutputEncoding defaults to ASCII(!), meaning that only characters in the 7-bit ASCII are correctly sent, and all characters outside that range are replaced with literal ? characters.

    You must set $OutputEncoding to match the encoding that appcmd expects when reading from stdin; according to your feedback, UTF-8 must be used:

    $OutputEncoding = [System.Text.Utf8Encoding]::new($false) # BOM-less UTF-8
    
    Get-Content test.xml | appcmd add site /in 
    
    # Consider restoring the previous $OutputEncoding value
    

    Note: The above assumes that Get-Content properly recognizes the encoding of test.xml when reading from it; if not, use its -Encoding parameter to specify the file's encoding explicitly.

    Complementarily, when PowerShell reads output from external programs, it is the encoding stored in [Console]::OutputEncoding that determines how the output is decoded - see this answer.