Referência rápida comandos powershell


Esse é um guia de alguns comandos que podem ser utilizados em arquivos Powershell

Executar arquivo powershell

Dentro do prompt do powershell para executar um arquivo de script script.ps utilizar:

$ ./script.ps

Comentário

Insira os comentários entre aspas, por exemplo:

"Hello"

Múltiplos comandos na mesma linha

Para executar diferentes comandos em uma mesma linha utilize “;”

comando1;comando2

Criar arquivo BAT que executa o arquivo de script powershell

Para executar um arquivo powershell utilizando um arquivo BAT, basta criar um arquivo BAT com o conteúdo abaixo e com o mesmo nome do arquivo powershell. Por exemplo, se o nome do script é “script.ps” criar o arquivo “script.bat” com o seguinte conteúdo:

@echo off

set scriptFileName=%~n0
set scriptFolderPath=%~dp0
set powershellScriptFileName=%scriptFileName%.ps1

powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

Script adicionar Features do IIS

"--> Install IIS Features"
# source: https://weblog.west-wind.com/posts/2017/may/25/automating-iis-feature-installation-with-powershell
# $ Get-WindowsOptionalFeature -Online -FeatureName "IIS*"

Set-ExecutionPolicy Bypass -Scope Process

"IIS-WebServerRole"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole -norestart

"IIS-WebServer"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServer -norestart

"IIS-CommonHttpFeatures"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-CommonHttpFeatures -norestart

"IIS-HttpErrors"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpErrors -norestart

"IIS-HttpRedirect"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpRedirect -norestart

"IIS-ApplicationDevelopment"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ApplicationDevelopment -norestart

"IIS-HealthAndDiagnostics"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HealthAndDiagnostics -norestart

"IIS-HttpLogging"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpLogging -norestart

"IIS-LoggingLibraries"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-LoggingLibraries -norestart

"IIS-RequestMonitor"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-RequestMonitor -norestart

"IIS-HttpTracing"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpTracing -norestart

"IIS-Security"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-Security -norestart

"IIS-RequestFiltering"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-RequestFiltering -norestart

"IIS-Performance"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-Performance -norestart

"IIS-WebServerManagementTools"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerManagementTools -norestart

"IIS-IIS6ManagementCompatibility"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-IIS6ManagementCompatibility -norestart

"IIS-Metabase"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-Metabase -norestart

"IIS-ManagementConsole"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ManagementConsole -norestart

"IIS-BasicAuthentication"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-BasicAuthentication -norestart

"IIS-WindowsAuthentication"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WindowsAuthentication -norestart

"IIS-StaticContent"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-StaticContent -norestart

"IIS-DefaultDocument"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-DefaultDocument -norestart

"IIS-WebSockets"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebSockets -norestart

"IIS-ApplicationInit"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ApplicationInit -norestart


"IIS-ISAPIExtensions"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ISAPIExtensions -norestart

"IIS-ISAPIFilter"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ISAPIFilter -norestart

"IIS-HttpCompressionStatic"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpCompressionStatic -norestart



"NetFx4Extended-ASPNET45"
Enable-WindowsOptionalFeature -Online -FeatureName NetFx4Extended-ASPNET45 -norestart

"IIS-NetFxExtensibility45"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-NetFxExtensibility45 -norestart

"IIS-ASPNET45"
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ASPNET45 -norestart

"--> Install UrlRewrite"
choco install urlrewrite /y

Instalar certificado SSL

O script abaixo adiciona o certificado SSL no computador. Substituir “xxxxxxx” pela senha do certificado e “certificate.pfx” pelo nome do arquivo

$pwdcertdev = ConvertTo-SecureString -String "xxxxxxx" -Force -AsPlainText; Import-PfxCertificate -FilePath "certificate.pfx" -Password $pwdcertdev -CertStoreLocation Cert:\LocalMachine\My -Exportable

Desabilitar o Internet Explorer Enhanced Security Configuration

Para via script executar: Server Manager / Local Server / IE Enhanced Security Configuration = Off

function Disable-InternetExplorerESC {
    $AdminKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}"
    $UserKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}"
    Set-ItemProperty -Path $AdminKey -Name "IsInstalled" -Value 0 -Force
    Set-ItemProperty -Path $UserKey -Name "IsInstalled" -Value 0 -Force
    Stop-Process -Name Explorer -Force
    Write-Host "IE Enhanced Security Configuration (ESC) has been disabled." -ForegroundColor Green
}
function Enable-InternetExplorerESC {
    $AdminKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}"
    $UserKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}"
    Set-ItemProperty -Path $AdminKey -Name "IsInstalled" -Value 1 -Force
    Set-ItemProperty -Path $UserKey -Name "IsInstalled" -Value 1 -Force
    Stop-Process -Name Explorer
    Write-Host "IE Enhanced Security Configuration (ESC) has been enabled." -ForegroundColor Green
}
function Disable-UserAccessControl {
    Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin" -Value 00000000 -Force
    Write-Host "User Access Control (UAC) has been disabled." -ForegroundColor Green    
}
Disable-UserAccessControl
Disable-InternetExplorerESC

Alterar o TimeZone

Para obter o timezone atual:

$ Get-TimeZone

Para listar todos timezones:

$ Get-TimeZone -ListAvailable

Para alterar o TimeZone para GMT-3

$ Set-TimeZone -Name "E. South America Standard Time"

Script configurar site no IIS

O script abaixo cria um site no IIS com o nome “site.com.br”, adiciona os binds http e https de “site.com.br” e “www.site.com.br”. Também cria o AppPool desse site com o mesmo nome e ao final, inicia o site. Para o bind SSL é esperado que o certificado já esteja instalado no IIS.

É possível gerar o script powershell para adicionar uma feature diretamente pelo IIS assim: https://stackoverflow.com/a/35735050/618464

Import-Module WebAdministration

"-->> Configure WebSite"

$name = "site.com.br"
$path = "$PSScriptRoot\Website"
$hosturl = "site.com.br"
$hosturl2 = "www.site.com.br"

">> Create WebAppPool"
New-WebAppPool -name $name -force

">> Create WebSite"
new-WebSite -name $name -PhysicalPath $path -HostHeader $hosturl -ApplicationPool $name  -force

">> Add https bind"
New-WebBinding -Name $name -Protocol "https" -Port 443 -HostHeader $hosturl


">> Add bind 2"
New-WebBinding -Name $name -Protocol "http" -Port 80 -HostHeader $hosturl2

">> Add https bind 2"
New-WebBinding -Name $name -Protocol "https" -Port 443 -HostHeader $hosturl2


">> Start Website"
Start-WebSite -Name $name

Alterar path padrão de Log do IIS

Import-Module WebAdministration
Set-WebConfigurationProperty "/system.applicationHost/sites/siteDefaults" -name logfile.directory -value C:\Logs

Criar Task Scheduler

$taskId = "task01"
$existingTask = Get-ScheduledTask -TaskName "$taskId" -ErrorAction Ignore
if ($null -ne $existingTask)
{
	Unregister-ScheduledTask -TaskName $existingTask.TaskName -Confirm:$false
}
$taskAction = New-ScheduledTaskAction -Execute "calc.exe" -Id "$taskId"
$triggers = @()
$h2Trigger = New-ScheduledTaskTrigger -Daily -At "3am"
$triggers += @($h2Trigger)
Register-ScheduledTask -Action $taskAction -Trigger $triggers -TaskName "$taskId" -Description "Clear IIS Logs" -User "NT AUTHORITY\NETWORKSERVICE"

Opções de configuração de frenquencia de execução:

New-ScheduledTaskTrigger -Once -At 3am
New-ScheduledTaskTrigger -Daily -At 3am
New-ScheduledTaskTrigger -Daily -DaysInterval 3 -At 3am
New-ScheduledTaskTrigger -Weekly -WeeksInterval 2 -DaysOfWeek Sunday -At 3am
New-ScheduledTaskTrigger -AtLogon

Habilitar Histório do Task Scheduler

$schedulerLog = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration "Microsoft-Windows-TaskScheduler/Operational"
$schedulerLog.IsEnabled=$true
$schedulerLog.SaveChanges()

Adicionar permissão para usuário NetworkService em uma pasta:

Adiciona permissão para usuário NETWORK SERVICE na pasta C:\Temp

$AclPath = "C:\Temp"
$Acl = Get-Acl $AclPath
$networkService = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::NetworkServiceSid, $null);
$rights = [System.Security.AccessControl.FileSystemRights]::FullControl
$inheritance = [int]([System.Security.AccessControl.InheritanceFlags]::ContainerInherit) + [int]([System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
$propagation = [System.Security.AccessControl.PropagationFlags]::None
$accessControl = [System.Security.AccessControl.AccessControlType]::Allow
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($networkService, $rights, $inheritance, $propagation , $accessControl)
$Acl.SetAccessRule($AccessRule)
Set-Acl $AclPath $Acl

Desabilita a configuração do Windows Explorer “Hide extensions for known file types”

$key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced'
Set-ItemProperty $key HideFileExt 0
Stop-Process -processname explorer

Verificar o status de um serviço Windows

$serviceName = "MyService"

$service = (Get-Service -Name $serviceName)
Write-Host ">> Service Status:" ($service.Status | Out-String)

if ($service.Status -eq 'ContinuePending'){
	">> STATUS ContinuePending!"
}
if ($service.Status -eq 'Paused'){
	">> STATUS Paused!"
}
if ($service.Status -eq 'PausePending'){
	">> STATUS PausePending!"
}
if ($service.Status -eq 'Running'){
	">> STATUS Running!"
}
if ($service.Status -eq 'StartPending'){
	">> STATUS StartPending!"
}
if ($service.Status -eq 'Stopped'){
	">> STATUS Stopped!"
}
if ($service.Status -eq 'StopPending'){
	">> STATUS StopPending!"
}

Comentários