Enable Windows 10 built-in hotspot by cmd/batch/powershell - windows

I'm searching for a way to enable/disable the Hotspot built into Windows 10 via the command prompt, powershell or a batch file. In the GUI, it can be easily done with the third button in the network panel (see image below), but I want to automate it.
I already found some hundred tutorials how to create a new hotspot using netsh, but as I understand it this would create another, different hotspot.
Instead I want to use the already configured one. Or does Windows 10 use the same and creates a new hotspot every time but in between only remembers the settings?
I played around a little bit and discovered the following:
My current WiFi driver doesn't support hosted networks. If I enter netsh wlan show drivers it says hosted network supprt: no. So for the 'common' solution I would have to update the driver.
Nevertheless, I can create a HotSpot with the built-in solution (see image).
It seems that if I activate this HotSpot, Windows creates an additional Microsoft Wi-Fi Direct Virtual Adapter #x. As soon I deactivate the HotSpot, the adapter vanishes.
So it seems that MS is using a very different technique for the built-in hotspot than the netsh variant. Which brings me again to the question: how can I automate (by script) the enabling/disabling of this hotspot?

The Hosted Network (which can be configured using the netsh wlan set hostednetwork ... command) and the "new" Mobile Hotspot use different technologies under the hood.
There's a WinRT API to control and configure the "new" mobile hotspot you're referring to. You can call it from PowerShell:
The following code snippet requires Ben N.'s await function for IAsyncOperation and IAsyncAction in PowerShell, which can be found here.
$connectionProfile = [Windows.Networking.Connectivity.NetworkInformation,Windows.Networking.Connectivity,ContentType=WindowsRuntime]::GetInternetConnectionProfile()
$tetheringManager = [Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager,Windows.Networking.NetworkOperators,ContentType=WindowsRuntime]::CreateFromConnectionProfile($connectionProfile)
# Be sure to include Ben N.'s await for IAsyncOperation:
# https://superuser.com/questions/1341997/using-a-uwp-api-namespace-in-powershell
# Check whether Mobile Hotspot is enabled
$tetheringManager.TetheringOperationalState
# Start Mobile Hotspot
Await ($tetheringManager.StartTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
# Stop Mobile Hotspot
Await ($tetheringManager.StopTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
The NetworkOperatorTetheringManager class also allows you to set the SSID and the passphrase of your hotspot programmatically.

TL;DR:
If anyone is interested, I've created a batch file using the above solution to turn on the Mobile Hotspot. Simply create a new .bat file and paste the following code inside:
#echo off
powershell.exe -encodedCommand WwBXAGkAbgBkAG8AdwBzAC4AUwB5AHMAdABlAG0ALgBVAHMAZQByAFAAcgBvAGYAaQBsAGUALgBMAG8AYwBrAFMAYwByAGUAZQBuACwAVwBpAG4AZABvAHcAcwAuAFMAeQBzAHQAZQBtAC4AVQBzAGUAcgBQAHIAbwBmAGkAbABlACwAQwBvAG4AdABlAG4AdABUAHkAcABlAD0AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAF0AIAB8ACAATwB1AHQALQBOAHUAbABsAA0ACgBBAGQAZAAtAFQAeQBwAGUAIAAtAEEAcwBzAGUAbQBiAGwAeQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBSAHUAbgB0AGkAbQBlAC4AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAA0ACgAkAGEAcwBUAGEAcwBrAEcAZQBuAGUAcgBpAGMAIAA9ACAAKABbAFMAeQBzAHQAZQBtAC4AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAFMAeQBzAHQAZQBtAEUAeAB0AGUAbgBzAGkAbwBuAHMAXQAuAEcAZQB0AE0AZQB0AGgAbwBkAHMAKAApACAAfAAgAD8AIAB7ACAAJABfAC4ATgBhAG0AZQAgAC0AZQBxACAAJwBBAHMAVABhAHMAawAnACAALQBhAG4AZAAgACQAXwAuAEcAZQB0AFAAYQByAGEAbQBlAHQAZQByAHMAKAApAC4AQwBvAHUAbgB0ACAALQBlAHEAIAAxACAALQBhAG4AZAAgACQAXwAuAEcAZQB0AFAAYQByAGEAbQBlAHQAZQByAHMAKAApAFsAMABdAC4AUABhAHIAYQBtAGUAdABlAHIAVAB5AHAAZQAuAE4AYQBtAGUAIAAtAGUAcQAgACcASQBBAHMAeQBuAGMATwBwAGUAcgBhAHQAaQBvAG4AYAAx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B3AG8AcgBrAE8AcABlAHIAYQB0AG8AcgBzAC4ATgBlAHQAdwBvAHIAawBPAHAAZQByAGEAdABvAHIAVABlAHQAaABlAHIAaQBuAGcATwBwAGUAcgBhAHQAaQBvAG4AUgBlAHMAdQBsAHQAXQApAA==
(Although it's trivial to say, I'll remind you that the above code will also work as a CMD command).
Explanation:
What I did is to take the following PowerShell script (given in above answers by Julius Hardt), and convert it to a batch file using this converter:
[Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,ContentType=WindowsRuntime] | Out-Null
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
}
$connectionProfile = [Windows.Networking.Connectivity.NetworkInformation,Windows.Networking.Connectivity,ContentType=WindowsRuntime]::GetInternetConnectionProfile()
$tetheringManager = [Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager,Windows.Networking.NetworkOperators,ContentType=WindowsRuntime]::CreateFromConnectionProfile($connectionProfile)
# Be sure to include Ben N.'s await for IAsyncOperation:
# https://superuser.com/questions/1341997/using-a-uwp-api-namespace-in-powershell
# Check whether Mobile Hotspot is enabled
$tetheringManager.TetheringOperationalState
# Start Mobile Hotspot
Await ($tetheringManager.StartTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
I've also put this batch file inside the startup folder located in "C:\Users\<USERNAME>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" so the Mobile Hotspot will turn on automatically upon Windows startup.
To toggle the Mobile Hotspot ON\OFF, I've modified the above answer (by Julius Hardt) to this:
[Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,ContentType=WindowsRuntime] | Out-Null
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
}
$connectionProfile = [Windows.Networking.Connectivity.NetworkInformation,Windows.Networking.Connectivity,ContentType=WindowsRuntime]::GetInternetConnectionProfile()
$tetheringManager = [Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager,Windows.Networking.NetworkOperators,ContentType=WindowsRuntime]::CreateFromConnectionProfile($connectionProfile)
# Be sure to include Ben N.'s await for IAsyncOperation:
# https://superuser.com/questions/1341997/using-a-uwp-api-namespace-in-powershell
# Check whether Mobile Hotspot is enabled
$tetheringManager.TetheringOperationalState
# If Mobile Hotspot is on - turn it off.
if ($tetheringManager.TetheringOperationalState -eq 1){
# Stop Mobile Hotspot
Await ($tetheringManager.StopTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
}
# If Mobile Hotspot is off - turn it on.
else{
# Start Mobile Hotspot
Await ($tetheringManager.StartTetheringAsync()) ([Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationResult])
}
The corresponding batch file:
#echo off
powershell.exe -encodedCommand WwBXAGkAbgBkAG8AdwBzAC4AUwB5AHMAdABlAG0ALgBVAHMAZQByAFAAcgBvAGYAaQBsAGUALgBMAG8AYwBrAFMAYwByAGUAZQBuACwAVwBpAG4AZABvAHcAcwAuAFMAeQBzAHQAZQBtAC4AVQBzAGUAcgBQAHIAbwBmAGkAbABlACwAQwBvAG4AdABlAG4AdABUAHkAcABlAD0AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAF0AIAB8ACAATwB1AHQALQBOAHUAbABsAA0ACgBBAGQAZAAtAFQAeQBwAGUAIAAtAEEAcwBzAGUAbQBiAGwAeQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBSAHUAbgB0AGkAbQBlAC4AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAA0ACgAkAGEAcwBUAGEAcwBrAEcAZQBuAGUAcgBpAGMAIAA9ACAAKABbAFMAeQBzAHQAZQBtAC4AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAFMAeQBzAHQAZQBtAEUAeAB0AGUAbgBzAGkAbwBuAHMAXQAuAEcAZQB0AE0AZQB0AGgAbwBkAHMAKAApACAAfAAgAD8AIAB7ACAAJABfAC4ATgBhAG0AZQAgAC0AZQBxACAAJwBBAHMAVABhAHMAawAnACAALQBhAG4AZAAgACQAXwAuAEcAZQB0AFAAYQByAGEAbQBlAHQAZQByAHMAKAApAC4AQwBvAHUAbgB0ACAALQBlAHEAIAAxACAALQBhAG4AZAAgACQAXwAuAEcAZQB0AFAAYQByAGEAbQBlAHQAZQByAHMAKAApAFsAMABdAC4AUABhAHIAYQBtAGUAdABlAHIAVAB5AHAAZQAuAE4AYQBtAGUAIAAtAGUAcQAgACcASQBBAHMAeQBuAGMATwBwAGUAcgBhAHQAaQBvAG4AYAAxACcAIAB9ACkAWwAwAF0ADQAKAEY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AAgAE0AbwBiAGkAbABlACAASABvAHQAcwBwAG8AdAANAAoAIAAgACAAIABBAHcAYQBpAHQAIAAoACQAdABlAHQAaABlAHIAaQBuAGcATQBhAG4AYQBnAGUAcgAuAFMAdABvAHAAVABlAHQAaABlAHIAaQBuAGcAQQBzAHkAbgBjACgAKQApACAAKABbAFcAaQBuAGQAbwB3AHMALgBOAGUAdAB3AG8AcgBrAGkAbgBnAC4ATgBlAHQAdwBvAHIAawBPAHAAZQByAGEAdABvAHIAcwAuAE4AZQB0AHcAbwByAGsATwBwAGUAcgBhAHQAbwByAFQAZQB0AGgAZQByAGkAbgBnAE8AcABlAHIAYQB0AGkAbwBuAFIAZQBzAHUAbAB0AF0AKQANAAoAfQANAAoAIwAgAEkAZgAgAE0AbwBiAGkAbABlACAASABvAHQAcwBwAG8AdAAgAGkAcwAgAG8AZgBmACAALQAgAHQAdQByAG4AIABpAHQAIABvAG4ALgANAAoAZQBsAHMAZQB7AA0ACgAgACAAIAAgACMAIABTAHQAYQByAHQAIABNAG8AYgBpAGwAZQAgAEgAbwB0AHMAcABvAHQADQAKACAAIAAgACAAQQB3AGEAaQB0ACAAKAAkAHQAZQB0AGgAZQByAGkAbgBnAE0AYQBuAGEAZwBlAHIALgBTAHQAYQByAHQAVABlAHQAaABlAHIAaQBuAGcAQQBzAHkAbgBjACgAKQApACAAKABbAFcAaQBuAGQAbwB3AHMALgBOAGUAdAB3AG8AcgBrAGkAbgBnAC4ATgBlAHQAdwBvAHIAawBPAHAAZQByAGEAdABvAHIAcwAuAE4AZQB0AHcAbwByAGsATwBwAGUAcgBhAHQAbwByAFQAZQB0AGgAZQByAGkAbgBnAE8AcABlAHIAYQB0AGkAbwBuAFIAZQBzAHUAbAB0AF0AKQANAAoAfQANAAoADQAKAA==

The Windows 10 mobile hotspot gets started by the Windows Mobile Hotspot Service (icssvc).
Using Powershell:
Get the current state of the service:
get-service "icssvc"
Start the service:
start-service "icssvc"
Stop the service:
stop-service "icssvc"
If you want to configure the hotspot then thats another thing. You can Google "Configure Internet Connection Sharing with PowerShell" to get you started.

Based on the PowerShell comment above,
Here are the WinRT code components for mix/match to accomplish the above tasks for WiFi Direct 2.0 HotSpot activities using C++ without dependencies on other tooling etc (they work on IoT Core, etc):
Programmatically set the SSID and/or PassPhrase
Programmatically query the current WiFi Direct 2.0 HotSpot status
Programmatically turn on/off the WiFi Direct 2.0 HotSpot
#include <winrt/Windows.Networking.Connectivity.h>
#include <winrt/Windows.Networking.NetworkOperators.h>
namespace winrt { // /ZW embed in :<winrt> when `Windows` is ambiguously defined
static void af_winrt_wifi_hotspot_test() {
// start ms-settings:network-mobilehotspot
init_apartment(); // apartment_type::multi_threaded
auto connectionProfile { Windows::Networking::Connectivity::NetworkInformation::GetInternetConnectionProfile() };
auto tetheringManager = Windows::Networking::NetworkOperators::NetworkOperatorTetheringManager::CreateFromConnectionProfile(connectionProfile);
switch(tetheringManager.TetheringOperationalState()) {
case Windows::Networking::NetworkOperators::TetheringOperationalState::Off: {
auto ioAsync = tetheringManager.StartTetheringAsync();
auto fResult = ioAsync.get();
}
break;
case Windows::Networking::NetworkOperators::TetheringOperationalState::On: {
auto ioAsync = tetheringManager.StopTetheringAsync();
auto fResult = ioAsync.get();
}
break;
case Windows::Networking::NetworkOperators::TetheringOperationalState::InTransition:
default:
break;
}
clear_factory_cache();
uninit_apartment();
}
}

I can confirm #smallscript's winRT solution works. Running the script will either open/close hotspot connection depends on the current status (enabled to disabled and vice versa).
To complete his answer I will point out two additional things in order to compile the code:
You must have Windows SDK installed(I used version 10.0.18362.0) to have the winRT library.
You need to link the RuntimeObject.lib library to your project, otherwise you'll get unresolved external symbols (Using VS, Add the name to: Project -> Properties -> Linker -> Input -> Additional Dependencies)

I think the only solution at the moment is to setup an autohotkey script to click the button on start up. Windows +A, Shift Tab, down arrow, etc... I need this for a headless PC to allow wifi remote desktop.

Turn on command - netsh wlan set hostednetwork mode=allow
Turn off command - netsh wlan set hostednetwork mode=disallow
-not tested-

By Using CMD.
It is too Simple to turn PC as Hotspot. But you PC must have Hosted network supported, to check it out try this command
#echo off
REM Copyright (C) 2013
REM user49828
REM
REM Batch file for creating Wifi Hotspot
if _%1_==_payload_ goto :payload
:getadmin
echo %~nx0: elevating self
set vbs=%temp%\getadmin.vbs
echo Set UAC = CreateObject^("Shell.Application"^) >> "%vbs%"
echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
goto :eof
:payload
echo %~nx0: running payload with parameters:
echo %*
echo ---------------------------------------------------
cd /d %2
shift
shift
rem put your code here
rem e.g.: perl myscript.pl %1 %2 %3 %4 %5 %6 %7 %8 %9
:start
#ECHO off
ECHO Pleae select one of the options Programmed By Overflown.com "user49828"
ECHO --------------------------------------------------------------------------------------------------------------------------
ECHO 1 Hotspot settings
ECHO 2 Start Hotspot
ECHO 3 Stop Hotspot
ECHO --------------------------------------------------------------------------------------------------------------------------
SET /p option=Please enter one of the options:
if %option%==1 ( goto setup ) else set /a er=1
if %option%==2 ( goto start1 ) else set /a er=er+1
if %option%==3 ( goto stop ) else set /a er=er+1
:noOption
if %er% GEQ 3 (
Echo Error!
Echo Please enter a correct option
#pause
cls
goto start
)
:setup
SET /p ssid=Please enter the Hotspot name:
SET /p key=Please enter the Hotspot password greater the 8 digits:
netsh wlan set hostednetwork mode=allow ssid=%ssid% key=%key%
if %errorlevel%==0 (
ECHO Setup complete
)
#pause
cls
goto start
:start1
netsh wlan start hostednetwork
#pause
cls
goto start
:stop
netsh wlan stop hostednetwork
#pause
cls
goto start
goto :eof

Related

How to query and add (if not listed) a location to Windows 10 Search Index using PowerShell

I have to re-mount removable drives (which require authentication) each time I boot the computer and Windows Indexing keeps removing the removable drives (perhaps because the removable drives are not available when the computer boots). In an ideal world Windows Indexing would keep these locations and just list them as 'Unavailable' (which it sometimes does). However because it doesn't I am interested in executing a script that queries the Windows Indexing locations and if it does not list the removable drives then add them. At the bottom of this thread I pasted the Batch script that I setup to run at boot (via Start Up folder) to search for a specific folder that is available thereafter mounting one of the removable drives.
I have found several examples of how to do this on Windows 7 (links pasted below) but I can't figure out how to do it in Windows 10. The links provided to the DLL (Microsoft.Search.Interop.dll) no longer resolve.
When searching for the latest Windows Search SDK for Windows 10 I was lead to the Windows SDK here:
https://learn.microsoft.com/en-us/windows/win32/search/-search-developers-guide-entry-page
I installed the C++ related portion of the Windows SDK then searched for Microsoft.Search.Interop.dll but I couldn't find it. Perhaps the DLL has changed?
From How to rebuild Windows Search Index by using PowerShell?
Load DLL containing classes & interfaces
Add-Type -path "C:\Temp\SearchIndexSdk\Microsoft.Search.Interop.dll"
#Provides methods for controlling the Search service. This
interface manages settings and objects that affect the search engine
across catalogs.
https://msdn.microsoft.com/en-us/library/bb231485(v=vs.85).aspx
$sm = New-Object Microsoft.Search.Interop.CSearchManagerClass
#Retrieves a catalog by name and creates a new ISearchCatalogManager
object for that catalog.
$catalog = $sm.GetCatalog("SystemIndex")
#Resets the underlying catalog by rebuilding the databases and performing a full indexing.
#https://msdn.microsoft.com/en-us/library/bb266414(v=vs.85).aspx
$catalog.Reset()
From How to add a location to windows 7/8 search index using batch or vbscript?
#Code copied from "Powershell Tackles Windows Desktop Search" http://powertoe.wordpress.com/2010/05/17/powershell-tackles-windows-desktop-search/
#Microsoft.Search.Interop.dll is needed, download from http://www.microsoft.com/en-us/download/details.aspx?id=7388
#Load the dll
Add-Type -path "D:\Unattend\UserFiles\Tools\Microsoft.Search.Interop.dll"
#Create an instance of CSearchManagerClass
$sm = New-Object Microsoft.Search.Interop.CSearchManagerClass
#Next we connect to the SystemIndex catalog
$catalog = $sm.GetCatalog("SystemIndex")
#Get the interface to the scope rule manager
$crawlman = $catalog.GetCrawlScopeManager()
#add scope
$crawlman.AddUserScopeRule("file:///D:*",$true,$false,$null)
$crawlman.SaveAll()
I would add a comment to the existing threads but I am not able to because I don't have reputation of 50 (dumb rule IMO).
Last... I found this site which lists the DLL along with some code but it hasn't been updated in a long time.
https://github.com/FileMeta/WindowsSearchSample
Thanks in advance!
Batch script that runs at boot:
#echo off
echo Windows Search is being restarted to recognize the Z drive
:while
if EXIST Z:\Watch (
I WANT TO CALL POWERSHELL SCRIPT TO ADD THE LOCATION TO THE INDEX IF NEEDED HERE
sc stop WMPNetworkSvc
ping 127.0.0.1 -n 5 > nul
sc stop WSearch
ping 127.0.0.1 -n 5 > nul
sc start WSearch
ping 127.0.0.1 -n 5 > nul
sc start WMPNetworkSvc
echo Exiting this script in 5 seconds
ping 127.0.0.1 -n 5 > nul
exit
) else (
echo Waiting 60 seconds to check if Z drive is available
ping 127.0.0.1 -n 60 > nul
goto :while
)
When I do a search for Searchdll in what I believe to be the folder where the Windows SDK installed to (C:\Program Files (x86)\Windows Kits\10) I find the following. If I had to guess which DLL is the Windows 10 equivalent of Windows 7's Microsoft.Search.Interop.dll I would guess that it's the 1st one i.e. interop.searchapi.dll.
Add-Type -Path "C:\Program Files (x86)\Windows Kits\10\bin\10.0.19041.0\x64\interop.searchapi.dll" does return without error... however $sm = New-Object Microsoft.Search.Interop.CSearchManagerClass returns with error that it cannot find the class in the assembly.
When I cd to "C:\Program Files (x86)\Windows Kits\10\bin\10.0.19041.0\x64" and enter ([appdomain]::currentdomain.GetAssemblies() | Where-Object Location -Match 'interop.searchapi').gettypes() I get the following
When I enter (([appdomain]::currentdomain.GetAssemblies() | Where-Object location -match 'interop.searchapi.dll').gettypes() | Where-Object name -eq 'CSearchManagerClass').getmembers() | Format-Table name, membertype I get
From the list of commands in the previous threads I do see GetCatalog and I presume that the members GetCrawlScopeManager, AddUserScopeRule, Reset, and SaveAll exist.
I don't know how to find the fully qualified class name or I'm doing something else wrong (unknowingly).
When I enter ([appdomain]::currentdomain.GetAssemblies() | Where-Object Location -Match 'interop.searchapi').fullname I get the following
Interop.SearchAPI, Version=10.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
But when I enter $sm = New-Object Interop.SearchAPI.CSearchManagerClass I get an error that it can't find the type Interop.SearchAPI.CSearchManagerClass.

List Last Windows Password Change For All Users On A Non-Domain System

I have found an answer to this question for systems that are attached to an AD domain controller. However, this question is for standalone systems where there is no possibility of attaching to a domain controller. Essentially, air-gapped systems.
Short and sweet: Is there a way to list the last time each user changed their Windows password for a non-domain, air-gapped system (either Windows 7 or 10) all at once either as a batch file or PowerShell script?
I know that net user {username} | find /I "Password last set" will do it for them one at a time. However, that would be tedious to run multiple times per machine and we have over 60 systems of this type. So I'm looking for a way to do this in one fell swoop, if possible.
As a caveat, we don't have the option of installing the activedirectory module in PowerShell for this. Also, since the majority of the systems are Windows 7, we don't have access to the Bash command line tools that would be available in Windows 10.
Any and all help with regard to this is appreciated.
Here's one way using the ADSI WinNT provider:
$computerName = [Net.Dns]::GetHostName() # i.e., local computer
$computer = [ADSI] "WinNT://$computerName,Computer"
$childObjects = $computer.Children
foreach ( $childObject in $childObjects ) {
if ( $childObject.Class -eq "User" ) {
if ( $childObject.PasswordAge[0] -gt 0 ) {
$pwdLastSet = (Get-Date).AddSeconds(-$childObject.PasswordAge[0])
}
else {
$pwdLastSet = $null
}
$childObject | Select-Object `
#{Name="AdsPath"; Expression={$_.AdsPath}},
#{Name="PasswordLastSet"; Expression={$pwdLastSet}}
}
}

batch file open windows and resize them

I am currently trying to open two windows through a batch file and then resize and move them (to be splitscreen). Opening the separate windows is easy:
#echo off
cd "C:\Program Files (x86)\Internet Explorer"
start iexplore.exe
cd "C:\Program Files (x86)\Mozilla Firefox"
start firefox.exe
exit
but I can't find a way to resize and move the windows I am opening. I would prefer not having to use any third party programs. I tried looking through the start /? help menu and don't believe any of the options are of use to me.
Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. All rights reserved.
C:\WINDOWS\system32>start /?
Starts a separate window to run a specified program or command.
START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
[command/program] [parameters]
"title" Title to display in window title bar.
path Starting directory.
B Start application without creating a new window. The
application has ^C handling ignored. Unless the application
enables ^C processing, ^Break is the only way to interrupt
the application.
I The new environment will be the original environment passed
to the cmd.exe and not the current environment.
MIN Start window minimized.
MAX Start window maximized.
SEPARATE Start 16-bit Windows program in separate memory space.
SHARED Start 16-bit Windows program in shared memory space.
LOW Start application in the IDLE priority class.
NORMAL Start application in the NORMAL priority class.
HIGH Start application in the HIGH priority class.
REALTIME Start application in the REALTIME priority class.
Press any key to continue . . .
If you have PowerShell installed (and you likely do), you can use user32.dll to move and adjust windows. Once upon a time, I needed a script for work that does exactly what you need and I found this and adjusted it to suit my needs. I then used this to convert it to a batch/powershell hybrid so that I only had to double-click the file to get the PowerShell script to run.
<# :
:: Based on https://gist.github.com/coldnebo/1148334
:: Converted to a batch/powershell hybrid via http://www.dostips.com/forum/viewtopic.php?p=37780#p37780
#echo off
setlocal
cls
set "POWERSHELL_BAT_ARGS=%*"
if defined POWERSHELL_BAT_ARGS set "POWERSHELL_BAT_ARGS=%POWERSHELL_BAT_ARGS:"=\"%"
endlocal & powershell -NoLogo -NoProfile -Command "$_ = $input; Invoke-Expression $( '$input = $_; $_ = \"\"; $args = #( &{ $args } %POWERSHELL_BAT_ARGS% );' + [String]::Join( [char]10, $( Get-Content \"%~f0\" ) ) )"
goto :EOF
#>
# Add the relevant section of the Win32 API to the PowerShell session
# Allows windows to be moved and resized
Add-Type #"
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
}
"#
################################################################################
# Moves and resizes the window based the broswer
#
# Arguments: $browser - the browser being moved and resized
# Returns: None
################################################################################
Function MoveAndResize ($browser)
{
# $browser_path is the full path to the browser
# $screen_x is the horizontal location of the window on the screen
# $screen_y is the vertical location of the window on the screen
# $win_x is the width of the target window
# $win_y is the height of the target window
Switch($browser){
InternetExplorer{
$browser_path="C:\Program Files\Internet Explorer\IEXPLORE.EXE"
$screen_x = 0
$screen_y = 0
$win_x = 960
$win_y = 1080
break
}
Firefox{
$browser_path="C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
$screen_x = 960
$screen_y = 0
$win_x = 960
$win_y = 1080
break
}
default {continue}
}
# Start the desired browser
Start-Process $browser_path
# Wait one second until the browser is fully loaded
Start-Sleep -S 1
# Find the running process where the application path matches $browser_path
$browser = (Get-Process | where {$_.Path -eq $browser_path}).MainWindowHandle
[Win32]::MoveWindow($browser, $screen_x, $screen_y, $win_x, $win_y, $true)
}
MoveAndResize "InternetExplorer"
MoveAndResize "Firefox"
Note that I'm using the Program Files version of iexplore instead of the Program Files (x86) version because that one wouldn't move or resize for some reason.

Detect a broken internet connection using windows batch programming

I'm using an internet connection which goes down after some time. If I repair my connection it works fine. I have to do it always manually. I want to do this task automatically.
I.e. I want to create a windows batch file which is constantly running in the background. When my internet connection is down, it will renew and restart the connection again without any interaction
I want to do this task using a windows batch file. I tried this:
runas /user:local\administrator
ipconfig /release
ipconfig /flushdns
ipconfig /renew
However, I don't know how to detect whether Network connection is down or up?
I'm hoping for quick and positive response.
I made this some time ago. I think that will help you. (but in is spanish)
https://github.com/edgardok/Arregla_Internet/blob/master/ARREGLA.INTERNET.bat
:INICIO
IF EXIST respuesta.tmp DEL respuesta.tmp >nul
PING %DIRECCIONREMOTA% > respuesta.tmp
FIND /C /I "perdidos = 0" respuesta.tmp >nul
GOTO CASO%ERRORLEVEL%
:CASO1
REM ***conexion fallida***
ECHO %date% %time%. NO ESTA HABILITADA LA PLACA DE RED O NO FUNCIONA.
GOTO menu
:CASO0
REM ***conexion OK***
ECHO %date% %time%. Conexion ok.
GOTO menu
You could try and ping a widely used service in your country (or ping google like crazy) to detect internet connectivity. it's not bullet proof, but will let you know when your internet is down (probably).
The result of pinging could be checked by batch/script and according to the result, decide whether you want to ipconfig /renew or not.
The problem you must be trying to address is
Why your network connection is breaking after sometime
and not
How to repair your network connection every now and then
because if you are able to identify the root cause for first problem then you are done.
f 'r sng Wndws r bv, cn tr ths:
fcnfg | grp -c "P ddrss"
Ths wll gv th nmbr f mtchng P drsss - n cs r cnnctn s dwn, 'll hv fwr thn nrmll.
'll nd grp fr ths (s t's nt prt f Wndws), bt t cn b btnd frm ths RL: nxtls.srcfrg.nt

PowerShell Script Running as a Service Behaves Strangely

PowerShell Script Running as a Service Behaves Strangely
The Project:
Create a background process that determines if the on board network card is connected. If it is connected, disable the wireless network card. When the onboard network card is not connected, re-enable the wireless card.
Why:
Users hot-dock all the time, getting funky routing tables OR get bound to the wrong DNS servers. When they attempt to access a local resource, say printers, they aren’t able to and then are in my cube (they would file a ticket, but that too would be a local resource). Trying to convince users to disable their own wireless (via switch on laptop) or not hot dock has met with limited success.
The Problem:
The PowerShell script below does run, and does work under my testing conditions. Likely under most testing conditions as the code and wmi queries are pretty generic. Running the script manually yields the expected results, HOWEVER running the script as a service via the only method I could find, srvany.exe, yielded unexpected results and “broke stuff”.
Details:
Running the script as a service, via srvany.exe, works ONCE. When the loop comes back around to test the network connection or tries the method to enable or disable it. The errors indicate that “get-wmiobject” is not a proper Cmdlet. Huh? It works, manually, it works once, but a second time after it disabled the wireless network card it does not. Worse yet MY shell , outside of the service, suddenly can’t do a get-wmiobject, until…. until you go into Device Manager and re-enable the wireless network card yourself.
Debugging attempts:
I rewrote the script and cleaned it up a little to allow for it to get the objects outside of the Do While loop. Nothing changed, but I left the script that way as it seems cleaner anyhow. I enabled “Interact with Desktop” in the service properties and sure enough you can see the script trying to work and getting the before mentioned errors.
Please help. Again the object here is to run a background process, one with enough privileges in Vista or 7 to disable and enable the wireless network card.
#***********************************************************************
# "switch-wifi-srv.ps1"
# This script attempts to identify if a wired network card is in use if
# one is, the Wireless network card is disabled, until the wired network
# card is no longer in use.
#
# Written by Aaron Wurthmann - aaron (AT) wurthmann (DOT) com
#
# 2010.02.10 ver 2 (Service Version)
# If you edit please keep my name or at the very least original author's.
# As of this writing I am unsure if script will work with all scenarios,
# however it has worked for me on Dell laptops running Windows 7 x64.
# -----------------------------------------------------------------------
# This script comes with ABSOLUTELY NO WARRANTY.
# You may redistribute copies of the script under
# the terms of the GNU General Public License.
# -----------------------------------------------------------------------
# Service Installation:
# Aquire and install the Windows 2003 Resource Kit OR the srvany.exe.
# Use sc.exe and srvany.exe to create a service....
# sc create SwitchWifiAuto binPath= "C:\Program Files (x86)\Windows Resource Kits\Tools\srvany.exe" DisplayName= "Switch Wifi Automatically"
# Edit registry entry for SwitchWifiAuto, add a key and a string value...
# HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SwitchWifiAuto\Parameters]
# "Application"="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy RemoteSigned -File C:\\SwitchWifiAuto\\switch-wifi-srv.ps1"
#************************************************************************
$state=""
$wireStatus=""
$wifiStatus=""
# Get Wired and Wireless Card Objects
$objWire=get-wmiobject -class win32_networkadapter -namespace root\CIMV2 | Where-Object {$_.Name -notmatch "Wireless" -and $_.Name -notmatch "Virtual" -and $_.PhysicalAdapter -eq "True"}
$objWifi=get-wmiobject -class win32_networkadapter -namespace root\CIMV2 | where-object {$_.Name -match "Wireless"}
# Get Name of Service to be Used in totally useless Do While Loop
$objService=get-service -display "Switch Wifi Automatically"
# Begin Do While Loop
Do {
# Get status of wired network card. If enabled and connected set $state to Disable (which will later Disable the Wifi network card)
[string]$wireStatus=$objWire | % {$_.NetEnabled}
if($wireStatus -eq "True") {
$state="Disable"
}
# Get Status of wireless card.
if($objWifi){
[string]$wifiStatus=$objWifi | % {$_.NetEnabled}
# If $state is not set to disable and if the wireless card is currently disabled, enable it.
if($state -ne "Disable") {
if($wifiStatus -eq "False") {
Out-Null -InputOject ($objWifi | % {$_.Enable()})
}
# If $state is set to Disable and if wireless card is currently enabled, disable it.
} else {
if($wifiStatus -eq "True") {
Out-Null -InputOject ($objWifi | % {$_.Disable()})
}
}
}
# Reset Checked Variables for good measure
$state=""
$wireStatus=""
$wifiStatus=""
# Sleep for 120 seconds (two minutes)
Start-Sleep -s 120
# Continuing looping (do while) until the service is not running.
# This is of course technically useless as when the service is not running neither is the script to check if the service is not running.
# I made it this way however because I don't like infinite loops and I thought it would be funny to it this way instead of while $var=0
} while ($objService.Status -eq "Running")
Try to remove any output. Service don't have stdout stream. And when the buffer is full strange thing happens. Just a guess ( I never used powershell ).
Debugging attempts: I rewrote the script and cleaned it up a little to
allow for it to get the objects outside of the Do While loop.
You need to include these within the loop or you will not get updated values and the loop will do nothing.

Resources