Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Create and Execute PowerShell Scripts in Windows

PowerShell is a powerful scripting language and command-line shell designed for task automation and configuration management, built on the .NET framework. It is a vital tool for systems administrators and engineers working in a Windows environment. In this article, we'll explore how to create and execute PowerShell scripts, providing practical examples to help you get started.

Creating a PowerShell Script

  1. Open a Text Editor:

    • Use any text editor like Notepad, Notepad++, or Visual Studio Code to create your script. Visual Studio Code is highly recommended due to its rich feature set and extensions for PowerShell.
  2. Write Your Script:

    • Begin by writing your PowerShell commands in the text editor. Here's a simple example that retrieves a list of running processes:

      # Get-ProcessExample.ps1
      Get-Process | Select-Object Name, CPU, ID
  3. Save the Script:

    • Save the file with a .ps1 extension, which is the standard extension for PowerShell scripts. For example, save the above script as Get-ProcessExample.ps1.

Executing a PowerShell Script

  1. Open PowerShell:

    • To execute a script, you need to open PowerShell. You can do this by searching for "PowerShell" in the Start menu and selecting "Windows PowerShell" or "Windows PowerShell ISE".
  2. Set Execution Policy:

    • PowerShell's execution policy determines whether scripts can run on your system. To allow script execution, you may need to change the execution policy. Run PowerShell as an administrator and execute the following command:

      Set-ExecutionPolicy RemoteSigned
    • This command allows scripts created locally to run, while downloaded scripts must be signed by a trusted publisher.

  3. Navigate to Script Location:

    • Use the cd command to navigate to the directory where your script is saved. For example:

      cd C:\Scripts
  4. Execute the Script:

    • Run the script by typing .\ followed by the script name. For example:

      .\Get-ProcessExample.ps1
    • This command executes the script and displays the list of running processes with their names, CPU usage, and IDs.

Examples:

  • Example 1: Listing Files in a Directory

    # ListFiles.ps1
    Get-ChildItem -Path C:\Users\YourName\Documents

    Execute with:

    .\ListFiles.ps1
  • Example 2: Displaying System Information

    # SystemInfo.ps1
    Get-ComputerInfo | Select-Object CsName, WindowsVersion, WindowsBuildLabEx

    Execute with:

    .\SystemInfo.ps1

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.