Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active April 27, 2024 15:05
Show Gist options
  • Star 60 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save primaryobjects/8b54f7f4219960127f1f620116315a37 to your computer and use it in GitHub Desktop.
Save primaryobjects/8b54f7f4219960127f1f620116315a37 to your computer and use it in GitHub Desktop.
Script to Enable Windows 10 Mobile Hotspot Automatically After Reboot

Enable Windows 10 Mobile Hotspot Automatically After Reboot

❤️ Sponsor This Project

On Windows 10, the Mobile Hotspot feature is automatically disabled when rebooting the machine. Users are required to manually open the Mobile Hotspot settings and toggle the slider for "Share my Internet connection with other devices" in order to enable it.

The included PowerShell script can be added to the Windows Task Scheduler to automatically turn on your Windows 10 Mobile Hotspot upon reboot, login, and unlock of the workstation by any user.

Quick Start

  1. Copy the two script files to a folder on your computer: hotspot.ps1 and hotspot.bat
  2. Open the Windows Task Scheduler.
  3. Right-click on Task Scheduler Library and select Create Task.
    • Enter a Name and Description.
    • Select Run whether user is logged on or not.
    • Checkmark Run with highest privileges.
  4. Click the Triggers tab.
  5. Click New.
    • For Begin the task select At startup.
    • Checkmark Delay task for: 1 minute.
    • Checkmark Stop task if it runs longer than: 30 minutes.
    • Checkmark Enabled.
  6. Click the Conditions tab.
  7. Uncheck the options Stop if the computer switches to battery power and Start the task only if the computer is on AC power.
  8. Click OK.

When saving the Task Scheduler, enter your username (username, ADUser\username, CORP\username, etc.) and your Windows password.

Troubleshooting Hotspot Not Activating After Sleep/Hibernation

If the hotspot enable task is not running after your PC wakes from sleep/hibernation, you can add a trigger to execute the task as soon as possible after waking. Create an additional trigger with the following steps.

  1. Edit the task and click the Triggers tab.
  2. For Begin the task select On a schedule.
  3. Check the radio option Daily.
  4. Enter the earliest Start Time to run. For example, 8:00 AM EST. This computer does not need to be awake during this time, so it is recommended to make this time earlier than you actually need.
  5. Select Recur every 1 day.
  6. Click OK.
  7. Click the Settings tab.
  8. Checkmark the option Run task as soon as possible after a scheduled start is missed.

Troubleshooting Hotspot Disabling Frequently

See also Windows 10 Mobile Hotspot Keep Alive Script.

If the mobile hotspot is turning itself off at random periods, you can try the following settings:

  1. Disable mobile hotspot power saving by opening the Mobile Hotspot settings and disabling When no devices are connected, automatically turn off mobile hotspot.

  2. Set the PeerlessTimeoutEnabled and PublicConnectionTimeout value to a longer duration. This can be done by setting the registry value HKLM\System\ControlSet001\Services\ICSSVC\Settings\PeerlessTimeoutEnabled to 120 (Hexadecimal) and HKLM\System\ControlSet001\Services\ICSSVC\Settings\PublicConnectionTimeout to 60 (Hexadecimal).

    An example registry script is shown below.

    Windows Registry Editor Version 5.00
    
    [HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\icssvc\Settings]
    "PeerlessTimeoutEnabled"=dword:00000120
    "PublicConnectionTimeout"=dword:00000060
    
  3. Run the script hotspot-keep-alive.ps1.

Running the Task When Connecting to the Internet Network

You may optionally want to add a condition to run the task whenever you connect to the Internet. This may be done by adding a new "Trigger" to the task scheduler. Select On an event, for "Log" select Microsoft-Windows-NetworkProfile/Operational, for Source select NetworkProfile, for Event ID enter 10000 (enter 10001 for network disconnect instead of connect). Checkmark Delay task for and select 30 seconds.

Windows 10 Mobile Hotspot Keep Alive Script

An easy script to keep the Windows 10 mobile hotspot turned on even if it becomes disabled.

Windows 10 Mobile Hotspot Keep Alive Script

# https://superuser.com/a/1434648
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
Function Await($WinRtTask, $ResultType) {
$asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
$netTask = $asTask.Invoke($null, @($WinRtTask))
$netTask.Wait(-1) | Out-Null
$netTask.Result
}
Function AwaitAction($WinRtAction) {
$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and !$_.IsGenericMethod })[0]
$netTask = $asTask.Invoke($null, @($WinRtAction))
$netTask.Wait(-1) | Out-Null
}
Function Get_TetheringManager() {
$connectionProfile = [Windows.Networking.Connectivity.NetworkInformation,Windows.Networking.Connectivity,ContentType=WindowsRuntime]::GetInternetConnectionProfile()
$tetheringManager = [Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager,Windows.Networking.NetworkOperators,ContentType=WindowsRuntime]::CreateFromConnectionProfile($connectionProfile)
return $tetheringManager;
}
Function SetHotspot($Enable) {
$tetheringManager = Get_TetheringManager
if ($Enable -eq 1) {
if ($tetheringManager.TetheringOperationalState -eq 1)
{
"Hotspot is already On!"
}
else{
"Hotspot is off! Turning it on"
Await ($tetheringManager.StartTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
}
}
else {
if ($tetheringManager.TetheringOperationalState -eq 0)
{
"Hotspot is already Off!"
}
else{
"Hotspot is on! Turning it off"
Await ($tetheringManager.StopTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
}
}
}
# Define a function to check the status of the hotspot
Function Check_HotspotStatus() {
$tetheringManager = Get_TetheringManager
return $tetheringManager.TetheringOperationalState -eq "Off"
}
# Define a function to start the hotspot
Function Start_Hotspot() {
$tetheringManager = Get_TetheringManager
Await ($tetheringManager.StartTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
}
$currentDateTime = Get-Date -Format "MM-dd-yyyy HH:mm:ss"
"$currentDateTime Starting hotspot keep-alive."
# Keep alive wifi.
while ($true) {
# Get the current date and time in a specific format
$currentDateTime = Get-Date -Format "MM-dd-yyyy HH:mm:ss"
if (Check_HotspotStatus) {
"$currentDateTime Hotspot is off! Turning it on"
Start_Hotspot
}
Start-Sleep -Seconds 10 # Wait for 10 seconds before checking again
}
PowerShell -Command "Set-ExecutionPolicy Unrestricted" >> "%TEMP%\StartupLog.txt" 2>&1
PowerShell C:\Users\YOUR_USERNAME\Desktop\hotspot.ps1 >> "%TEMP%\StartupLog.txt" 2>&1
# https://superuser.com/a/1434648
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
Function Await($WinRtTask, $ResultType) {
$asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
$netTask = $asTask.Invoke($null, @($WinRtTask))
$netTask.Wait(-1) | Out-Null
$netTask.Result
}
Function AwaitAction($WinRtAction) {
$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and !$_.IsGenericMethod })[0]
$netTask = $asTask.Invoke($null, @($WinRtAction))
$netTask.Wait(-1) | Out-Null
}
Function SetHotspot($Enable) {
$connectionProfile = [Windows.Networking.Connectivity.NetworkInformation,Windows.Networking.Connectivity,ContentType=WindowsRuntime]::GetInternetConnectionProfile()
$tetheringManager = [Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager,Windows.Networking.NetworkOperators,ContentType=WindowsRuntime]::CreateFromConnectionProfile($connectionProfile)
if ($Enable -eq 1) {
if ($tetheringManager.TetheringOperationalState -eq 1)
{
"Hotspot is already On!"
}
else{
"Hotspot is off! Turning it on"
Await ($tetheringManager.StartTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
}
}
else {
if ($tetheringManager.TetheringOperationalState -eq 0)
{
"Hotspot is already Off!"
}
else{
"Hotspot is on! Turning it off"
Await ($tetheringManager.StopTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
}
}
}
Function ToggleHotspot($Delay) {
SetHotspot(1)
sleep -seconds $Delay
SetHotspot(0)
sleep -seconds $Delay
SetHotspot(1)
}
ToggleHotspot(3)
@chrisdi91
Copy link

I used "Winaero Tweaker" for it.
Maybe this will help also? But did not try this way:
Hot to Unblock a downloaded file

@Sa1Gur
Copy link

Sa1Gur commented Apr 12, 2022

Hi.

Windows locks some file types that are considered a potential threat when downloaded from the Internet. To prevent errors on the installation, unlock the files following this procedure:

  1. Right click the file in Windows Explorer. Click Show More Options
  2. Click Properties.
  3. On the General tab, locate the Security field, and click Unblock.

download

Or via powershell Unblock-File -Path .\hotspot.ps1

@chrisdi91
Copy link

I just mentioned "Winaero Tweaker", because at my office laptop, i had not the "Unblock" checkbox. Maybe due to security regulations ...

@Sa1Gur
Copy link

Sa1Gur commented Apr 12, 2022

I just mentioned "Winaero Tweaker", because at my office laptop, i had not the "Unblock" checkbox. Maybe due to security regulations ...

Does powershell Unblock-File -Path command working at your laptop?

@chrisdi91
Copy link

Honestly can't remember if i Tried ... i am not a programmer either so i was happy to find the tool.
But at the moment i do not have a blocked file to test ist ...
Well ... so far for me it is not necessary at the moment to find out, because it does what it should right now. :)

@Novikss
Copy link

Novikss commented Apr 12, 2022

Thanks a lot for all your answers and advice. Now it is working as intended

@Nissaninyo
Copy link

Can you please add more details to the guide?
I don't know how to complete it.

@Nissaninyo
Copy link

Nissaninyo commented Apr 23, 2022

Hi! Thank you for the script! It helped me a lot.

I'd like to suggest adding info about setting up. Like

2. Edit hostpot.cmd to match hotspot.ps1 file location

Hey, can you please tell me how I do this?

@chrisdi91
Copy link

chrisdi91 commented Apr 23, 2022

Hi! Thank you for the script! It helped me a lot.
I'd like to suggest adding info about setting up. Like

2. Edit hostpot.cmd to match hotspot.ps1 file location

Hey, can you please tell me how I do this?

Hey hi

in the Hotspot.cmd it says:

„ C:\Users\YOUR_USERNAME\Desktop\hotspot.ps1 >> "%TEMP%\StartupLog.txt" 2>&1

and instead of YOUR_USERNAME you must use your Windows Username

or you edit your whole path and put maybe both files in an separate folder in another directory.

you just have to fill the path, where your hotspot.ps1 file is saved.

@Nissaninyo
Copy link

Hey hi

in the Hotspot.cmd it says:

„ C:\Users\YOUR_USERNAME\Desktop\hotspot.ps1 >> "%TEMP%\StartupLog.txt" 2>&1 “ and instead of YOUR_USERNAME you must use your Windows Username

or you edit your whole path and put maybe both files in an separate folder in another directory.

you just have to fill the path, where your hotspot.ps1 file is saved.

Thanks

@Nissaninyo
Copy link

It's not working for me (the files are unlocked), what could be the reason?

@Sa1Gur
Copy link

Sa1Gur commented Apr 25, 2022

You could try launching Hotspot.cmd file manually to check if it's working on your machine. And check out logs (%TEMP%\StartupLog.txt)

@Nissaninyo
Copy link

You could try launching Hotspot.cmd file manually to check if it's working on your machine. And check out logs (%TEMP%\StartupLog.txt)

Okay I checked and unfortunately it only works with 2.4 GHz and not with 5GHz

@Impesoft
Copy link

Hi! Thank you for the script! It helped me a lot.

I'd like to suggest adding info about setting up. Like

  1. Click Actions tab and add hotspot.cmd
  2. Edit hostpot.cmd to match hotspot.ps1 file location
  3. Unblock hotspot.ps1

+1

I did find the absence of this confusing... but I knew it was required, so I obviously added this myself, but not everyone will know this.

@justfoolingaround
Copy link

justfoolingaround commented May 22, 2022

Function ToggleHotspot($Delay) {
   SetHotspot(1)
   sleep -seconds $Delay
   SetHotspot(0)
   sleep -seconds $Delay
   SetHotspot(1)
}

Taken from hotspot.ps1 L45-51

Is there any particular reason as to why this is made such that the hotspot gets enabled, closed and re-enabled after the set delay (3, in this case.)?

@chrisdi91
Copy link

The

Function ToggleHotspot($Delay) {
   SetHotspot(1)
   sleep -seconds $Delay
   SetHotspot(0)
   sleep -seconds $Delay
   SetHotspot(1)
}

Taken from hotspot.ps1 L45-51

Is there any particular reason as to why this is made such that the hotspot gets enabled, closed and re-enabled after the set delay (3, in this case.)?

is that the reason why it wont work anymore for me?
so far it worked.
But since a few days after turning the computer on, the Wifi stayed turned off.
I just testet the cmd.
If the wifi is turned off it will switch it on and again off.
If it is on, it will switch it off and on again.

But that was not from the beginning.
Can someone help?

@Azaruddin-Scientist
Copy link

Azaruddin-Scientist commented Jun 2, 2022

Thank you stranger on the internet, i was getting frustrated when the normal sript not working when windows start but with your scripts, now my Hotspot turns ON when windows start. Thanks. chef kiss.
note to others:- change USER_NAME to your username if the files are on desktop or if the files are moved means change the C;\ location to that location.

@OttToyBoy
Copy link

Thank you! I very much appreciate all the work you must have put in to do this.

Quick note: My username is two words separated by a space, e.g. "c:\users\two words\Desktop\hotspot.cmd"
Probably inelegant but my solution was to use: "c:\users\TWOWOR~1\Desktop\hotspot.cmd" because the space in the username was not allowed by the command.

@chrisdi91
Copy link

chrisdi91 commented Jun 27, 2022

Thank you! I very much appreciate all the work you must have put in to do this.

Quick note: My username is two words separated by a space, e.g. "c:\users\two words\Desktop\hotspot.cmd" Probably inelegant but my solution was to use: "c:\users\TWOWOR~1\Desktop\hotspot.cmd" because the space in the username was not allowed by the command.

Did you try underscore instead of space?
I think - in another thing I had a folder with space ( like 'folder name') and in the powershell it appeard like 'folder_name'
Maybe here too?

Another thing
As i mention at 23.05.2022 that it wont work at my office network (but at home it does) (maybe conflicts with my outconnect vpn cmd?)

I got another problem because of this:
https://www.theregister.com/2022/06/20/windows_patch_issues/?td=keepreading-btm
it is only possible to go share wifi or to be in the network (comparable like a wifi connected smartphone that cannot share a hotsport (only with mobile data)
anyone got the same problem?

@primaryobjects
Copy link
Author

Yes, a recent hotfix (KB5014697 or KB5014699) causes the issue:

"When attempting to use the hotspot feature, the host device might lose the connection to the internet after a client device connects."

The solution is to go to Windows Update Settings, View update history, Uninstall updates, select KB5014697 or KB5014699.

Until an official fix is released by Microsoft.

@brashquido
Copy link

Works well for me with Windows 11, provided I have an active Wifi or ethernet connection. If I don't, the script throws errors and even via GUI the WiFi hotspot toggle switch is greyed out saying I need an active ethernet/wifi connection.

What I found is that if I toggle the airplane mode switch on and then off, I am then able to enable the wifi hotspot even without an active ethernet or wifi connection. At this point the script still seems to bomb out however referencing a null value.

Any idea why this might be?

@smartc
Copy link

smartc commented Sep 5, 2022

This script was exactly what I was looking for... Seems to be working with one issue for me. The connection defaults to being shared over Bluetooth instead of Wifi. I can change it to Wifi manually but it always reverts back to Bluetooth after a reboot.

Is there some way to tell PowerShell to share the connection over wifi instead of over bluetooth?

image

@fuegolin1
Copy link

Si alguien no le funciona en windows 11 es posible que sean por las politicas. Si encuentra esto en el arhivo StartupLog.txt

information please see "Get-Help Set-ExecutionPolicy".
At line:1 char:1

  • Set-ExecutionPolicy Unrestricted
  •   + CategoryInfo          : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException
      + FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand
    

C:\Users\Administrator\Desktop\Hostpot\hotspot.ps1 : File C:\Users\Administrator\Desktop\Hostpot\hotspot.ps1 cannot be
loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1

  • C:\Users\Administrator\Desktop\Hostpot\hotspot.ps1
  •   + CategoryInfo          : SecurityError: (:) [], PSSecurityException
      + FullyQualifiedErrorId : UnauthorizedAccess
    
    
    

Hacer lo siguiente:

1- Correr PowerShell como administrador
2- Ejecutar el siguiente comando -->> Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser
3- luego escribir-- >> A (para aceptar el desbloqueo todas las politicas)

@Olirale
Copy link

Olirale commented Dec 20, 2022

Thank u so much, we have changed the file ".cmd" which starts the operation by adding:
PowerShell -Command "Set-ExecutionPolicy Undefined" >> "%TEMP%\StartupLog.txt" 2>&1
So when the script ends, the policy is set to Undefined again (or whatever you had before)

@maxsu
Copy link

maxsu commented Apr 1, 2023

@primaryobjects I've simplified the powershell script:

Add-Type -AssemblyName System.Runtime.WindowsRuntime

$networkInfoType = [Windows.Networking.Connectivity.NetworkInformation]
$tetheringManagerType = [Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager] 

$tetheringManager = $tetheringManagerType::CreateFromConnectionProfile(
    $networkInfoType::GetInternetConnectionProfile()
)

Function EnableHotspot {
    if ($tetheringManager.TetheringOperationalState -eq 1) {
        "Hotspot is already On!"
    }
    else {
        "Hotspot is off! Turning it on"
        $tetheringManager.StartTetheringAsync() | Out-Null
    }
}

Function DisableHotspot {
    if ($tetheringManager.TetheringOperationalState -eq 0) {
        "Hotspot is already Off!"
    }
    else {
        "Hotspot is on! Turning it off"
        $tetheringManager.StopTetheringAsync() | Out-Null
    }
}

Function RebootHotspot {
    EnableHotspot
    Start-Sleep -seconds 3
    DisableHotspot
    Start-Sleep -seconds 3
    EnableHotspot
}

RebootHotspot

Changes:

  1. Eliminated the AsTask/Await logic - we now just hope the hotspot will change state fast enough
  2. Extracted the tethering manager setup; simplified the type literals
  3. Split the SetHotspot function into EnableHotspot and DisableHotspot functions
  4. Renamed the ToggleHotspot function to RebootHotspot; hard coded the 3 second delay

Caution: This script may appear to Reboot a hotspot that is hung, even though the reboot fails to bring the hotspot back to working order. I don't know what the original script would do in that case either, so for my purposes this risk is fine.

The result works on for my needs and is significantly easier for me to understand! Feel free to grab any of the changes you want!

@comiluv
Copy link

comiluv commented Jul 27, 2023

To run the cmd file in a minimized Window, set the task scheduler to run below:
run: %windir%\system32\cmd.exe
arguments: /C start "" /MIN %userprofile%\OneDrive\hotspot.cmd

fix the path in the arguments according to the location of your cmd file

@MickeyJMay
Copy link

Thank you! Working for me on Windows 11.

@remypzt
Copy link

remypzt commented Sep 2, 2023

Thakns for this but unfortunlatey it's not working for me on windows 11, I tried Sa1gur suggestions and Gurjeetsaini01 solution but still not working. If I launch hotspot.ps1 directly It's working but it's not working by using task scheldure or hotspot.cmd or netsh wlan start hostednetwork //start hotspot etc... I give up to do it clean : for those who's interrested I use Power automate for simulate mouse trigger for activate the hotspot

@4Brooker
Copy link

Hi all,
Sadly I don't get it to work. Is it for you guys still working?
I'm on windows 11 22H2.
Thanks in advance.

@tengelmannflitzer
Copy link

tengelmannflitzer commented Feb 19, 2024

for me it didn't work reliable.
i just made a simple autohotkey script to open the settings, emulate the toggle with send keys.
you could do the same with vbshell/cmd.
i convert the ahk script to exe and put it in autostart.

it's not elegant, but it works :-)
Sometimes hotspot won't work if i turn it on manually, then I have to turn wifi off and on again.
So i always toggle wifi first here and then turn hotspot on.

(I guess on english windows 10/11 the line would be
IfWinExist, Settings instead of IfWinExist, Einstellungen

sleep 15000
RunWait cmd.exe /c explorer ms-settings:network-wifi,,hide
sleep 500
Send,{Space}
sleep 2000
RunWait cmd.exe /c explorer ms-settings:network-mobilehotspot,,hide
sleep 500
Send,{Tab}
sleep 500
Send,{Tab}
sleep 500
Send,{Space}
sleep 5000
IfWinExist, Einstellungen
WinClose ;
sleep 5000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment