50 Comandos GNU X 50 Comandos PowerShell

🐂 🆚 ✴️ Vários comandos do dia a dia usados no terminal do GNU e equivalentes em PowerShell.


50 Comandos GNU X 50 Comandos PowerShell


No mundo da automação de tarefas, dominar a linha de comando é uma habilidade essencial. Seja com os tradicionais comandos GNU, ou no ecossistema Windows, com o poderoso PowerShell, conhecer as ferramentas certas pode transformar sua produtividade.

Nesta postagem, vamos confrontar 50 comandos GNU com seus equivalentes no PowerShell.


💻 01. Remover um diretório recursivamente

🐂 GNU

rm -rf /home/$USER/folder

✴️ PowerShell

Remove-Item -Path "C:\folder" -Recurse -Force

💻 02. Obter nome de um processo que está rodando:

🐂 GNU

ps aux | grep apache2 # httpd

systemd: systemctl status apache2

✴️ PowerShell

Get-Service | Where-Object { $_.DisplayName -like "*Apache*" }

💻 03. Parar um serviço

sudo kill -9 $(pidof apache2) # httpd

systemd: sudo systemctl stop apache2

✴️ PowerShell

Stop-Service -Name "Apache2.4"

💻 04. Remover uma Variável de Ambiente

🐂 GNU

unset NOME_DA_VARIAVEL

✴️ PowerShell C:\App\bin

# Obtenha o valor atual da variável de ambiente Path do sistema
$envPath = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine)

# Separe os caminhos em um array
$paths = $envPath -split ';'

# Filtre para remover o caminho que você não quer mais
$newPaths = $paths | Where-Object { $_ -ne "C:\App\bin" }

# Recrie a variável de ambiente Path (sem o caminho indesejado)
$newPathString = ($newPaths -join ';').TrimEnd(';')

# Atualize a variável de ambiente do sistema
[Environment]::SetEnvironmentVariable("Path", $newPathString, [EnvironmentVariableTarget]::Machine)

💻 05. Verificar se um comando existe

🐂 GNU

which mycommand

✴️ PowerShell

Get-Command mycommand

💻 06. Criar uma pasta/diretório

🐂 GNU

mkdir my-project

✴️ PowerShell

New-Item -ItemType Directory "MyProject"

💻 07. Criar uma pasta/diretório recursivamente

🐂 GNU

mkdir -p my-project/folder/new

✴️ PowerShell

New-Item -Path "C:/MyProject/folder/new" -ItemType Directory

💻 08. Mover uma pasta/diretório de lugar

🐂 GNU

mv folder new/path/

💻 PowerShell

Move-Item -Path "folder" -Destination "C:\new\path\"

💻 09. Entrar em um pasta/diretório

🐂 GNU

cd pasta/

✴️ PowerShell

Set-Location pasta

💻 10. Copiar arquivos e diretórios

🐂 GNU

cp file path/to/dest
cp -r folder/ path/to/dest

✴️ PowerShell

Copy-Item file path\to\dest
Copy-Item folder\ -Recurse -Destination path\to\dest

💻 11. Obter a pasta pessoal e/ou nome do usuário

🐂 GNU

$HOME
# echo $HOME

$USER
# echo $USER

✴️ PowerShell

$env:USERPROFILE
# Write-Host $env:USERPROFILE

$env:USERNAME
# Write-Host $env:USERNAME

💻 12. Listar arquivos e diretórios

🐂 GNU

ls -la

✴️ PowerShell

Get-ChildItem -Force

💻 13. Mostrar conteúdo de um arquivo texto

🐂 GNU

cat file.txt

✴️ PowerShell

Get-Content file.txt

💻 14. Buscar texto dentro de arquivos

🐂 GNU

grep "termo" file.txt

✴️ PowerShell

Select-String -Pattern "termo" -Path file.txt

💻 15. Exibir uso de disco

🐂 GNU

df -h

✴️ PowerShell

Get-PSDrive -PSProvider FileSystem

💻 16. Ver uso de memória

🐂 GNU

free -h

✴️ PowerShell

Get-CimInstance Win32_OperatingSystem | Select-Object TotalVisibleMemorySize,FreePhysicalMemory

💻 17. Exibir variáveis de ambiente

🐂 GNU

printenv

✴️ PowerShell

Get-ChildItem Env:

💻 18. Renomear arquivo/diretório

🐂 GNU

mv oldname newname

✴️ PowerShell

Rename-Item -Path oldname -NewName newname

💻 19. Executar comando como administrador/root

🐂 GNU

sudo comando

✴️ PowerShell (executar shell como administrador)

Start-Process powershell -Verb runAs

💻 20. Ver rede/interfaces

🐂 GNU

ip addr show

✴️ PowerShell

Get-NetIPAddress

💻 21. Cria uma variável de Ambiente

Exemplo para Terlang: C:\Program Files\Terlang\bin(Windows) e ${HOME}/.local/terlang/bin/(GNU)

🐂 GNU

export PATH="${PATH}:${HOME}/.local/terlang/bin/"

✴️ PowerShell

[System.Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\Program Files\Terlang\bin", [System.EnvironmentVariableTarget]::Machine)

💻 22. Exibir últimas linhas de um arquivo (tail)

🐂 GNU

tail -n 20 file.log

✴️ PowerShell

Get-Content file.log -Tail 20

💻 23. Exibir processos em tempo real (top)

🐂 GNU

top

✴️ PowerShell

Get-Process | Sort-Object CPU -Descending | Select-Object -First 10

(não é em tempo real, mas dá um snapshot dos processos com maior uso de CPU)


💻 24. Buscar e matar processo por nome

🐂 GNU

pkill -f processo

✴️ PowerShell

Get-Process -Name processo | Stop-Process -Force

💻 25. Monitorar alterações em arquivo (tail -f)

🐂 GNU

tail -f file.log

✴️ PowerShell

Get-Content file.log -Wait


💻 26. Compactar arquivos (tar gzip)

🐂 GNU

tar -czvf archive.tar.gz folder/

✴️ PowerShell

Compress-Archive -Path folder\* -DestinationPath archive.zip

💻 27. Descompactar arquivo zip

🐂 GNU

unzip archive.zip

✴️ PowerShell

Expand-Archive -Path archive.zip -DestinationPath destino\

💻 28. Visualizar variáveis de ambiente específicas

🐂 GNU

echo $VARIAVEL

✴️ PowerShell

$env:VARIAVEL

💻 29. Definir variável de ambiente para a sessão atual

🐂 GNU

export VARIAVEL=valor

✴️ PowerShell

$env:VARIAVEL="valor"

💻 30. Exibir informações do sistema (kernel, SO)

🐂 GNU

uname -a

✴️ PowerShell

Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, OSArchitecture

💻 31. Ver horário e data atual

🐂 GNU

date

✴️ PowerShell

Get-Date

💻 32. Exibir quem está logado no sistema

🐂 GNU

who

✴️ PowerShell

query user

💻 33. Ver portas TCP abertas e processos associados

🐂 GNU

sudo netstat -tulpn

✴️ PowerShell

Get-NetTCPConnection | Select-Object LocalAddress,LocalPort,OwningProcess

💻 34. Buscar arquivos pelo nome

🐂 GNU

find /path -name "arquivo.txt"

✴️ PowerShell

Get-ChildItem -Path C:\path -Recurse -Filter "arquivo.txt"

💻 35. Agendar tarefa (cron / agendador)

🐂 GNU

crontab -e

✴️ PowerShell

# Exemplo simples para criar tarefa agendada via PowerShell
$action = New-ScheduledTaskAction -Execute "notepad.exe"
$trigger = New-ScheduledTaskTrigger -At 9am -Daily
Register-ScheduledTask -TaskName "AbrirNotepad" -Action $action -Trigger $trigger

💻 36. Limpar tela

🐂 GNU

clear

✴️ PowerShell

Clear-Host

💻 37. Mostrar variáveis do sistema (com nome e valor)

🐂 GNU

env

✴️ PowerShell

Get-ChildItem Env:

💻 38. Comparar arquivos linha a linha

🐂 GNU

diff file1 file2

✴️ PowerShell

Compare-Object (Get-Content file1) (Get-Content file2)

💻 39. Executar script local (bash / powershell)

🐂 GNU

./script.sh

✴️ PowerShell

.\script.ps1

💻 40. Parar execução do comando (Ctrl + C)

🐂 GNU

Ctrl + C

✴️ PowerShell

Ctrl + C

💻 41. Obter histórico de comandos na sessão atual

🐂 GNU

history

✴️ PowerShell

Get-History

💻 42. Obter arquivo com histórico de comandos

🐂 GNU

cat ~/.bash_history

✴️ PowerShell

Get-Content (Get-PSReadlineOption).HistorySavePath

💻 43. Buscar texto no histórico de comandos

🐂 GNU

history | grep termo

✴️ PowerShell

Get-History | Where-Object CommandLine -Match "termo"

💻 44. Exibir variáveis definidas na sessão atual

🐂 GNU

set

✴️ PowerShell

Get-Variable

💻 45. Definir variável local (shell/session)

🐂 GNU

VARIAVEL=valor

✴️ PowerShell

$VARIAVEL = "valor"

💻 46. Limitar saída de comando (paginador)

🐂 GNU

command | less

✴️ PowerShell

command | Out-Host -Paging

💻 47. Definir alias (apelido para comando)

🐂 GNU

alias ll='ls -la'

✴️ PowerShell

Set-Alias ll Get-ChildItem

💻 48. Remover alias

🐂 GNU

unalias ll

✴️ PowerShell

Remove-Item Alias:ll

💻 49. Mostrar informações da CPU

🐂 GNU

lscpu

✴️ PowerShell

Get-CimInstance Win32_Processor | Select-Object Name,NumberOfCores,NumberOfLogicalProcessors

💻 50. Abrir editor de texto no terminal

🐂 GNU

vim arquivo.txt

✴️ PowerShell

notepad arquivo.txt

🍖 Bônus:

Fazer download de arquivo:

  • GNU:
wget https://url.com/file.zip
# Ou: wget https://url.com/file.zip -O outronome.zip
  • PowerShell:
Invoke-WebRequest -Uri "https://url.com/file.zip" -OutFile "file.zip"

👓 Veja também:

🔗 7 Exemplos de Uso do PowerShell

🔗 Conheça 7 ferramentas do GNU que são o poder da linha de comando

🔗 10 Dicas de Flags e Parâmetros para GNU GCC

🔗 Personalize seu PowerShell Like a Pro


powershell gnu comandos


Compartilhe


Nosso canal no Youtube

Inscreva-se


Marcos Oliveira

Marcos Oliveira

Desenvolvedor de software
https://github.com/terroo


Crie Aplicativos Gráficos para Linux e Windows com C++

Aprenda C++ Moderno e crie Games, Programas CLI, GUI e TUI de forma fácil.

Saiba Mais

Receba as novidades no seu e-mail!

Após cadastro e confirmação do e-mail, enviaremos semanalmente resumos e também sempre que houver novidades por aqui para que você mantenha-se atualizado!