Script for locating "Service" locations in Windows - windows

I am trying to write a script in windows command prompt (windows 8), to find out the directory location of services running. For example
net start // gives all the running services. I want to know the location of those services
Help required!

The following command is using PowerShell in order to display what you want:
powershell.exe -noexit "Get-WmiObject win32_service | select Name, DisplayName, State, PathName"
Just copy and paste it into a "cmd" window.
It will display you the service name, the display name, the state and the path to the executable.

Related

Windows Server RDRemoteApp with Custom Configuration Argument

I have multiple users using a Windows Server 2016 Remotely.
Currently, each user has an exe file on their desktop - program.exe with a custom configuration argument:
program.exe --conf=D:/username/config.ini
Now I'd like to set up this program as a RemoteApp over RDP. How do I set the custom argument for every user individually to go to a specific path? (or a rule, like ~/config.ini under home directory)
It isn't really clear what you are asking, however you can set the arguments for the remoteapp by right clicking, choosing "properties" and setting the command line arguments.
If you are asking for powershell:
New-RDRemoteApp -CollectionName "Remoteapp Collection" -DisplayName "Some program" -FilePath "C:\Program Files\Program\program.exe" -CommandLineSetting Require -RequiredCommandLine "--conf=D:/username/config.ini"

Opening up Windows Terminal with elevated privileges, from within Windows Terminal

There are plenty of questions here which asks how to elevate priviliges from powershell, and almost all of them recommend this command:
Start-Process -Verb RunAs powershell.exe .....
(or pwsh.exe for Powershell Core)
And this works, it opens up a new Powershell window with elevated privileges, after having gone through a UAC block to verify access.
However, while I'm using Powershell, I'm doing it inside Windows Terminal, the new terminal application for Windows 10, and I would like to open a new instance of Windows Terminal with elevated privileges, not just a Powershell window.
So I tried these commands:
Start-Process -Verb RunAs wt
Start-Process -Verb RunAs wt.exe
Start-Process -Verb RunAs (Get-Command wt)
Start-Process -Verb RunAs "C:\Users\lasse\AppData\Local\Microsoft\WindowsApps\wt.exe"
They all fail with:
Start-Process: This command cannot be run due to the error: The file cannot be accessed by the system..
I'm assuming this has something to do with where the executable is located, within my profile, but if I right-click the Windows Terminal icon I have on my task bar and choose to run it as administrator, it opens up just fine. This is what I want to duplicate.
So is there a way for me to modify either the commands I tried above, or change some access setting that would make this work?
For my specific instance, I simply want to make it simpler to pop open an admin terminal, I don't need a way to elevate arbitrary commands, then I will happily use the commands I have already shown here.
Currently you cannot open an elevated wt.exe session from the command line without workarounds. Workarounds include using gsudo, Using Task Scheduler (I tested this one and it works but you need to use the full path to wt.exe and you can skip the shortcut creation step) OR if you are ok with a keyboard shortcut, the simplest way; using a keyboard shortcut to run Windows Terminal as Admin from the taskbar.
For your use case:
For my specific instance, I simply want to make it simpler to pop open
an admin terminal, I don't need a way to elevate arbitrary commands,
then I will happily use the commands I have already shown here.
The simplest approach will work:
Pin Windows Terminal as the first item on the task bar. Then hit Win+Ctrl+Shift+1 to open it as admin.
If you really must launch Windows Terminal from the command line from within Windows Terminal then create a task in the Task Scheduler:
Give the task a name, check 'Run with highest privileges'.
Choose the 'Actions' tab, click 'New', select 'Start a program' as the action. Put the full path to wt.exe in the 'Program/script field'. Click OK. Click OK again.
Click 'Conditions' tab, uncheck "Start the task only if the computer is on AC power".
Click 'Settings' tab, make sure "Allow task to be run on demand" is checked and uncheck "Stop the task if running for longer than".
Finally in your shell (Powershell), launch an elevated Windows Terminal session by running the command: schtasks /run /TN "TASK_NAME" where TASK_NAME is the name you gave the task in step 1.
Try this:
powershell "Start-Process -Verb RunAs cmd.exe '/c start wt.exe'"
Also check out these links:
WT.exe command line arguments:
https://learn.microsoft.com/en-us/windows/terminal/command-line-arguments?tabs=windows
Article about adding Open Windows Terminal Command Prompt to the context menu in Explorer (includes Admin):
https://dkcool.tailnet.net/2020/07/add-open-windows-terminal-command-prompt-to-the-explorer-context-menu-in-windows-10/
Article about adding Open Admin Command Prompt to the context menu in Explorer:
https://dkcool.tailnet.net/2019/05/add-open-admin-command-prompt-to-the-explorer-context-menu-in-windows-10/
Not a direct answer but another option if you have PowerToys is to:
Alt + Space, type Terminal,
Select Run as Administrator (or Ctrl + Shift + Enter)
You can install PowerToys using WinGet
With recent releases, this issue appears to be fixed. It works now, doing exactly as you originally tried and failed (Start-Process -verb RunAs wt). I would recommend trying again now with the latest releases (at least Windows Terminal, and perhaps PowerShell as well).
No need for workarounds anymore!!
Windows Terminal has a feature to automatically run as administrator in the preview; no need for workarounds now.
Pin to the Taskbar and hold Ctrl + Shift while left clicking on the Windows Terminal icon.
In my particular case I also need Windows Terminal opened as administrator all the time. This is what I did, run "where wt" to display the path where Windows Terminal application exe is located, it should be C:\Users\YOURUSER\AppData\Local\Microsoft\WindowsApps\wt.exe.
I created a shortcut to that file and checked "Run as administrator" in the advanced properties, then I just pinned it to start and voila. You can delete your temporary shortcut after that if you want.
You can create a shortcut to always run Windows Terminal as administrator using this powershell script:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\Windows Terminal.lnk")
$Shortcut.TargetPath = "$env:LOCALAPPDATA\Microsoft\WindowsApps\Microsoft.WindowsTerminal_8wekyb3d8bbwe\wt.exe"
$Shortcut.Save()
$bytes = [System.IO.File]::ReadAllBytes("$Home\Desktop\Windows Terminal.lnk")
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON
[System.IO.File]::WriteAllBytes("$Home\Desktop\Windows Terminal.lnk", $bytes)
You can just paste it and run it from Windows Powershell ISE, it will create a Windows Terminal.lnk file on your desktop. Whenever you double click on that shortcut Windows terminal will run as an admnnistrator
I know this answer does not fully match your question but given that also other answers were oriented in this way I hope this won't disturb the discussion.
I always need to run PowerShell as Administrator and I only want to use Windows Terminal, which given it's restrictions cannot be configured to run always as Administrator.
I hated the need to use shortcuts and other hacks I found being suggested online, so I think I found a better solution but you have to pay the cost of a 1/2 seconds at startup.
Locate your user profile (A profile is a Windows PowerShell ISE script that runs automatically when you start a new session) using _ $PROFILE
Edit profile with any preferred editor _ code $PROFILE
Adde the following code to the profile file and save it
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$host.ui.rawui.windowtitle="Bootstrapper"
Start-Process -Verb RunAs wt
} else {
$Processes = Get-Process | Where-Object {$_.mainWindowTitle -eq 'Bootstrapper' -and $_.name -eq 'WindowsTerminal'}
if($Processes.count -gt 0)
{
Stop-Process -Id $Processes[0].id
}
}
What the script do?
You can pin Windows Terminal icon to your application bar and when you click there WT will start as non elevated user, but the profile will understand if this is the case.
When you are not running as Administrator it will change the name of the window and start a new WT as administrator.
The new instance will also execute the profile file and if the instance is runinng as Administrator, it will look for the WT named Bootstrapper and kill it.
This proces takes between one and two seconds, I prefer this way other than right clicking on the icon.
It's likely you were just facing a Path issue. I know that the command examples you gave (e.g. Start-Process -verb RunAs wt) have worked for me for some time (as mentioned in #fialdrexs's answer).
Did you install Windows Terminal from a Github release or from the Store?
I currently have the following entry in my settings.json profiles list to add an elevated Windows Terminal to the drop down options:
{
// https://github.com/microsoft/terminal/issues/632#issuecomment-663686412
"name": "Windows Terminal (elevated)",
"commandline": "%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -Command Start-Process -Verb RunAs \"shell:appsFolder\\Microsoft.WindowsTerminal_8wekyb3d8bbwe!App\"",
"hidden": false,
"icon": "ms-appx:///Images/Square44x44Logo.targetsize-32.png"
}
The comment with the GitHub link should get you to where I originally found this information.
I find a away to workaround, just create a file bat with content
powershell Start-Process -Verb RunAs wt.exe
Save file yourfile.bat to folder you want.
Add path folder to System Environment.
Press WINDOW + R and type file bat name.
Currently this problem was fixed, but it ended up with a weird issue. Running wt.exe from Win+R, searching it on start menu, and starting itself from the terminal, show the same error message.
The application was unable to start correctly (0xc0000022). Click OK
to close the application.
However it works when executing wt via Command Prompt, PowerShell, and PowerShell Core.
So just a quick workaround answer, start PowerShell and run the command,
Start-Process -Verb RunAs wt.exe;
or the simpler
start -verb runas wt

Uninstalling Systrack from CMD

So I'm trying to remotely uninstall the application SysTrack using:
wmic product where "description='Systems Management Agent' " uninstall
but for some reason it can't find the product. Doing a
product get name
from the wmic:root console, I don't see it listed. I'm wondering why the wmic can't get all the list of installed programs? It shows up on programs and features list, but now when I run that wmi command. I am a domain admin so the credentials should be a problem (the folder in the Program Files(x86) folder for SysTrack does have a lock on it though, but I can access)
Side note: I really wish there was a way to remotely just view that programs and features menu. Would be incredibly handy for the tasks I've been doing lately.
try;
wmic product where "name like 'Systems Management Agent'" call uninstall /nointeractive
it should work.
Try this in powershell ise. It will take a list of hostnames from a text file and uninstall the application. Edit the path for your local directory and text file name.
This script is 2 lines. Everything before $app.Uninstall() is on one line and then $app.Uninstall() is the 2nd line.
$app = Get-WmiObject -Class Win32_Product -ComputerName (Get-Content -Path "C:\Users\MYUSERNAME\Documents\PowerShell\servers.txt") | Where-Object {$_.Name -match “Systems Management Agent”}
$app.Uninstall()

Windows 8.1 can't start Powershell from a cmd or powershell prompt - "This app can't run on your PC"

Powershell suddenly quit opening from both cmd and powershell prompts. I haven't installed anything new between when it did work and when it quit working.
When I try to start powershell.exe from a cmd window (both elevated and not elevated) with the following command
C:\Users\myuser>powershell.exe
I get a popup error from the OS that says:
This app can't run on your PC
Once I close that popup the cmd prompt I made the call from then prints:
Access is denied
To the screen (yes even when I do this in an elevated cmd prompt)
When I try to do it in powershell with the following command:
PS C:\Users\myuser> powershell.exe
I get:
Program 'powershell.exe' failed to run: The specified executable is not a valid application for this OS platform.
At line:1 char:1
+ powershell.exe
+ ~~~~~~~~~~~~~~.
At line:1 char:1
+ powershell.exe
+ ~~~~~~~~~~~~~~.
+ CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException
+ FullyQualifiedErrorID : NativeCommandFailed
Apparently even powershell doesn't like powershell anymore.
I've tried restarting the computer and that didn't fix it, but I'm totally stymied as to what to do next.
#PetSerAl gave the crucial pointer in comments on the question.
The "This app can't run on your PC" pop-up error message on Windows 8 or above
indicates:
a corrupted file, such as a 0-byte *.exe file, esp. when followed by an "Access denied" error in the console.
or, increasingly less commonly, an attempt to run a 64-bit executable on a 32-bit edition of Windows.
Troubleshooting steps:
From a Command Prompt (cmd.exe console), run where.exe <executable-name>;
from PowerShell, run Get-Command -All <executable-name>, which shows you all executables by that name present in the directories listed in the $env:PATH environment variable in that order, by their full paths.
Note that where.exe, unlike Get-Command, also looks in the current directory, and looks there first.
Thus, the first path returned is the executable that is actually executed when only the executable name is specified.
Note that a match in the current directory, if found by where.exe, only matters when calling the executable from cmd.exe (from the Command Prompt or a batch file), because PowerShell by design doesn't allow invocation of executables from the current directory by mere name.
If you want to run where.exe from PowerShell, extension .exe is required, because the command name where by itself is a built-in alias for the Where-Object cmdlet.
In the output from where.exe / Get-Command, check:
if the executable you expect is listed first.
if its size is non-zero.
Remove unexpected (zero-byte) executables, or, if you expect them to be there as functioning executables, reinstall them.
Example:
Look for all all executables named powershell.exe in the current directory and in the directories listed in $env:PATH.
Note that the proper home of powershell.exe is C:\Windows\System32\WindowsPowerShell\v1.0, as reflected in $PSHOME.
From cmd.exe (regular Command Prompt):
where powershell.exe
Example output:
C:\Windows\System32\powershell.exe
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
From PowerShell:
Get-Command -All powershell.exe
If you also want to look in the current directory, use
Get-Command -All .\powershell.exe, powershell.exe
Example output:
CommandType Name Version Source
----------- ---- ------- ------
Application powershell.exe 0.0.0.0 C:\WINDOWS\system32\powershell.exe
Application powershell.exe 10.0.14... C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe
If you want to include the file size in the output:
PS> where.exe powershell.exe | % { [system.io.fileinfo] $_ |
select fullname, length, #{ n = 'Version'; e = { $_.versioninfo.FileversionRaw } } }
FullName Length Version
-------- ------ -------
C:\Windows\System32\powershell.exe 0
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe 446976 10.0.14393.206
Delete the powershell.exe (with 0KB) from location C:\Windows\System32
In my case Powershell working fine after deleting the powershell.exe (with 0KB) from system 32

How to run an application as shell replacement on Windows 10 Enterprise

I need to create a special account on a computer running Windows 10 Enterprise. This account would launch an application directly on login instead of the default shell and exiting the application should force the computer to restart.
I was able to do this easily on Windows 8.1 Embedded Industry Pro using the configuration console and lockdown features.
Now, on Windows 10 I try to follow the two tutorials on technet WESL_UserSetting and Set up a kiosk on Windows 10 Pro, Enterprise, or Education
However, neither of the tutorials work. I have managed to execute the scripts described in them but they have no effect (I've modified them so they do not remove the shells set).
Finally I've ended up with the following code:
$COMPUTER = "localhost"
$NAMESPACE = "root\standardcimv2\embedded"
$ACCOUNT_NAME = "cmp"
$ShellLauncherClass = [wmiclass]"\\$COMPUTER\${NAMESPACE}:WESL_UserSetting"
$NTUserObject = New-Object System.Security.Principal.NTAccount($ACCOUNT_NAME)
$NTUserSID = $NTUserObject.Translate([System.Security.Principal.SecurityIdentifier]).Value
$NTUser_Shell = Get-WmiObject -namespace $NAMESPACE -computer $COMPUTER -class WESL_UserSetting |
where {$_.Sid -eq $NTUserSID}
if ($NTUser_Shell) {
"`Custom shell already set for [$ACCOUNT_NAME] removing it"
$ShellLauncherClass.RemoveCustomShell($NTUserSID)
}
$restart_shell = 0
$restart_device = 1
$shutdown_device = 2
$ShellLauncherClass.SetCustomShell($NTUserSID, "cmd.exe", ($null), ($null), $restart_device)
"`nCurrent settings for custom shells:"
Get-WmiObject -namespace $NAMESPACE -computer $COMPUTER -class WESL_UserSetting | Select Sid, Shell, DefaultAction
Executing this script in an admin powershell produces the desired output:
Custom shell already set for [cmp] removing it
Current settings for custom shells:
Sid Shell DefaultAction
--- ----- -------------
S-1-5-21-3842421150-1098587697-2315725148-1002 cmd.exe 1
However logging as the 'cmp' user simply shows the standard Windows 10 shell.
What should I change in order to be able to run a program instead of a standard shell?
I had the same problem right now. And yes, Microsoft has changed the way to do a shell replacement. You can install and use the Embedded Shell Launcher to customize windows as you like it for kiosk mode. But this is only available for Enterprise and Education.
If you don't want to buy the Enterprise version you can use the already known registry locations in HKCU and HKLM. https://msdn.microsoft.com/en-us/library/ms838576(v=WinEmbedded.5).aspx
But wait, oh no since Windows 10 it is only possible to use Microsoft signed applications, so your normal .net application isn't started and the screen keeps being black after login. But we've figured out a workaround.
Just use a Batch-File as bootstrapping. If you set the registry keys you like to a Batch-File and the Batch-File starts the real application, then it works like a charm.
#echo off
echo Bootstrapping, please wait ...
start /b "Bootstrap" "C:\vmwatcher\VMViewClientWatcher.exe"
Have you tried changing the users shell?
https://msdn.microsoft.com/en-us/library/ms838576(v=WinEmbedded.5).aspx
There are a few registry keys you need to set. First one enables the ability to give the user a unique shell, the second one defines the executable that starts instead of explorer.
I wanted to do something similar, and I borrowed heavily from other answers, but none of them were a complete working answer for me. Here's what I ended up doing.
Create a new user account
Setup the following vbs script (largely inspired by this thread) to launch the shell application and name it something like "launch.vbs"
set oShell=createobject("wscript.shell")
sCmd="d:\launchbox\launchbox.exe"
oShell.run sCmd,,true 'true forces it to wait for process to finish
sCmd="shutdown /r /t 0"
oShell.run sCmd
Login as the new user
Run regedit
Add a new string value named Shell to HKEY_Current_User\Software\Microsoft\Windows NT\CurrentVersion\Winlogon with a value of the command that you need to run to execute your script:
wscript d:\launchbox\launch.vbs
Logoff and log back on as the user to see it in action
I battled with this one myself. If you look at the notes for Windows 10 Shell Launcher, it only works in the Enterprise or Education version. If you try using this in Home or Pro versions it simply boots to a blank screen. Using the same script in Enterprise, I confirmed works perfectly...
I think you set up correctly the custom shell for the user, but maybe you need to activate the ShellLanuncher behaviour.
Try this (at the end of your script):
$ShellLauncherClass.SetEnabled($TRUE)
This way the standard windows 10 shell is not launched when you log on with the other account, but (at least in my case) the command line does not start and the result is a black screen.
You can still run the task manager and run a new task from there, but I don't understand why the command line does not automatically start.
I ran into the same issue, and that's because the Script from TechNet on how to configure ShellLauncher actually enables, then disables the same Shell!
# Enable Shell Launcher
$ShellLauncherClass.SetEnabled($TRUE)
$IsShellLauncherEnabled = $ShellLauncherClass.IsEnabled()
"`nEnabled is set to " + $IsShellLauncherEnabled.Enabled
# Remove the new custom shells.
$ShellLauncherClass.RemoveCustomShell($Admins_SID)
$ShellLauncherClass.RemoveCustomShell($Cashier_SID)
# Disable Shell Launcher
$ShellLauncherClass.SetEnabled($FALSE)
$IsShellLauncherEnabled = $ShellLauncherClass.IsEnabled()
"`nEnabled is set to " + $IsShellLauncherEnabled.Enabled
I was lazily just copying and pasting the code and expected it to work.
If you comment out the final ten lines, this process will work.
Remember Kids: don't just copy and paste code from Strangers!
I want to begin by apologizing for commenting on a very old thread.
I have struggled for the past 6 months trying to get a custom app to run as a default shell, and retain administrator rights. Like many people, these scripts and/or commands just weren't working, and I needed something quick, effective and EASY!
Simply replacing the "explorer.exe" (HKLM\SOFTWARE\Microsoft\Window NT\Winlogon\Shell) with a custom app location provided a black screen.
A much simpler way, and it works great, was to create a BATCH script to call the custom app through elevated powershell...
powershell -nologo -noprofile -executionpolicy bypass -command "start-process -verb 'runas' -filepath <full path of custom app executable>"
By replacing "explorer.exe" with this batch script I was able to successfully create a kiosk style lockdown under Windows 10 PRO with a non-UWP app.
My fist attempt to help where I have received much. Not a complete answer, but maybe enough to get you to your destination. This worked on my "Kiosk" app which is on "my" Windows 10 Enterprise system which was built specifically for my app. It will set your "shell" to start on system startup and then start your click once program. Hope this helps.
Imports System.Threading
Public Class Form1
# Path to your ClickOnce app
Dim startPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Programs) _
& '"\"' & '"remaining path to your app"' & '".appref-ms"'
# Path to your shell which is also a clickonce app(this one)
Dim spath As String = Application.StartupPath & '"\"' & My.Application.Info.AssemblyName _
& '".exe"'
# This sets the registry to start your shell which in turn starts your app.
# I did this so that if the app is closed, they see the shell background.
# You can add controls to your shell to restart the app, shutdown....
#Just be cautious, make sure your app is 100% done and updates on it's own before you
# disable the ability to get back to windows explorer.
# Other wise you could have a very bad day.
My.Computer.Registry.SetValue('"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows NT\ _
CurrentVersion\Winlogon"', '"Shell"', spath)
Thread.Sleep(500)
Process.Start(startPath)
End Class
You can create a Provisioning Package using Windows Configuration Designer.
The gui will help in creating a simple shell replacement when you choose 'provision kiosk devices'

Resources