Handle services with powershell

Asked

Viewed 578 times

4

I created a script to start and stop a service. My intention is to be able to start or stop a service by simply clicking on a desktop shortcut. I created a shortcut for the script and in the destination field in the shortcut properties I added the arguments PowerShell.exe -ExecutionPolicy ByPass -File. The shortcut is working but in order 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 to run as administrator. My intention is to make administrator mode the default shortcut so I can run it with two clicks. In the light of the question, I would like to know what the arguments mean -ExecutionPolicy ByPass because this tip was given to me in another forum and I already researched and did not find the meaning of this argument in the shortcut. Below follows 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'
}

1 answer

2


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

  • Right-click the shortcut and select "Properties"

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

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

If you prefer to change the execution privilege directly in the script code, you can do so 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

According to the parameter documentation -Executionpolicy:

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 aim 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 a particular code differently from the rules defined in the Executionpolicy.

Simply put, there are six main policies:

  • Restricted - does not allow script execution

  • Allsigned - allows only the execution of digitally signed scripts

  • Remotesigned - allows the execution of locally developed unsigned scripts. If the script has been downloaded (remote), it must have a digital signature

  • Unrestricted - allows the execution of unsigned scripts, but warns the user if the script has been downloaded

  • Bypass - runs any script without any warning

  • Undefined - undefined policy. Powershell searches for a standard user or machine policy. If all are undefined, the default is "Restricted"

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.