Manipulate services with powershell

4

I've 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 to the script and in the target field in the shortcut properties I added the PowerShell.exe -ExecutionPolicy ByPass -File arguments. The shortcut is working but for it to be able to handle the services I have to run it as an administrator which has me compelled to right click on the shortcut and choose run as administrator. My intention is to make administrator mode the shortcut pattern so I can run it with two clicks. Taking the question, I would like to know what -ExecutionPolicy ByPass means because this tip was given to me in another forum and I already researched and I did not find the meaning of these arguments in the shortcut. Here 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'
}
    
asked by anonymous 24.01.2016 / 13:02

1 answer

2

The simplest way to run the script as Administrator by default is to directly set 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 execute 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 documentation for the parameter -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 are intended to help the user not to execute scripts for "cheating" 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 ExecutionPolicy.

Simply put, there are six main policies:

  • Restricted - does not allow scripting
  • AllSigned - Allows only execution of digitally signed scripts

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

  • Unrestricted - allows unsigned scripts to run, 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 checking the documentation for this parameter for more details, as there are several possible configuration strategies.

    
25.01.2016 / 00:56