Basic Commands

Basic PowerShell Commands for Cross-Platform Use#

PowerShell’s strength lies in its cross-platform capabilities. Here’s how you can leverage PowerShell to work seamlessly across Windows, Linux, and macOS.

Identifying the Operating System#

Understanding the operating system you are working on is crucial for scripting. PowerShell provides automatic variables to identify the OS:

  • $IsWindows for Windows
  • $IsLinux for Linux
  • $IsMacOS for macOS

In later examples, we will show how you can use these variables in your scripts to execute OS-specific tasks.

Some Cross-Platform Commands#

PowerShell offers several cmdlets that are universal and work seamlessly across Windows, Linux, and macOS. Here’s a look at some of these commands with real-world usage scenarios:

(Note: In the examples, <path>, <file>, and <content> are placeholders. Replace them with your actual file path, file name, or content.)

  1. Get-ChildItem

    • Usage: Get-ChildItem -Path <path>
    • Purpose: Lists items (files and folders) in the specified path.
    • Example:
      # On any platform, list files in the current directory
      Get-ChildItem -Path .
      
  2. Get-Content

    • Usage: Get-Content -Path <file>
    • Purpose: Reads and displays the content of a file.
    • Example:
      # On any platform, display the content of 'example.txt'
      Get-Content -Path example.txt
      
  3. Set-Content

    • Usage: Set-Content -Path <file> -Value <content>
    • Purpose: Writes or replaces content in a file.
    • Example:
      # On any platform, write 'Hello, World!' to 'example.txt'
      Set-Content -Path example.txt -Value "Hello, World!"
      
  4. Test-Path

    • Usage: Test-Path -Path <path>
    • Purpose: Checks if a given path exists.
    • Example:
      # On any platform, check if 'example.txt' exists
      Test-Path -Path example.txt
      
  5. Copy-Item

    • Usage: Copy-Item -Path <source> -Destination <destination>
    • Purpose: Copies files or directories from one location to another.
    • Example:
      # On any platform, copy 'example.txt' to a new location 'backup\example.txt'
      Copy-Item -Path example.txt -Destination backup\example.txt
      

These commands represent just a small sample of what PowerShell can do across different operating systems. By practicing these commands, you’ll build a solid foundation for more advanced PowerShell scripting.

Next Steps#

  • Experiment: Try these commands on different operating systems to see their cross-platform nature in action.
  • Expand Your Knowledge: As you become more comfortable, explore other cmdlets and their cross-platform capabilities.

Mastering these basic commands is your first step towards harnessing the power of PowerShell in a diverse computing environment.

Continue Your Learning Journey#

Embrace the versatility of PowerShell and make your scripts truly cross-platform!