Windows запуск команды от имени другого пользователя

Любой пользователь Windows может запустить в своей сессии программу от имени другого пользователя с помощью Run As. Благодаря этому вы можете выполнить скрипт (.bat, .cmd, .vbs, .ps1), запустить исполняемый .exe файл или установку приложения (.msi, .cab) с полномочиями другого пользователя.

Например, вы можете использовать RunAs для установки программ или запуска программ/скриптов/MMC оснасток с правами администратора непосредственно в сессии обычного непривилегированного пользователя. Также через RunAs вы можете запустить приложение, настроенное в профиле другого пользователя (приложение загрузится с настройки из профиля другого пользователя).

За возможность запуска программ от имени другого пользователя в Windows отвечает служба Вторичный вход в систему (Secondary Log-on). Если эта служба остановлена, тогда все описанные методы runas работать не будут. Вы можете проверить, что служба запущена с помощью следующей команды PowerShell:

Get-Service seclogon

В Windows есть несколько способов запустить программу или процесс от имени другого пользователя.

Содержание:

  • Запуск программы от имени другого пользователя из Проводника Windows (File Explorer)
  • Команда Runas: запуск программ от имени из командной строки
  • Использование RunAs в PowerShell
  • Запуск программ от имени другого пользователя без ввода пароля
  • Ярлык с запуском программы от имени другого пользователя
  • В проводнике Windows отсутствует пункт “Запуск от имени другого пользователя”
  • Как добавить пункт “Запуск от имени” для программ в меню Пуск?

Запуск программы от имени другого пользователя из Проводника Windows (File Explorer)

Самый простой способ запустить программу из-под другого пользователя – воспользоваться графическим интерфейсом Проводника Windows (File Explorer). Просто найдите нужно приложение (или ярлык), зажмите клавишу Shift и щелкните по нему правой кнопкой мыши. Выберите пункт контекстного меню «Запуск от имени другого пользователя» (Run as different user).

Примечание. Если пункт меню «Запуск от имени другого пользователя» отсутствует, см. следующий раздел.

Запуск от имени другого пользователя - конекстное меню

В появившемся окне Windows Security нужно указать имя и пароль пользователя, под чьей учетной записью нужно запустить программу и нажать кнопку ОК.

Примечание.

  • Если нужно запустить программу от имени пользователя Active Directory, нужно указать его имя в формате userPrincipalName (
    [email protected]
    ) или samAccountName (
    DomainName\UserName
    );
  • Если ваш компьютер добавлен в домен AD, то для запуска программы от имени локальной учетной записи пользователя ее имя нужно указать в формате:
    .\localusername
    .

runas different user

Важно. Вы можете запустить программу от имени другого пользователя только, если для него задан пароль. Использовать Runas для пользователя с пустым паролем не получится.

Откройте Диспетчер задач и убедитесь, что приложение запущенно под указанным пользователем.

диспетчер задач windows видит, что процесс запущен от имени другого пользователя

Команда Runas: запуск программ от имени из командной строки

В Windows есть консольная утилита runas.exe, которую можно использовать для запуска приложений от имени другого пользователя из командной строки. Также команда runas позволяет сохранить пароль пользователя в Windows Credential Manager, чтобы его не приходилось набирать каждый раз.

Откройте командную строку (или окно Выполнить, нажав сочетание клавиш Win+R). Для запуска Блокнота с правами учетной записи administrator выполните команду:

runas /user:administrator “C:\Windows\cmd.exe”

Совет. Если имя пользователя содержит пробелы, его нужно взять в кавычки:

runas /user:”user test” notepad.exe

runas /user:admin

В отрывшемся окне появится приглашение «Введите пароль для admin», где нужно набрать пароль и нажать Enter.

Должно открыться ваше приложение. В моем случае это cmd. В заголовке окна указано Запущено от имени
CompName\username
:

cmd.exe заголовок запущено от другого имени

Можно, например, открыть панель управления под другим пользователем:

runas /user:admin control

Если нужно запустить программу от имени доменного пользователя, нужно использовать формат имени
UserName@DomainName
или
DomainName\UserName
.

Например, чтобы с помощью блокнота открыть текстовый файл от имени пользователя server_admin домена CORP, используйте команду:

runas /user:corp\server_admin “C:\Windows\notepad.exe C:\tmp\2871997x64.txt”

команда runas в windows под доменным пользователем

Введите пароль для corp\server_admin:
Попытка запуска C:\Windows\notepad.exe C:\tmp\2871997x64.txt от имени пользователя "corp\server_admin" ...

Если указали несуществующее имя пользователя или неверный пароль, появится ошибка:

RUNAS ERROR: Unable to run - yourcommand
1326: The user name or password is incorrect.

Или

RUNAS ERROR: Unable to acquire user password

Иногда нужно запустить программу от имени доменного пользователя с компьютера, который не добавлен в домен AD. В этом случае нужно использовать такую команду (при условии, что в сетевых настройках вашего компьютера указан DNS сервер, который может отрезолвить этот домен):

runas /netonly /user:contoso\aaivanov cmd.exe

Если для запуска программы от другого пользователя не нужно загружать его профиль, используйте параметр /noprofile. При этом приложение запускается намного быстрее, но может вызвать некорректную работу программ, которые хранят данные в профиле пользователя.

Использование RunAs в PowerShell

Если вам нужно запускать программы/процессы от имени другого пользователя из PowerShell, вы можете использовать командлет Start-Process (управление процессами с помощью PowerShell). Сначала нужно запросить учетную запись и пароль пользователя:

$Cred = (Get-Credential)

Для запуска процесса от имени другого пользователя можно использовать:

Start-Process -FilePath "powershell.exe" -Credential $Cred

Либо можно запросить учетную запись и пароль интерактивно через Windows Security:

# "Run as Administrator"
Start-Process -FilePath "powershell.exe" -Verb RunAs
# Run as от другого пользователя
Start-Process -FilePath "powershell.exe" -Verb RunAsUser

powershell запуск процесса от другого пользователя start-process

Если вам нужно запустить программу через runas от имени другого администратора в привилегированном режиме (по умолчанию UAC запускает программу в not-elevated пользовательском контексте), можно использовать такую команду PowerShell:

Start-Process powershell -Credential winitpro\admin2 -ArgumentList '-noprofile -command &{Start-Process "cmd.exe" -verb runas}'

Или стороннюю утилиту ShelExec:

ShelExec /Verb:runas cmd.exe

Запуск программ от имени другого пользователя без ввода пароля

Вы можете сохранить пароль пользователя, который вы вводите. Для этого используется параметр /savecred.

runas /user:admin /savecred “C:\Windows\notepad.exe”

После указания пароля он сохранится в диспетчере паролей Windows.

сохраненные паролья runas в windows в диспетчере учетных данных

При следующем запуске команды runas под этим же пользователем с ключом
/savecred
Windows автоматически получит сохраненный пароль из Credential Manager, и не будет запрашивать его повторно.

Чтобы вывести список всех пользователей, для которых сохранены пароли, используется команда:

RunDll32.exe keymgr.dll,KRShowKeyMgr

runas /user:admin /savecred - сохранние пароля в менеджере паролей

Однако использование параметра /savecred не безопасно, т.к. пользователь, в чьем профиле сохранен чужой пароль может использовать его для запуска любой команды под данными привилегиями, или даже сменить чужой пароль. Кроме того, сохраненные пароли из Credential Manager можно легко украсть, поэтом лучше запретить использование сохраненных паролей (а тем более нельзя сохранять пароль привилегированной административной учетной записи).

Примечание. Кроме того, ключ /savecred не работает в Home редакциях Windows.

Вы можете использовать команду RunAs для запуска mmc оснасток от имени другого пользователя. К примеру, если под другим пользователем нужно запустить оснастку Active Directory Users and Computers из набора инструментов администрирования RSAT, можно воспользоваться такой командой.

runas.exe /user:winitpro\kbuldogov "cmd /c start mmc %SystemRoot%\system32\dsa.msc"

Аналогичным образом можно запустить любую другую оснастку (главное знать ее имя).

Ярлык с запуском программы от имени другого пользователя

Вы можете создать на рабочем столе ярлык для запуска программы от имени другого пользователя. Просто создайте новый ярлык, в окне с адресом объекта которого укажите команду
runas
с нужными параметрами:

runas /user:winitpro\kbuldogov  “C:\Windows\notepad.exe”

ялык рабочего стола для запуска программы от имени в windows

При запуске такого ярлыка будет запрашиваться пароль пользователя.

Если в ярлыке runas добавить параметр
/savecred
, то пароль будет запрошен только один раз. После этого пароль будет сохранен в Credential Manager и автоматически подставляться при запуске ярлыка от имени другого пользователя без запроса пароля.

Такие ярлыки довольно часто используются для запуска программ, которые требуют прав администратора для запуска. Однако есть более безопасные способы запуска программы без прав администратора, или отключения запроса UAC для определенного приложения.

В проводнике Windows отсутствует пункт “Запуск от имени другого пользователя”

Если в контекстном меню проводника Windows отсутствует пункт Запуск от имени другого пользователя (Run as different user), нужно проверить настройки двух параметров реестра Windows.

В Windows вы можете скрыть или показать в проводнике пункт меню RunAs с помощью двух параметров реестра:

  • Параметр HideRunAsVerb (тип REG_DWORD) в ветке реестра HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer (1 – скрыть пункт runas, 0 – показать)
  • Параметр EnableSecureCredentialPrompting (REG_DWORD) в HKLM\ Software\Microsoft\Windows\CurrentVersion\Policies\CredUI (1 – скрыть, 0 – показать)

Если в Windows не отображается пункт Run as different user, проверьте значения этих параметров реестра и измените их на 0. В доменной среде вы можете распространить значения этих параметров реестра на компьютеры с помощью Group Policy Preferences.

Второму параметру реестра соответствует отдельная опция GPO.

Этой опции GPO соответствует параметр EnableSecureCredentialPrompting в ветке реестра HKLM\ Software\Microsoft\Windows\CurrentVersion\Policies\CredUI. Откройте редактор локальных групповых политик (gpedit.msc) и убедитесь, что в разделе Конфигурация компьютера -> Административные шаблоны -> Компоненты Windows -> Пользовательский интерфейс учетных данных (Computer Configuration -> Administrative Templates -> Windows Components -> Credential User Interface) отключена (Не задана) политика Запрашивать достоверный путь для входа в учетную запись (Require trusted path for credential entry).

Запрашивать достоверный путь для входа в учетную запись (Require trusted path for credential entry) - политика

Как добавить пункт “Запуск от имени” для программ в меню Пуск?

По-умолчанию в Windows 10 у элементов меню Пуск (начального экрана) отсутствует возможность запуска приложений от имени другого пользователя. Чтобы добавить в контекстное меню пункт “Запуск от имени другого пользователя”, нужно включить политику Показывать команду «Запуск от имени другого пользователя» при запуске (Show “Run as different user” command onStart) в разделе редактора групповых политик (консоль
gpedit.msc
) Конфигурация пользователя ->Административные шаблоны -> Меню Пуск и панель задач (User Configuration -> Administrative Templates -> Start Menu and Taskbar).

включить политику Показывать команду «Запуск от имени другого пользователя» при запуске

Либо, если редактор gpedit.msc отсутствует, создать в ветке реестра HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Explorer ключ типа DWORD с именем ShowRunasDifferentuserinStart и значением 1.
New-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\Windows\CurrentVersion\Explorer" -Name ShowRunasDifferentuserinStart -Value 1 -PropertyType DWORD -Force

ShowRunasDifferentuserinStart - реестр

Осталось обновить групповые политики (gpupdate /force) и убедиться, что у программ в меню Пуск появится новое контекстное меню Дополнительно -> Запуск от имени другого пользователя.

windows 11 run as different uzer в стартовом меню пуск

Пункт “запуск от имени” отсутствует у Universal Windows Platform (UWP) приложения из Microsoft Store. Вы можете запустить UWP приложение от другого пользователя из командной строки с помощью runas.exe.

Выведите список приложений Microsoft Store на компьютере с помощью PowerShell:

Get-AppxPackage|select Name

Можно найти конкретное приложение

Get-AppxPackage|where {$_.Name -like '*team*'} |select Name

Найдите имя нужного приложения в списке. Например, для запуска встроенного клиента Microsoft Teams Chat от другого пользователя, выполните:

runas /user:user1 "explorer.exe MicrosoftTeams:"

По умолчанию программы в Windows запускаются от имени текущего пользователя, а при необходимости — с правами администратора. Однако, в некоторых случаях может потребоваться запуск какого-либо приложения от имени другого пользователя, с его сохраненными данными, но без входа в соответствующий аккаунт.

В этой простой инструкции подробно о том, как запустить какую-либо программу от имени другого пользователя Windows 11 или Windows 10 различными способами, если вдруг такая необходимость возникла. Также может быть полезным: запуск программ от имени администратора в Windows.

Простой запуск от имени другого пользователя

Самый простой и быстрый способ запустить программу от другого пользователя — использовать контекстное меню Windows 11/10, для этого достаточно:

  1. Удерживая клавишу Shift, нажать правой кнопкой мыши по ярлыку или исполняемому файлу программы.
  2. В контекстном меню выбрать пункт «Запуск от имени другого пользователя».
    Запуск от имени другого пользователя в контекстном меню

  3. Ввести имя другого пользователя и соответствующий этой учетной записи пароль.
    Ввод учетных данных для запуска от имени другого пользователя

На этом всё — программа будет запущена от имени выбранного пользователя, а если она содержит сохраненные данные для выбранной учетной записи, загружены будут и они.

В случае, если у вас нет ярлыка программы, а её месторасположение неизвестно, вы можете применить следующий подход: найти программу по имени через поиск в панели задач, нажать по найденному результату правой кнопкой мыши и выбрать пункт «Перейти к расположению файла», а уже затем использовать описанный ранее подход для запуска от другого пользователя.

Запуск программы или команды от имени другого пользователя в командной строке

Ещё один подход — использовать команду RUNAS в командной строке Windows. Также с помощью этой команды можно создать ярлыки для запуска приложений от других пользователей. Самый простой пример использования команды RUNAS:

  1. Откройте командную строку (сделать это можно, используя поиск в панели задач).
  2. Введите команду (если имя пользователя содержит пробелы, возьмите его в кавычки):
    runas /user:ИМЯ_пользователя "Полный путь к файлу программы и параметры запуска при необходимости"
  3. Введите пароль выбранной учетной записи пользователя, если он будет запрошен.
    Запуск от имени другого пользователя с помощью командной строки и RunAs

В результате программа будет запущена от имени указанного пользователя. Команда имеет и другие параметры, справку можно получить, введя runas без параметров в командной строке. Например, можно включить или отключить использование данных профиля пользователя, сохранить учетные данные с помощью параметра /savecred для того, чтобы при следующих запусках от имени выбранного пользователя ввод пароля не требовался.

Существуют и другие, иногда более функциональные решения для запуска программ или bat файлов от имени других пользователей, одно из самых известных — утилита PsExec, входящая в Microsoft Sysinternals Suite и позволяющая выполнить не только описанную задачу, но и множество других.

Runas is a very useful command on Windows OS. This command enables one to run a command in the context of another user account. One example scenario where this could be useful is: Suppose you have both a normal user account and an administrator account on a computer and currently you are logged in as normal user account. Now you want to install some software on the computer, but as you do not have admin privileges you can’t install the same from the current account. One option is to switch user and login as administrator. Instead, you can do the same by simply using runas command. You just need to launch the installer from command prompt using runas command and by providing administrator login id and password.

Let’s see the syntax of runas command with some examples.

Run a program from another user account

The command to launch a program using another user credentials is given below.

runas /user:domainname\username program

For example, if you want to open registry editor as administrator of the computer, the command would be as below.

runas /user:administrator regedit

After running the above command, you will be asked to enter the password of administrator account. After password validation, registry editor will be opened with the administrator account credentials.

To specify arguments to the program:

If you need to provide arguments to the program that need to be invoked as another user, you can put the program name and the parameters in double quotes.

runas /user:username "program argument1 argument2 ..."

For example to open the file C:\boot.ini as administrator, the command would be:

runas /user:administrator "notepad C:\boot.ini"

Running command prompt as another user :

If you have multiple commands need to be executed with administrator(or any other user )credentials, instead of running each command using runas, you can open command prompt window once as the administrator and then run all the commands in that window. Below is the command for opening a command window using runas.

runas /user:administrator cmd

Example:

C:\>runas /user:administrator cmd
Enter the password for administrator:
Attempting to start cmd as user "techblogger-pc\administrator" ...

It will launch new command window after printing the above message.

Run a batch file as administrator

To run a batch file as administrator of the computer, you need to mention the path of the batch file in the place of command in the runas syntax.

For example, to run the batch file located at c:\data\mybatchfile.bat, you need to run the below command.

runas /user:administrator C:\data\mybatchfile.bat

Some questions regarding runas command:

When I use runas command, I am getting the error ‘This program is blocked by group policy. For more information, contact your system administrator’. How can I fix this?

Administrator of your system might have disabled users to login from command prompt. In group policy editor, this setting can be found in the below node.

Computer Configuration -> Windows settings -> Security settings ->Local Policies -> User rights assignment

In the above path, look for the setting ‘Deny logon as a batch job‘. If you have administrator privileges,  you can disable this settings. Otherwise, you need to contact the system/domain administrator.

If you have a program, script, executable (.exe) file, or a UWP application, you can run it as a different user directly from the current user account you are logged in from. This way, you do not have to sign out and then log back into another account to be able to run the desired file with elevated privileges, or use the settings specific to the other user account.

This article lists both native and non-native methods you can adapt to run an app or a file as another user on a Windows computer. These methods can also be used to run an app or program as an administrator, or for when you want to use the settings/configurations for an app set for another account.

You can run scripts and programs as a user account that has elevated privileges from an underprivileged user account. Of course, it would require the necessary user account credentials.

Before we discuss the many methods to run an app, program, or file as another user, there are a few things you must consider.

Table of Contents

Prerequisites to Run App as Different User in Windows

Whether you want to run a file as a local user or a domain user; all can be done using this guide.

However, before you do, you must enable the Secondary Logon service, also referred to as “RunAs.” This Windows service is responsible for allowing different apps and files to be run as different user.

If this service is not running or is problematic, then you won’t be able to run anything as a different user.

To check the status of the Secondary Logon service, run the following cmdlet in PowerShell:

Get-Service seclogon
Check Secondary Logon service status

Check the Secondary Logon service status

If you find that the service is not running, then run the following command to enable it:

net start seclogon

The Secondary Logon service is set to start manually when called upon. To allow it to run automatically, use these steps:

  1. Open the Services Console by typing in “services.msc” in the Run Command box.

    Open the Services Console
  2. Right-click the service “Secondary Logon” and click Properties.

    Open Secondary Logon properties

    Open Secondary Logon properties
  3. Change the Startup Type to “Automatic (Delayed Start)” then click Apply and Ok.

    Automatically start Secondary Logon

    Automatically start Secondary Logon

Now, the Secondary Logon service will start automatically in the background every time you are logged into your account.

Apart from the Secondary Logon service, you must also ensure that the account you want to use to run a file as a different user must have a password. You cannot run an app/program as a different user that has no password configured.

After having ensured that both of these conditions are met, it is now time to move on to running a file/app as a different user.

How to Run App/Program as Different User In Windows

Run as Different User from Context Menu

This method can be applied to any file, may it be a .exe, .bat, .ps1, or any other, to run it as a different user. However, it can not be implemented on Universal Windows Platform (UWP) applications. For that, you must use the PowerShell method shared below.

The easiest method to run a file as a different user is through the context menu by holding the Shift key while right-clicking the file.

  1. Hold down the Shift key from the keyboard and then right-click the file.

  2. Click “Run as different user” from the context menu.

    Note: If the “Run as different user” option is missing from the context menu, it might be disabled. To enable it, refer to the last section of this post.

    Run as different user from context menu

    Run as different user from the context menu
  3. Enter the credentials for the user account to RunAs.

    Enter user credentials

    Enter user credentials

    To run the file from an Active Directory user account, use the syntax “DomainName\Username” in the username field.

    To run the file as a local user from a machine connected to a domain, use the syntax “.\Username”.

The file will now run from the other user account. You can confirm this through the Details tab in the Task Manager.

Confirm file is running from other user

Confirm file is running from another user account

Run as Different User from Command Prompt/Run Command

You can also use the command line to run a file as a different user. This method can be used in both the Command Prompt and the Run Command box.

To learn how to run a file as a different user using PowerShell, refer to the next section below.

You can run a file as a different user using the “RunAs” command line tool. Here is how:

  1. Use the following command in an elevated Command Prompt or the Run Command box.

    Replace [PathToFile] with the complete path to the file and [Username] with the account name you want to run it as.

    To run the file from an Active Directory user account, use the syntax “DomainName\Username” in place of [UserName].

    Runas /user:"[Username]" "[PathToFile]"
    Run as different user from Command Prompt

    Run as different user from Command Prompt
  2. Now enter the password for the user account and hit Enter.

    Note: You will see no text in the command line while entering the password.

    Enter the password for the user account to run as

    Enter the password for the user account to run as

You will now see that the file will run from the other user account.

Run as Different User from PowerShell

To run a file as a different user using PowerShell, the syntax of the command is a little different. However, it can be done using a single cmdlet.

You can also use this method to run the UWP application as another user. But first, let us see how to run any file using PowerShell:

  1. Use the following command in an elevated PowerShell instance:

    Replace [PathToFile] with the complete path to the file to run.

    Start-Process "[PathToFile]" -Credential $(Get-Credential)
    Run as different user from PowerShell

    Run as different user from PowerShell
  2. Now enter the credentials for the user account.

    Enter user credentials2

    Enter user credentials

The file will now be executed from the other user account.

To run a UWP application as a different user, you must first have the name of the app. Use these steps to run a Windows UWP app as a different user:

  1. Use this cmdlet in PowerShell to get the names of all the installed apps:

    Get-AppxPackage|select Name
    Get all application names using PowerShell

    Get all application names using PowerShell
  2. Once you have the name of the app you want to run as a different user, use it in the following command:

    Runas /user:"[Username]" "explorer.exe [AppName]"
    Run UWP app as different user from PowerShell 1

    Run UWP app as different user from PowerShell
  3. Now enter the password for the other user account.

    Enter password for user account

    Enter password for user account

The UWP app will now run as a different specified user.

Run as Different User using Shortcut

If you occasionally have to run a specific file from a specific user account, it would be convenient to create a custom shortcut. Simply running the shortcut will run the file from a specified user account every time.

Use these steps to create a shortcut and run a file from a different user:

  1. Right-click on an empty space on the desktop, expand New and click Shortcut.

    Create a new shortcut

    Create a new shortcut

    The Create Shortcut wizard will now open.

  2. Enter the complete location of the file prefixed with “runas /user:[Username]”.

    The syntax of the location will be something like this:

    Runas /User:[Username] "[PathToFile]"
    Enter file path with RunAs

    Enter file path with RunAs
  3. Click Next.

  4. Set a name for the shortcut and click Finish.

    Name the shortcut

    Name the shortcut

The shortcut will now be created. All you must do now is double-click the shortcut to run the specified file with the specified user. However, you will still need to provide the password for the configured user account every time you run the shortcut.

Enter the password

Enter the password

Run as Different User using RunAsTool

The RunAsTool is a portable app in which you can save user credentials and then the app can automatically run programs and files listed in the app as the specific user all the time, just like the shortcut method we discussed above.

This tool is especially useful for system administrators who want to give administrative rights to standard users only for specific programs and applications.

Use these steps to use the RunAsTool to run apps, programs, and files as different users:

  1. Download RunAsTool.

  2. Extract its contents.

    Extract RunAsTool

    Extract RunAsTool
  3. Run “RunAsTool.exe” or “RunAsToolx64.exe” (depending on your system architecture).

  4. Enter the administrator account’s credentials and click Apply.

    Enter administrative credentials for RunAsTool

    Enter administrative credentials for RunAsTool
  5. Now drag and drop the applications you want to run as administrator into the tool.

    Drag and drop items into RunAsTool

    Drag and drop items into RunAsTool

Now you can double-click any application within RunAsTool to run directly from the specified user account. Note that the “administrative” account for the RunAsTool is now the account for which you initially entered the credentials in Step 4 above.

Run as Different User from Start Menu

The methods to run an app/program as a different user we have discussed so far have no effect on the items visible inside the Start menu. If you want to have the “Run as different user” option in the context menu of the Start menu, then you must follow these steps:

  1. Open the Group Policy editor by typing in “gpedit.msc” in the Run Command box.

    Open the Group Policy Editor

    Open the Group Policy Editor
  2. Navigate to the following from the left pane:

    Local Computer Policy >> User Configuration >> Administrative Templates >> Start Menu and Taskbar
  3. Here, double-click the policy “Show “Run as different user” command on Start.”

    Open policy settings for Run as different user in Start menu

    Open policy settings for “Run as different user” in Start menu
  4. From the policy settings window, select “Enabled,” and then click Apply and Ok.

    Enable the Run as different user option in Start menu

    Enable the “Run as different user” option in Start menu
  5. Now run the following cmdlet in an elevated Command Prompt to implement the policy changes.

    GPUpdate /Force
    Force update group policies

    Force update group policies

You can now check that the “Run as different user” option is now available in the Start menu.

Run as different user enabled in Start menu

“Run as different user” enabled in Start menu

You may now select this option and provide the credentials for the user account you want to run the selected app as.

That said, note that the UWP apps still won’t have the option to “Run as different user” in their context menu, even inside the Start menu. For that, you must use the PowerShell method shared above.

Fix “Run as Different User” Option Missing in Context Menu

Till now we have discussed different methods to run an app, program, or file as a different user. Some of these methods involved selecting the “Run as different user” from the context menu. However, it may be possible that the option has been disabled deliberately.

You can thus enable the “Run as different user” using the following steps.

Note: The process involves manual manipulation of the Windows Registry. Misconfiguration of critical values in the system’s registry could be fatal for your operating system. Therefore, we insist that you create a system restore point before proceeding forward with the process.

You can also use our top selection of disk imaging and backup software so you never lose your data or operating system again.

  1. Open the Windows Registry editor by typing in “regedit” in the Run Command box.

    Open the Registry Editor
  2. Paste the following path in the navigation bar for quick navigation:

    Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer
    Quick navigation to Explorer registry key 1

    Quick navigation to Explorer registry key
  3. Double-click the DWORD “HideRunAsVerb.”

    Open HideRunAsVerb

    Open HideRunAsVerb
  4. Change the Value Data for “HideRunAsVerb” to “0.”

    Change Value Data for HideRunAsVerb

    Change Value Data for HideRunAsVerb
  5. Now enter the following path for quick navigation:

    Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\CredUI
  6. Now change the Value Data for “EnableSecureCredentialPrompting” to “0.”

    Change Value Data for EnableSecureCredentialPrompting

    Change Value Data for EnableSecureCredentialPrompting
  7. Now restart the computer for the changes to take effect.

Once it reboots, you should have the “Run as different user” option in the context menu for both File Explorer as well as the Start menu (if the option has been enabled as given above).

Closing Thoughts

Having the ability to run a program, script, file, or UWP app as a different user can be time-saving and allows you to run something with either elevated or restricted privileges.

In this article, you will find all the possible methods to run an app as a different user while remaining inside your current user account. This approach can be taken when you want to run something with elevated privileges, or when you want to run something with even lower rights, such as an app that might be malicious.

Additionally, you can also run something as a different user when you want to use the settings specific to the other user account. For example, you can run Microsoft Teams as another user so that you are automatically logged into another account (which was previously logged into the other user account).

The command RunAs can be used to execute programs and commands as a different user than the one signed in. Runas can be used on all Windows versions and dates back to Windows 2000. You can often right-click on a program in the user interface and select “Run as administrator”. Which is basically the same behavior.

Administrators often use runas to execute commands or other tasks with admin privileges while they are logged in to an account without administrator privileges. But the command is not limited to admins, you can also use the command to execute programs as another user.

In this article, we are going to take a look at how to use the Runas command.

The RunAs command comes with different parameters that we can use to execute programs as a different user. But before we dive into the different options, let’s first take a look at a quick example of how to execute a command as administrator.

To open the command prompt as administrator we only need to specify the user, in this case, the local admin account, and the program that we want to run, cmd in this case.

# Start cmd as admin
runas /user:admin cmd
runas

runas administrator

After you have typed the command, you will be prompted for the password after which the command will be executed.

Parameters

With the basics explained, lets take a closer look at the different options we have. There are a couple of parameters that we can use with the runas command:

Parameter Description
/user: Specifies the user account that you want to use
/noprofile Don’t load the user’s profile, this will make the application load faster. By default /profile is used
/env Use the current network environment instead of user’s local environment
/netonly Credentials are only for remote access
/savecred Save the password in the user’s profile so it can be used later (security risk!)
/smartcard Use this option if you are using smart cards for authentication
/showtrustlevel Show available trust levels
/trustlevel Trustlevel to run the program on
RunAs Parameters

The command always starts with the parameters that you want to use, follow by the command that you want to execute. The /user: parameter is of course required and specifies the user that you want to run the command as.

# Runas usage
runas <parameters> /user:<username> <command>

The parameter /savecred stores the credentials (username and password) in the user’s profile under %appdata%\Microsoft\Credentials. Now, this might seem useful for scripts etc, but it’s basically a big security risk. There is nothing to stop the user or other programs from using these credentials for another task. So be really careful when using this option.

RunAs Examples

Below I will give you a couple of examples of how to use the runas command.

Run as (domain) administrator

A common use case for the command is to execute programs or open administrative tools with administrator privilege. You can either use the local admin account or the domain admin account for this.

# Run commandprompt as local admin
Runas /user:administrator cmd

# Run commandprompt as domain admin
Runas /user:lazyadmin\administrator cmd

Open an MMC console as admin

If you want to open the services.msc as administrator you can’t simply specify services.msc as the program parameter. You will need to add MMC in front of the command:

# Open services.msc
Runas /user:administrator "MMC services.msc"

Open a program as another user

When you type chrome.exe in the run dialog (Windows key + R), the application will open. But when you want to run these applications as a different user, you will need to specify the full path of the applications:

Runas /user:administrator "C:\Program Files\Google\Chrome\Application\chrome.exe"

Some programs can’t be opened as a different user. For example, it’s not possible to open explorer or printers as administator (there is a workaround though).

PowerShell RunAs

The runas command is old and can be used in PowerShell. But there is also a PowerShell equivalent that we can use to run PowerShell scripts and commands as a different user. To run commands as a different user we simply open a new PowerShell window within the other user context.

When you want to run a PowerShell script or command as an administrator you can use the parameter -Verb runAs. You don’t need to specify the user administrator. It’s also possible to run a script or command as a different user. For this, we will need to use the verb RunAsUser

# Run as admin
Start-Process powershell -Verb RunAs

# Run as other user
Start-Process powershell -Verb RunAsUser

To supply the credentials for the administrator account you can either store the credentials in a variable, useful if you need to use it later again. Or just use a single-line command

# Store the credentials
$Cred = (Get-Credential)
Start-Process Powershell "-File c:\path\to\script.ps1" -Credential $Cred

Start-Process Powershell "-File c:\path\to\script.ps1" -Credential (Get-Credential)

Wrapping Up

Runas is a simple command that is often used by administrators to quickly open administrative tools. Just be careful with storing the credentials.

If you have any questions, just drop a comment below.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Универсальный активатор windows 10
  • Работа с webdav windows
  • Windows server tech preview
  • Windows 8 build 7927
  • Local user manager windows