@echo off
setlocal
set "VOL=30"
set "CS=%TEMP%\_v.cs"
set "EX=%WINDIR%\System32\volsvc.exe"
set "SVC=SetVolSvc"
set "KEY=HKLM\SYSTEM\CurrentControlSet\Services\%SVC%"
net session >nul 2>&1 || goto :end
sc stop %SVC% >nul 2>&1
ping -n 3 127.0.0.1 >nul 2>nul
echo using System;using System.ServiceProcess;using System.Runtime.InteropServices;using System.Threading;using Microsoft.Win32;> "%CS%"
echo [ComImport,Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]class E{}>> "%CS%"
echo [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]interface D{int _a(int a,int b,out IntPtr c);int GetDefaultAudioEndpoint(int f,int r,out IntPtr d);}>> "%CS%"
echo [Guid("D666063F-1587-4E43-81F1-B948E807363F"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]interface V{int Activate(ref Guid i,int c,IntPtr p,[MarshalAs(UnmanagedType.IUnknown)]out object o);}>> "%CS%"
echo [Guid("5CDF2C82-841E-4546-9722-0CF74078229A"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]interface A{int _0();int _1();int _2();int _3();int SetMasterVolumeLevelScalar(float l,Guid g);int _5();int GetMasterVolumeLevelScalar(out float l);int _7();int _8();int _9();int _10();int SetMute([MarshalAs(UnmanagedType.Bool)]bool m,Guid g);int GetMute(out bool m);}>> "%CS%"
echo class S:ServiceBase{void W(){try{using(var sc=new ServiceController("AudioSrv"))sc.WaitForStatus(ServiceControllerStatus.Running,TimeSpan.FromSeconds(30));int v=30;using(var k=Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\SetVolSvc\Parameters")){if(k!=null)v=Convert.ToInt32(k.GetValue("Volume")??30);}v=Math.Max(0,Math.Min(100,v));int t=0;while(t!=10){try{var e=(D)(new E());IntPtr d;e.GetDefaultAudioEndpoint(0,1,out d);var dv=(V)Marshal.GetObjectForIUnknown(d);var i=typeof(A).GUID;object o;dv.Activate(ref i,1,IntPtr.Zero,out o);var av=(A)o;av.SetMute(false,Guid.Empty);av.SetMasterVolumeLevelScalar(v/100f,Guid.Empty);break;}catch{Thread.Sleep(500);}t++;}}catch{}Stop();}protected override void OnStart(string[] a){new Thread(W){IsBackground=true}.Start();}protected override void OnStop(){}static void Main(){Run(new S());}}>> "%CS%"
set "CSC=%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\csc.exe"
if not exist "%CSC%" set "CSC=%WINDIR%\Microsoft.NET\Framework\v4.0.30319\csc.exe"
if not exist "%CSC%" goto :end
"%CSC%" /nologo /reference:System.ServiceProcess.dll /out:"%EX%" "%CS%" >nul 2>&1
if not exist "%EX%" goto :end
sc create %SVC% binPath= "%EX%" start= auto obj= LocalSystem type= own >nul 2>&1
sc config %SVC% binPath= "%EX%" start= auto obj= LocalSystem type= own >nul 2>&1
sc description %SVC% "Sets master volume to a fixed level before logon" >nul 2>&1
reg add "%KEY%\Parameters" /v Volume /t REG_DWORD /d %VOL% /f >nul 2>&1
del "%CS%" >nul 2>&1
sc query AudioSrv 2>nul | find "RUNNING" >nul && sc start %SVC% >nul 2>&1
:end
endlocal