Auto set volume in a batch file


genocide088

New member
Local time
3:22 PM
Posts
4
OS
windows 11 22H2
this is as close i could get to making a batch file to automatcially set the volume down

i need to rewrite script so that just set it to 25% but cant figure out how to do

and if already below 25% just leave it

please someone could edit my code to achieve this?

it only reduces by 40% the =20 is 20 X 2% not what i want a half win

setlocal EnableDelayedExpansion

set /a volume=20

for /l %%x in (1,1,%volume%) do (
powershell -c "(New-Object -ComObject WScript.Shell).SendKeys([char]174)"
)
 
Windows Build/Version
windows 11 22h2

My Computer

System One

  • OS
    windows 11 22H2
I use SetVol.exe, others might suggest SoundVolumeView. Don't do the SendKeys thing, it's very 80's.
thanks but i must have it only in a batch file. no 3rd party software please. as i already modified 1000 more annoyances in windows 11 in just a few mouse clicks. funny you say its very 80ties actually i was programming a way back then in 1980 our family had a commodore pet 2001 computer.
 

My Computer

System One

  • OS
    windows 11 22H2
The problem of changing volume via SendKeys (or keystrokes) is:
1. You have no idea what the current volume level is. Therefore to get to 25% or 50%, you would have to send enough keystrokes to "zero" it, before increasing the volume from zero to 25% or 50%.
2. Sending keystrokes might be visible, if your onscreen volume display reacts in response.
3. You don't have finer control over volume levels.

My choice is SetVol.exe because it's the lightest, least obtrusive volume tool I could find. Otherwise just have PS repeat a ton of down keys, then enter up keys after you've passed zero volume.
 

My Computer

System One

  • OS
    Windows 7
I use a batch file for this but I do call up third-party utilities in it.

I use GetAudioVolume to find out what the current volume setting is.
I use NirSoft NirCmd to set the volume to what I want.

Best of luck,
Denis
 

My Computer

System One

  • OS
    Windows 11 Home x64 Version 23H2 Build 22631.3447
Set Volume to 24 or ( 26 which are the nearest even numbers to 25 as each keysend appears to change volume in 2 percent steps, when going up from 0 or going down from 100).

The batch file below can only set a fixed level of 24 (ie. if your current Voulme is below 24 and you run the script, it will raise it to 24), as there is no way of determining your current Volume level through this script.

Batch_File_to_Set_System_Volume_to_a_Fixed_Level_of_24.bat
Code:
<# ::
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit
setlocal
powershell -noprofile -ExecutionPolicy ByPass  "[ScriptBlock]::Create((${%~f0} | out-string)) | Invoke-Expression" & Exit
#
goto :EOF
#>
$Level  =  24
Function Set-SpeakerVolume{
Param (
  [Switch]$Min,
  [Switch]$Max,
  [Int]$Percent
)
  $wshShell = New-Object -Com WScript.Shell
  if ($Min){
      1..50 | % {$wshShell.SendKeys([Char]174)}
  }
  elseif ($Max){
      1..50 | % {$wshShell.SendKeys([Char]175)}
  }
  elseif($Percent){
      1..50 | % {$wshShell.SendKeys([Char]174)}
      1..($Percent/2) | % {$wshShell.SendKeys([Char]175)}
  }
  else{
      $wshShell.SendKeys([Char]173)
  }
}
Set-SpeakerVolume -Percent $Level
Exit

A less "cheesy" script which doesn't rely on keysend, which can set an exact level of 25.
Batch_File_to_Set_System_Volume_to_a_Fixed_Level_of_25.bat
Code:
<# ::
setlocal
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit 
powershell -noprofile -ExecutionPolicy ByPass  "[ScriptBlock]::Create((${%~f0} | out-string)) | Invoke-Expression" & exit
#>

Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume
{
    // f(), g(), ... are unused COM method slots. Define these if you care
    int f(); int g(); int h(); int i();
    int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext);
    int j();
    int GetMasterVolumeLevelScalar(out float pfLevel);
    int k(); int l(); int m(); int n();
    int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext);
    int GetMute(out bool pbMute);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice
{
    int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
    int f(); // Unused
    int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
}
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorComObject { }
public class Audio
{
    static IAudioEndpointVolume Vol()
    {
        var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
        IMMDevice dev = null;
        Marshal.ThrowExceptionForHR(enumerator.GetDefaultAudioEndpoint(/*eRender*/ 0, /*eMultimedia*/ 1, out dev));
        IAudioEndpointVolume epv = null;
        var epvid = typeof(IAudioEndpointVolume).GUID;
        Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, /*CLSCTX_ALL*/ 23, 0, out epv));
        return epv;
    }
    public static float Volume
    {
        get { float v = -1; Marshal.ThrowExceptionForHR(Vol().GetMasterVolumeLevelScalar(out v)); return v; }
        set { Marshal.ThrowExceptionForHR(Vol().SetMasterVolumeLevelScalar(value, System.Guid.Empty)); }
    }
    public static bool Mute
    {
        get { bool mute; Marshal.ThrowExceptionForHR(Vol().GetMute(out mute)); return mute; }
        set { Marshal.ThrowExceptionForHR(Vol().SetMute(value, System.Guid.Empty)); }
    }
}
'@
[audio]::Volume  = 0.25 # 0.25 = 25%, etc.
exit
 

My Computer

System One

  • OS
    Windows 11 23H2
    Computer type
    PC/Desktop
    Manufacturer/Model
    custom
    CPU
    intel i7-8700 (non-K)
    Motherboard
    Asus Z370 TUF Gaming
    Memory
    32Gb
    Graphics Card(s)
    On-board Intel iGPU
    Sound Card
    On-board Realtek
    Hard Drives
    Samsung_SSD_850_EVO
    PSU
    Corsair Rm850X
    Cooling
    All air
@garlin;
As a matter of interest, if I use this batch file, I can maintain the System Volume if it is less than 25, or reduce it to 25 if it is greater than 25. How would one prevent the duplication of the main functional part of the code ?

Code:
<# ::
setlocal
powershell -noprofile -ExecutionPolicy ByPass  "[ScriptBlock]::Create((${%~f0} | out-string)) | Invoke-Expression" & exit
#>


Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume
{
    // f(), g(), ... are unused COM method slots. Define these if you care
    int f(); int g(); int h(); int i();
    int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext);
    int j();
    int GetMasterVolumeLevelScalar(out float pfLevel);
    int k(); int l(); int m(); int n();
    int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext);
    int GetMute(out bool pbMute);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice
{
    int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
    int f(); // Unused
    int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
}
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorComObject { }
public class Audio
{
    static IAudioEndpointVolume Vol()
    {
        var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
        IMMDevice dev = null;
        Marshal.ThrowExceptionForHR(enumerator.GetDefaultAudioEndpoint(/*eRender*/ 0, /*eMultimedia*/ 1, out dev));
        IAudioEndpointVolume epv = null;
        var epvid = typeof(IAudioEndpointVolume).GUID;
        Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, /*CLSCTX_ALL*/ 23, 0, out epv));
        return epv;
    }
    public static float Volume
    {
        get { float v = -1; Marshal.ThrowExceptionForHR(Vol().GetMasterVolumeLevelScalar(out v)); return v; }
        set { Marshal.ThrowExceptionForHR(Vol().SetMasterVolumeLevelScalar(value, System.Guid.Empty)); }
    }
    public static bool Mute
    {
        get { bool mute; Marshal.ThrowExceptionForHR(Vol().GetMute(out mute)); return mute; }
        set { Marshal.ThrowExceptionForHR(Vol().SetMute(value, System.Guid.Empty)); }
    }
}
'@


$alpha = [Audio]::Volume
Write-Host Volume is $alpha


If ($alpha -ge "0.26") {
Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume
{
    // f(), g(), ... are unused COM method slots. Define these if you care
    int f(); int g(); int h(); int i();
    int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext);
    int j();
    int GetMasterVolumeLevelScalar(out float pfLevel);
    int k(); int l(); int m(); int n();
    int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext);
    int GetMute(out bool pbMute);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice
{
    int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
    int f(); // Unused
    int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
}
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorComObject { }
public class Audio
{
    static IAudioEndpointVolume Vol()
    {
        var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
        IMMDevice dev = null;
        Marshal.ThrowExceptionForHR(enumerator.GetDefaultAudioEndpoint(/*eRender*/ 0, /*eMultimedia*/ 1, out dev));
        IAudioEndpointVolume epv = null;
        var epvid = typeof(IAudioEndpointVolume).GUID;
        Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, /*CLSCTX_ALL*/ 23, 0, out epv));
        return epv;
    }
    public static float Volume
    {
        get { float v = -1; Marshal.ThrowExceptionForHR(Vol().GetMasterVolumeLevelScalar(out v)); return v; }
        set { Marshal.ThrowExceptionForHR(Vol().SetMasterVolumeLevelScalar(value, System.Guid.Empty)); }
    }
    public static bool Mute
    {
        get { bool mute; Marshal.ThrowExceptionForHR(Vol().GetMute(out mute)); return mute; }
        set { Marshal.ThrowExceptionForHR(Vol().SetMute(value, System.Guid.Empty)); }
    }
}
'@
[audio]::Volume  = 0.25
}
exit

(pn: small correction made to this bat file.)
 

My Computer

System One

  • OS
    Windows 11 23H2
    Computer type
    PC/Desktop
    Manufacturer/Model
    custom
    CPU
    intel i7-8700 (non-K)
    Motherboard
    Asus Z370 TUF Gaming
    Memory
    32Gb
    Graphics Card(s)
    On-board Intel iGPU
    Sound Card
    On-board Realtek
    Hard Drives
    Samsung_SSD_850_EVO
    PSU
    Corsair Rm850X
    Cooling
    All air
I've seen this code example before, but even as a reasonably experienced programmer -- do I know what device this references? I can't tell if this manages the master volume, or one of the mixer devices. This is where a dedicated, lightweight app makes more sense to a non-developer.

"SetVol.exe 25" -- And my scripting is done, with a portable, no-fuss EXE that I just copy in my path. ;-)
 

My Computer

System One

  • OS
    Windows 7
I have a weekly computer cleanup Script that I run and when finished it Restarts the computer. Upon Restart, it plays the X-Files theme. Therefore, I set the Speaker Volume within the computer cleanup Script. I have adapted it for this thread with the hope that someone will find in useful.

Code:
@echo off & color 07 & Title Set [Speaker Volume]: & echo.
set "Source=%~0"
set "Function=%Temp%\Speaker_Volume.ps1"
PowerShell Write-Host -ForegroundColor Red """" "IMPORTANT: """ -NoNewline; Write-Host -ForegroundColor DarkYellow """The [Speaker Volume] ONLY works with [EVEN] numbers entered."""; Write-Host -ForegroundColor DarkYellow """"            "Entering [0] will [MUTE] the [Speaker Volume] and retain the existing [Volume Level].""" & echo.
set /p "Level=>Enter the [Speaker Volume] and press <Enter>: "
del %Function% 2>nul & MORE /E +10 "%Source%" > %Function%
Call PowerShell -ExecutionPolicy ByPass -File %Function% %Level%
echo. & echo  The [Speaker Volume] has been set to [%Level%].
echo. & echo ^>Press ANY key to EXIT . . . & pause >nul & Exit

ForEach ($arg in $args) {
         $Level =$arg
         }
Function Set-SpeakerVolume{
Param (
  [Switch]$Min,
  [Switch]$Max,
  [Int]$Percent,
  [Int]$Level
)
  $wshShell = New-Object -Com WScript.Shell
  if ($Min){
      1..50 | % {$wshShell.SendKeys([Char]174)}
  }
  elseif ($Max){
      1..50 | % {$wshShell.SendKeys([Char]175)}
  }
  elseif($Percent){
      1..50 | % {$wshShell.SendKeys([Char]174)}
      1..($Percent/2) | % {$wshShell.SendKeys([Char]175)}
  }
  else{
      $wshShell.SendKeys([Char]173)
  }
}
Set-SpeakerVolume -Percent $Level
cmd /c del %Function%
Exit

I initially set up the original one with the help and input of @das10 .
 

My Computer

  • Like
Reactions: OAT
I have a weekly computer cleanup Script that I run and when finished it Restarts the computer. Upon Restart, it plays the X-Files theme. Therefore, I set the Speaker Volume within the computer cleanup Script. I have adapted it for this thread with the hope that someone will find in useful.

Code:
@echo off & color 07 & Title Set [Speaker Volume]: & echo.
set "Source=%~0"
set "Function=%Temp%\Speaker_Volume.ps1"
PowerShell Write-Host -ForegroundColor Red """" "IMPORTANT: """ -NoNewline; Write-Host -ForegroundColor DarkYellow """The [Speaker Volume] ONLY works with [EVEN] numbers entered."""; Write-Host -ForegroundColor DarkYellow """"            "Entering [0] will [MUTE] the [Speaker Volume] and retain the existing [Volume Level].""" & echo.
set /p "Level=>Enter the [Speaker Volume] and press <Enter>: "
del %Function% 2>nul & MORE /E +10 "%Source%" > %Function%
Call PowerShell -ExecutionPolicy ByPass -File %Function% %Level%
echo. & echo  The [Speaker Volume] has been set to [%Level%].
echo. & echo ^>Press ANY key to EXIT . . . & pause >nul & Exit

ForEach ($arg in $args) {
         $Level =$arg
         }
Function Set-SpeakerVolume{
Param (
  [Switch]$Min,
  [Switch]$Max,
  [Int]$Percent,
  [Int]$Level
)
  $wshShell = New-Object -Com WScript.Shell
  if ($Min){
      1..50 | % {$wshShell.SendKeys([Char]174)}
  }
  elseif ($Max){
      1..50 | % {$wshShell.SendKeys([Char]175)}
  }
  elseif($Percent){
      1..50 | % {$wshShell.SendKeys([Char]174)}
      1..($Percent/2) | % {$wshShell.SendKeys([Char]175)}
  }
  else{
      $wshShell.SendKeys([Char]173)
  }
}
Set-SpeakerVolume -Percent $Level
cmd /c del %Function%
Exit

I initially set up the original one with the help and input of @das10 .

ok i tried it nice thanks
its better than retarted way to get down volume by 2% repeated
i am getting lazy at redoing code its only a hobby for me
please if possible could you update code NO INPUT FROM USER JUST AUTO SET IT TO 25%
why i want this is cause oh boy i did quite a number on the windows install and all softwares i wanted to install
and all there settings as much as possilbe that i want and all crap ware removed
we talking hundreds of buzy-work nonsense i used to have to do
if you can rewrite like this thanks very much

oh and another one i dont think its possilbe to solve but i tried dam hard even in the registry to auto set all the file associations to the programs i want in WINDOWS 11 not windows 10 which is easy to do
i came close but i dont think that can be done. is retardation why microshit make you even changing edge to google chrome about 10 are you sure you want to switch settings. if anyone know how to do that please let me know

actaully i think i should look into linux but have done so its that windows is the defacto legacy system so unfortunate really
 

My Computer

System One

  • OS
    windows 11 22H2
Back
Top Bottom