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.
Related
I want to make my computer sleep from the command line (DOS, PS, or WSL) in a way so that it wakes up when I click the mouse or press a key - exactly how it works when one clicks "Start -< Power -> Sleep"
The following DO NOT WORK - all of the below put the machine into some other kind of deeper sleep, which ignores keyboard/mouse input (it's a laptop plugged into a monitor - I have to open its lid and press the power button to wake it, which messes up my desktop...)
psshutdown -d -t 0
C:\Windows\System32\rundll32.exe powrprof.dll,SetSuspendState 0,1,0
C:\Windows\System32\rundll32.exe powrprof.dll,SetSuspendState 1,1,0
[Void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") ; $PowerState = [System.Windows.Forms.PowerState]::Suspend; [System.Windows.Forms.Application]::SetSuspendState($PowerState, $false, $false);
(aka)
powershell -Command "[Void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') ; $PowerState = [System.Windows.Forms.PowerState]::Suspend;echo Zzzz;[System.Windows.Forms.Application]::SetSuspendState($PowerState, $false, $false);"
Is there maybe some way to inject key-presses into the windows buffer? This would probably do the trick, if it's possible?:-
Ctrl-Esc, Up-Arrow, Right-Arrow, Right-Arrow, Right-Arrow, Right-Arrow, Enter, Enter
Does the Accessibility subsystem have any easy way to find desktop UI elements (the start menu) and trigger actions on them maybe ? (A click on the "Sleep").
Obviously - the best answer would be if anyone knows exactly what system call windows itself is making when that sleep button is pressed!
I guess this literally answers my question, although it's not ideal (takes a long time, is prone to probably going wrong if keys are pressed in the middle).
powershell - Command "$wshell = New-Object -ComObject wscript.shell;
$explorerpid = Get - Process | Select MainWindowTitle, ProcessName, Id | where {
$_.ProcessNAme - eq 'explorer'
} | foreach {
$_.Id
};
$wshell.AppActivate($explorerpid);
sleep 1;
$wshell.SendKeys('^{ESC}');
sleep 1;
$wshell.SendKeys('{UP}');
sleep 1;
$wshell.SendKeys('{RIGHT}');
sleep 1;
$wshell.SendKeys('{RIGHT}');
sleep 1;
$wshell.SendKeys('{RIGHT}');
sleep 1;
$wshell.SendKeys('{RIGHT}');
sleep 1;
$wshell.SendKeys('{ENTER}');
sleep 1;
$wshell.SendKeys('{ENTER}');
True
The above can be put into a .bat file, or made into a shortcut to make it easier to get to as well.
If anyone knows the correct way to invoke whatever underlying call the explorer.exeprocess is using to trigger a sleep directly, do please let us know!
This is another method which doesn't work for me - might work for others though?
(powershell):-
$PowrProf = Add-Type -MemberDefinition "[DllImport(`"PowrProf.dll`", CharSet = CharSet.Unicode)]`npublic static extern bool SetSuspendState(bool bHibernate, bool bForce, bool bWakeupEventsDisabled);" -Name Kernel32 -Namespace Win32 -PassThru
$PowrProf::SetSuspendState($False, $True, $False) ;echo bForce is not used
From: https://learn.microsoft.com/en-us/windows/win32/api/powrprof/nf-powrprof-setsuspendstate
p.s. The above also shows you how to call arbitrary windows API functions from the command line. Note that the weird things with backticks ` in front of them are powershell escapes for newline `n and quotes `"
Here also is yet-another, which simply does nothing whatsoever for me:-
$Kernel32 = Add-Type -MemberDefinition "[DllImport(`"kernel32.dll`", CharSet = CharSet.Unicode)]`npublic static extern bool SetSystemPowerState(bool fSuspend, bool fForce);" -Name Kernel32 -Namespace Win32 -PassThru
$Kernel32::SetSystemPowerState($True, $False)
Whatever explorer.exe is doing with their "sleep" button is clearly not using any of the above documented APIs - grrr!!
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.
This question shows a Powershell script to generate a list of open File Explorer windows and their path.
My goal is to capture the currently open set of explorer windows, and write out a CMD file with commands like: C:\WINDOWS\explorer.exe /e, "C:\open\this\folder"
So I would like to have the full path and folder name in normal path notation. This is what is showing in titlebar of the Explorer Windows: "C:\open\this\Favorite folder"
The proposed code is:
function Get-WindowTitle($handle) {
Get-Process |
Where-Object { $_.MainWindowHandle -eq $handle } |
Select-Object -Expand MainWindowTitle
}
$app = New-Object -COM 'Shell.Application'
$app.Windows() |
Select-Object LocationURL, #{n='Title';e={Get-WindowTitle $_.HWND}}
As shown above, LocationURL provides a full path in an escaped-URL style:
file:///C:/open/this/Favorite%20%folder"
The #{n='Title';e={Get-WindowTitle $_.HWND}} component produces a column "Title" which is truncated to 5 characters:
C:\...
The full output for one explorer window looks like:
LocationURL Title
----------- -----
file:///C:/open/this/Favorite%20%folder C:...
I found I could avoid the truncation by padding the string 'Title' with many spaces. That string's width seems to determine the maximum width of the output.
Still, I observe that only about 60% of the open explorer windows list a path. The rest are just a blank line.
I tried "$app.Windows() | Select-Object LocationName", but the output only contains the Explorer folder name only, not the full path and folder that is displayed in the Explorer title.
Another mystery is why the script runs so slowly. If I have 10 explorer windows open, the script runs for 30 seconds, taking about 3 seconds per path.
For this script:
function Get-WindowTitle($handle) {
Get-Process |
Where-Object { $_.MainWindowHandle -eq $handle } |
Select-Object -Expand MainWindowTitle
}
$app = New-Object -COM 'Shell.Application'
$app.Windows() |
Select-Object LocationName,#{n=' ------------Title---------------- ';e={Get-WindowTitle $_.HWND}}
This is the output (with some redacting with *** for privacy)
PS C:\E***> .\OpenExplorer.ps1
LocationName ------------Title----------------
------------ ----------------------------------------------------------------------------------
2019-07
Ame****
2019 Priv...
2019-10-3... C:\E\Event Presentations\2019-10-31 Priv**********bcast
E C:\E
5G Brief ... C:\E\Tech************ing\5G Brief (2018)
36 Series...
2019 DE* ... C:\E\16*****N\2019 DE*******************
Newsletters C:\E\Newsletters
Reports C:\E\Tech************ing\Reports
2019-10-2... C:\E\16**********s\2019-10-29 *********************
2019-11 C:\Data\Docs\Stand*********24\2019-11
UB****
Financial... C:\E\Financ************
Expenses C:\E\Internal\Expenses
E C:\E
E***
I assume what you're really interested is the local filesystem paths of the open Explorer windows, not necessarily the window titles (which aren't guaranteed to reflect the full paths).
Somewhat obscurely, the window objects returned by the .Windows() method contain the local path representation in their .Document.Folder.Self.Path property.
(New-Object -ComObject 'Shell.Application').Windows() | ForEach-Object {
$localPath = $_.Document.Folder.Self.Path
"C:\WINDOWS\explorer.exe /e, `"$localPath`""
}
The above produces output such as:
C:\WINDOWS\explorer.exe /e, "C:\Users\jdoe"
C:\WINDOWS\explorer.exe /e, "C:\Program Files"
You can output this to a batch file file as needed, e.g. by appending | Set-Content file.cmd to the above command.
Note: The windows are listed in the order in which they were created, so you cannot infer which among them was most recently activated. See this answer for a solution that finds the topmost File Explorer window and determines the path shown in it.
I found I could avoid the truncation
The truncation is just a display artifact - the data is still there.
You can make the data visible in one of two ways:
pipe to Format-Table -AutoSize to make sure that column values aren't truncated, space permitting
pipe to Format-List, which will show each property on its own line (line-wrapping overly long values).
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 WwBXAGkAbgBkAG8AdwBzAC4AUwB5AHMAdABlAG0ALgBVAHMAZQByAFAAcgBvAGYAaQBsAGUALgBMAG8AYwBrAFMAYwByAGUAZQBuACwAVwBpAG4AZABvAHcAcwAuAFMAeQBzAHQAZQBtAC4AVQBzAGUAcgBQAHIAbwBmAGkAbABlACwAQwBvAG4AdABlAG4AdABUAHkAcABlAD0AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAF0AIAB8ACAATwB1AHQALQBOAHUAbABsAA0ACgBBAGQAZAAtAFQAeQBwAGUAIAAtAEEAcwBzAGUAbQBiAGwAeQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBSAHUAbgB0AGkAbQBlAC4AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAA0ACgAkAGEAcwBUAGEAcwBrAEcAZQBuAGUAcgBpAGMAIAA9ACAAKABbAFMAeQBzAHQAZQBtAC4AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAFMAeQBzAHQAZQBtAEUAeAB0AGUAbgBzAGkAbwBuAHMAXQAuAEcAZQB0AE0AZQB0AGgAbwBkAHMAKAApACAAfAAgAD8AIAB7ACAAJABfAC4ATgBhAG0AZQAgAC0AZQBxACAAJwBBAHMAVABhAHMAawAnACAALQBhAG4AZAAgACQAXwAuAEcAZQB0AFAAYQByAGEAbQBlAHQAZQByAHMAKAApAC4AQwBvAHUAbgB0ACAALQBlAHEAIAAxACAALQBhAG4AZAAgACQAXwAuAEcAZQB0AFAAYQByAGEAbQBlAHQAZQByAHMAKAApAFsAMABdAC4AUABh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dABoAGUAcgBpAG4AZwBBAHMAeQBuAGMAKAApACkAIAAoAFsAVwBpAG4AZABvAHcAcwAuAE4AZQB0AHcAbwByAGsAaQBuAGcALgBOAGUAdAB3AG8AcgBrAE8AcABlAHIAYQB0AG8AcgBzAC4ATgBlAHQAdwBvAHIAawBPAHAAZQByAGEAdABvAHIAVABlAHQAaABlAHIAaQBuAGcATwBwAGUAcgBhAHQAaQBvAG4AUgBlAHMAdQBsAHQAXQApAA==
(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 WwBXAGkAbgBkAG8AdwBzAC4AUwB5AHMAdABlAG0ALgBVAHMAZQByAFAAcgBvAGYAaQBsAGUALgBMAG8AYwBrAFMAYwByAGUAZQBuACwAVwBpAG4AZABvAHcAcwAuAFMAeQBzAHQAZQBtAC4AVQBzAGUAcgBQAHIAbwBmAGkAbABlACwAQwBvAG4AdABlAG4AdABUAHkAcABlAD0AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAF0AIAB8ACAATwB1AHQALQBOAHUAbABsAA0ACgBBAGQAZAAtAFQAeQBwAGUAIAAtAEEAcwBzAGUAbQBiAGwAeQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBSAHUAbgB0AGkAbQBlAC4AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAA0ACgAkAGEAcwBUAGEAcwBrAEcAZQBuAGUAcgBpAGMAIAA9ACAAKABbAFMAeQBzAHQAZQBtAC4AVwBpAG4AZABvAHcAcwBSAHUAbgB0AGkAbQBlAFMAeQBzAHQAZQBtAEUAeAB0AGUAbgBzAGkAbwBuAHMAXQAuAEcAZQB0AE0AZQB0AGgAbwBkAHMAKAApACAAfAAgAD8AIAB7ACAAJABfAC4ATgBhAG0AZQAgAC0AZQBxACAAJwBBAHMAVABhAHMAawAnACAALQBhAG4AZAAgACQAXwAuAEcAZQB0AFAAYQByAGEAbQBlAHQAZQByAHMAKAApAC4AQwBvAHUAbgB0ACAALQBlAHEAIAAxACAALQBhAG4AZAAgACQAXwAuAEcAZQB0AFAAYQByAGEAbQBlAHQAZQByAHMAKAApAFsAMABdAC4AUABhAHIAYQBtAGUAdABlAHIAVAB5AHA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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
I want to create a batch file which runs a program for 7 seconds, irrespective of the completion of execution of the other program. I also want that the program should take input and save the output in an external file. This is what I tried:
start program.exe
ping 1.1.1.1 -n 1 -w 7000 > nul
taskkill /im program.exe /f
rem continue here
The above works fine, but when I replace line 1 with:
start program.exe < in.txt > out.txt
then input from file and output in file doesn't work.
cmd doesn't set the STARTF_USESTDHANDLES flag of the CreateProcess STARTUPINFO structure. Instead, it temporarily redirects its own standard handles and relies on inheritance. This approach works even if cmd has to call ShellExecuteEx, which lacks a way to explicitly set the standard handles.
However, redirecting its own standard handles doesn't work when CREATE_NEW_CONSOLE is set in the process creation flags, which is the default for the start command. To avoid this problem, use the /b option to prevent creating a new console.
You may also want to redirect stderr to stdout or a file. This prevents errors from being written to the console. For example:
start /b program.exe <in.txt >out.txt 2>&1
start /b program.exe <in.txt >out.txt 2>err.txt
start /b program.exe <in.txt >out.txt 2>nul
Example using Debugging Tools for Windows
(test) C:\>cdb -Goxi ld cmd
Microsoft (R) Windows Debugger Version 6.12.0002.633 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.
CommandLine: cmd
Symbol search path is: symsrv*symsrv.dll*
C:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is:
(ed0.1770): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00000000`77848700 cc int 3
0:000> .reload /f
Reloading current modules
.....
0:000> bp CreateProcessW
0:000> g
Run where.exe in a new console.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
(test) C:\>start /w where.exe <nul >nul
Breakpoint 0 hit
kernel32!CreateProcessW:
00000000`775a0660 4883ec68 sub rsp,68h
Note that cmd.exe redirects its StandardOutput before calling CreateProcess:
0:000> ?? ((ntdll!_PEB *)#$peb)->ProcessParameters->StandardOutput
void * 0x00000000`00000060
0:000> !handle 60 3
Handle 60
Type File
Attributes 0
GrantedAccess 0x120196:
ReadControl,Synch
Write/Add,Append/SubDir/CreatePipe,WriteEA,ReadAttr,WriteAttr
HandleCount 2
PointerCount 3
The process creation flags, i.e. dwCreationFlags, the 6th parameter:
0:000> dd (#rsp + 6*8) l1
00000000`00182c58 00080410
is passed as 0x80410, which is a bitwise OR of the following flags:
EXTENDED_STARTUPINFO_PRESENT
CREATE_UNICODE_ENVIRONMENT
CREATE_NEW_CONSOLE
Because a new console is created, where.exe doesn't inherit cmd's standard handles:
0:000> g
Symbol search path is: symsrv*symsrv.dll*
C:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is:
(1550.1a80): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00000000`77848700 cc int 3
1:001> ?? ((ntdll!_PEB *)#$peb)->ProcessParameters->StandardOutput
void * 0x00000000`00000007
Note: in Windows 8+ a console handle is just a regular file handle, so you'll have to look deeper.
I'm using Windows 7 for this example, so console handles are fake handles tagged by setting the lower 2 bits (e.g. 3, 7, 11 => 0b0011, 0b0111, 0b1011). By 'fake' I mean they're not in the process handle table used for kernel object handles. Thus, for example, you can't use the debugger !handle command to inspect handle 7:
1:001> !handle 7 f
Could not duplicate handle 7, error 87
In Windows 7, console handles are allocated and managed by the console host process, conhost.exe. They're tagged so Windows base functions can make the required LPC call to conhost.exe via NtRequestWaitReplyPort.
The above example demonstrated how creating a new console overrides inheriting cmd's redirected standard handles. Now let's add the /b option to prevent creating a new console.
1:001> g
(test) C:\>start /b /w where.exe <nul >nul
Breakpoint 0 hit
kernel32!CreateProcessW:
00000000`775a0660 4883ec68 sub rsp,68h
dwCreationFlags is 0x80600:
0:000> dd (#rsp + 6*8) l1
00000000`00182c58 00080600
which is a bitwise OR of the following creation flags:
EXTENDED_STARTUPINFO_PRESENT
CREATE_UNICODE_ENVIRONMENT
CREATE_NEW_PROCESS_GROUP
(A side effect of specifying /b is to create the process as the leader of a new process group. If it's a console process, this allows generating a Ctrl+Break event that targets the group.)
In this case, where.exe does inherit the redirected standard handles from cmd.exe:
0:000> g
Symbol search path is: symsrv*symsrv.dll*
C:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is:
(1508.1534): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00000000`77848700 cc int 3
1:001> ?? ((ntdll!_PEB *)#$peb)->ProcessParameters->StandardOutput
void * 0x00000000`00000064
1:001> !handle 64 3
Handle 64
Type File
Attributes 0
GrantedAccess 0x120196:
ReadControl,Synch
Write/Add,Append/SubDir/CreatePipe,WriteEA,ReadAttr,WriteAttr
HandleCount 3
PointerCount 4
Again, in Windows 7 it's easy to spot a console pseudo handle because it's tagged by setting the low 2 bits of the handle value. For Windows 8+, a quick check is to look at the low nibble (4 bits) of the file's granted access, for which read data access is 1, write data access is 2, and append data access is 4. A file opened for a console buffer has both read and write access, whereas cmd's redirection uses either read (<) or write (>), but not both. The above is the redirected output, and you can see the file is opened with write and append access (2+4), but not read access. That's a quick check, but if you want to be certain you can use a kernel debugger such as kd.exe, or a tool such as Sysinternals Process Explorer or handle.exe. These can show you the NT kernel object path, such as \Device\ConDrv\Input for a Windows 8+ console input handle.