Handle services with powershell

Question:

I created a script to start and stop a service. My intention is to be able to start or stop a service through a simple mouse click on a desktop shortcut. I created a shortcut for the script and in the target field in the shortcut properties I added the arguments PowerShell.exe -ExecutionPolicy ByPass -File . The shortcut is working but for it to be able to manipulate the services I have to run it as administrator, which has forced me to right-click on the shortcut and choose run as administrator. My intention is to make admin mode the default for the shortcut so that I can run it with two clicks. Taking advantage of the question, I would like to know what the -ExecutionPolicy ByPass arguments mean because this tip was given to me in another forum and I already searched and I didn't find the meaning of these arguments in the shortcut. Below is the script:

if((Get-Service -Name 'MSSQL$SQLEXDEV').Status -eq "Running")
{
    Stop-Service -Name 'MSSQL$SQLEXDEV'
    Set-Service -Name 'MSSQL$SQLEXDEV' -StartupType Disabled
}
else
{
    Set-Service -Name 'MSSQL$SQLEXDEV' -StartupType Manual
    Restart-Service -Name 'MSSQL$SQLEXDEV'
}

Answer:

The simplest way to run the script as Administrator by default is to directly set the shortcut to "Run as administrator":

  • Right click on the shortcut and select "Properties"

  • In the "Shortcut" tab, click the "Advanced" button

  • Select the "Run as administrator" option and then click "Ok" and "Ok" again

In case you prefer to change the execution privilege directly in the script code, you can do it as described below:

# Obtém o ID do usuário
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()

# Obtém informações do grupo ao qual o usuário pertence
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
 
# Obtém informações sobre o grupo "Administrador"
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
 
# Verifica se a execução atual já está em modo elevado
# Essa verificação é necessária para que o script não entre em looping
if (-Not ($myWindowsPrincipal.IsInRole($adminRole)))
{ 
   # Cria um novo processo do PowerShell
   $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
   
   # Informa como parâmetro para o novo processo, o caminho do script atual
   $newProcess.Arguments = $myInvocation.MyCommand.Definition;
   
   # Parâmetro para o novo processo que solicita a
   # execução em modo elevado (Administrador)
   $newProcess.Verb = "runas";
   
   # Inicia o novo processo
   [System.Diagnostics.Process]::Start($newProcess);
   
   # Encerra o processo atual (que está em modo Usuário)
   exit
}

# Aqui, você coloca o código que será executado pelo seu script em modo Administrador
if((Get-Service -Name 'MSSQL$SQLEXDEV').Status -eq "Running")
{
    Stop-Service -Name 'MSSQL$SQLEXDEV'
    Set-Service -Name 'MSSQL$SQLEXDEV' -StartupType Disabled
}
else
{
    Set-Service -Name 'MSSQL$SQLEXDEV' -StartupType Manual
    Restart-Service -Name 'MSSQL$SQLEXDEV'
}

Source: A self elevating PowerShell script – by Benjamin Armstrong

As per the documentation for the -ExecutionPolicy parameter:

This parameter determines the PowerShell execution policy for the machine, for a user, or for a session.

The rules defined for the PowerShell execution policy are intended to help the user not to execute scripts by "mistake" or "carelessness".

These rules are not security policies and do not prevent the user from executing certain code differently from the rules defined in the ExecutionPolicy.

Simply put, there are six main policies:

  • Restricted – does not allow script execution

  • AllSigned – only allows execution of digitally signed scripts

  • RemoteSigned – allows the execution of locally developed scripts without signing. If the script was downloaded (remote), it must have a digital signature

  • Unrestricted – allows the execution of scripts without signature, but warns the user if the script has been downloaded

  • Bypass – run any script without any warning

  • Undefined – undefined policy. PowerShell looks for a default user or machine policy. If all are undefined, the default is "Restricted"

I recommend consulting the documentation for this parameter for more details, as there are several possible configuration strategies.

Scroll to Top