I am trying to create virtual hosts with a Powershell script. It works fine, but I am having trouble with the encoding. I have tried all the -encoding switch values allowed with no luck.
Here is my script
$hostName = $args[0];
if ($args -eq $null -or $args.Length -eq 0)
{
"No arguments. Supply the virtual host name as the first argument."
exit
}
if (!(Test-Path -path D:\wamp\$hostName))
{
$indexText = "<?php echo `"<h1>Holder for $hostName</h1>`";"
New-Item D:\wamp\$hostName -type directory
New-Item D:\wamp\$hostName\index.php -type file
Out-File -FilePath D:\wamp\$hostName\index.php -InputObject $indexText -Encoding UTF8
}
$hosts = Get-Content C:\Windows\System32\drivers\etc\hosts
$hosts = $hosts + "127.0.0.1 $hostName.localhost"
Out-File -FilePath C:\Windows\System32\drivers\etc\hosts -InputObject $hosts
$conf = Get-Content "C:\Program Files (x86)\wamp\bin\apache\Apache2.2.11\conf\extra\httpd-vhosts.conf"
$conf = $conf + "<VirtualHost *:80>"
$conf = $conf + " DocumentRoot `"D:/wamp/$hostName`""
$conf = $conf + " ServerName $hostName.localhost"
$conf = $conf + " ErrorLog `"logs/$hostName.localhost-error.log`""
$conf = $conf + " CustomLog `"logs/$hostName.localhost-access.log`" common"
$conf = $conf + "</VirtualHost>"
Out-File -FilePath "C:\Program Files (x86)\wamp\bin\apache\Apache2.2.11\conf\extra\httpd-vhosts.conf" -InputObject $conf -Encoding ascii
Write-Host "Restart wamp server to effect changes"
Has anybody managed to get this working reliably or am I on to a none-starter here? I can always use PHP instead 🙂
If the encoding is not correct then Apache refuses to start under wampserver. If I change the encoding in notepad++ to ANSI then everything works fine, but powershell doesn’t like -encoding ANSI.
using the
-Encoding OEMoption onOut-Fileseems to be a solution to this problem incase anybody else comes up against it.For example:-
Edit:-
I eventually solved this problem by rewriting the script in PHP as I could never get it to work consistently in Powershell. Here is my script incase others find it useful, it is designed to run from the command line eg:-
Will create a new virtual host call ‘www’.