Windows PowerShell tutorial for beginners
2022-4-24 05:41:59 Author: kalitut.com(查看原文) 阅读量:32 收藏

In this PowerShell tutorial I will provide you with practice-oriented knowledge about PowerShell. Would you like to do your IT tasks better and more efficiently and would you like to use PowerShell for this? In this PowerShell tutorial you will learn the necessary basics. With practical examples, you can easily understand the tasks shown.

PowerShell tutorial for beginners

In this PowerShell introduction we would like to accompany you in several chapters through the different techniques of PowerShell. Starting with the simple basics through to practice-oriented scripts that will make your everyday work easier.

PowerShell Introduction

Visual Basic Script has long been the scripting language for IT administrators and developers.

Since PowerShell has been on the market, more and more PowerShell scripts have been used to simplify and automate IT processes.

Windows PowerShell

Windows PowerShell has been available since Windows 7 and can only be used on Windows client and server systems. Windows PowerShell is preinstalled on Windows systems by default.

PowerShell Core 6.0

PowerShell Core 6.0 has been publicly available since 2018 and can be used regardless of the operating system. PowerShell is now also available on Linux, MacOS and of course Windows.

PowerShell 7

PowerShell 7 has been publicly available since March 4th, 2020 and can be used regardless of the operating system. PowerShell 7 brings more new features and a compatibility mode for older PowerShell commands.

PowerShell .vs cmd.exe .vs Visual Basic Script

Now I want to show you a figure that shows how relevant PowerShell is to Visual Basic and CMD. You can see that the use and popularity of PowerShell has been increasing steadily since 2004.

PowerShell .vs cmd.exe .vs Visual Basic Script
PowerShellVisual Basic Scriptcmd.exe
From Windows 7: Integrated PowerShell Console to query and make changes to the operating system and applications.No console included in the operating system.Old Windows console still used for standard commands like ping and . co is used.
PowerShell is a framework and is based on CMDLETs, which are commands that are added as PowerShell modules. PowerShell modules are constantly being developed and are manufacturer-independent.Visual Basic has built-in commands that are limited in their functionality.The CMD uses so-called batch files that are only rarely used.
PowerShell works with objects and pipes, making complicated queries easier to process.Visual Basic is limited in use and, in my opinion, not that flexible.The Command Prompt has text-based processing and can call applications that first have to be programmed at great expense and are available as Windows programs *.exe.
PowerShell is 2018 operating system independent and is available as PowerShell Core. PowerShell can now be used for Linux, Mac OS and of course still for Windows.Visual Basic is a Microsoft scripting language. However, Microsoft is increasingly relying on PowerShell.The cmd.exe is only available for a Windows operating system. It is used for older applications and standard commands like "ping".

Was is Windows PowerShell?

Windows PowerShell is a framework developed by Microsoft based on the .Net Framework.

Windows PowerShell essentially consists of two components. Once the PowerShell Interpreter and the actual PowerShell script language.

PowerShell Interpreter
The PowerShell Interpreter is an application that translates PowerShell commands into understandable machine code.

PowerShell scripting language
The scripting language for PowerShell is object-oriented and therefore simply structured.

The application for Windows PowerShell is called. “powershell.exe”. When you start this application, you will get a console similar to the “cmd” console.
However, the PowerShell console is shown in blue. If you are using a Windows operating system higher than Windows XP, just search for PowerShell and open it.

PowerShell scripting language

Now you can enter a command in this PowerShell console.

For example, let’s take the command to list all processes on the Windows system on which you just started powershell.exe.

The command is called: Get-Process

Powershell Get-Process

With this command you can see all the processes that are currently running on your Windows system. For example, you could now end some processes, display more information about a specific process, or restart a process and so on.

But before you dig deep, let’s learn a few important basics.

Why PowerShell?

Windows PowerShell is installed by default from Windows 7 and can be used in all subsequent Windows versions. From Windows Server 2012 R2 onwards, most graphical server tools use PowerShell commands in the background, which are only displayed graphically for the administrator.

PowerShell modules are provided by the most well-known technology manufacturers in the world. With these PowerShell modules you can use PowerShell to access and administrate the manufacturer’s hardware.

Microsoft has built such PowerShell modules for all of their products. You can use PowerShell to manage all Windows versions from Windows Server 2008 with PowerShell. Furthermore, you can simultaneously administrate all Windows applications such as Active Directory, DNS, Exchange, Hyper-V, file servers, etc. with PowerShell.

With the right PowerShell knowledge, you can complete your tasks more efficiently and easily.

With the introduction of PowerShell Core 6.0 on January 12, 2018, PowerShell has become operationally independent. With PowerShell Core 6.0, the commands and scripts written in Windows can also be executed on a Linux derivative. The other way around too, of course.

In this PowerShell tutorial you will learn how to best use PowerShell. With simple practical examples, I will show you PowerShell as you can use it in your everyday life.

I wish you lots of success and fun learning PowerShell in this free PowerShell tutorial.

Windows PowerShell .vs PowerShell 6.0 Core .vs PowerShell 7

Since the beginning of the year, on January 12th, 2018, the media started with the news that PowerShell 6.0 Core was publicly available. PowerShell 6.0 Core is intended to extend Windows PowerShell, which has been known in the Windows world and beyond for years.

PowerShell Core 6.0 is not a successor to Windows PowerShell in that sense. It’s a picture of that. The main difference between PowerShell Core 6.0 and Windows PowerShell is that PowerShell Core 6.0 is not based on the .Net Framework but on the .Net Core Framework. This means that it can also be used on other operating systems than Windows, such as Linux or MacOS.

With PowerShell 7, Microsoft has opened another milestone.

PowerShell 7 brings us more possibilities in scripting and using PowerShell. Furthermore, PowerShell 7 has a compatibility mode for Windows PowerShell commands.

Thus, Windows PowerShell remains the most used scripting tool in the Windows world. Hence the name “Windows PowerShell”. I guess with PowerShell 7 that will change in the next few years. So that Windows administrators use PowerShell 7 as standard.

I’ll cover the basics in this PowerShell tutorial. So that you can use them in Windows PowerShell as well as in PowerShell 6.0 Core and PowerShell 7.

PowerShell 7

PowerShell 7 is available since March 2020 after 2 years of development . 

PowerShell 7 is the successor to Windows PowerShell and PowerShell Core.

In this blog post, I will explain why Microsoft released PowerShell 7.

In addition, I will show you what the advantages of PowerShell 7 are and how to download and install it.

Invoke Windows PowerShell?

Windows Powershell is called with “powershell.exe” as described in the introduction.
Windows Powershell is from Windows and does not have to be installed separately.

Go to PowerShell 7

PowerShell 7 is not yet part of the Windows operating system. with the next Windows version PowerShell 7 will be included by default.
However, Microsoft has published the installation files for everyone who wants to use PowerShell 7. So that you can post-install Powershell 7.

Here are a few links where you can download PowerShell 7 and the corresponding instructions on how to install PowerShell 7 on Windows. If you want to install PowerShell 7 on Windows, download the .msi. Installing PowerShell is super easy with an MSI.

Download and install PowerShell 7

To download and install PowerShell 7 , please go to the following link.

https://github.com/PowerShell/PowerShell/releases/tag/v7.0.0

After you have downloaded PowerShell 7 you can install it eg on your test system.

installing PowerShell 7

After you install PowerShell 7, you can open the console and test PowerShell

test PowerShell

Once you have the PowerShell 7 console open, enter the command there .

You will now see information about the current PowerShell version.

Here the PS version should have at least the value 7.XX. If so, then you are currently using PowerShell 7.

Have fun trying it out .

CMD.EXE | POWERSHELL.EXE | PWSH.EXE

Here is a small representation of how script processing and command processing has developed over the years. Starting from the cmd console, which was already in use in IBM computers in 1981 and in 2018 we can use PowerShell cross-platform.

PowerShell cross-platform

So, that’s been a little story in the world of PowerShell for now. Now I would like to jump into the basic introduction of PowerShell with you.

I would like to first show you which platform PowerShell is used for and then let’s look at the PowerShell methods to control or administrate this system. At the beginning it is very important to understand how and where PowerShell can be used or is already being used. The systems described are examples from practice.

How and where is PowerShell used?

Let’s assume you work a lot with Windows systems, then you can use PowerShell to administrate the following systems, among others. There’s a lot more, but first I’d like to show you where PowerShell is used in practice, for example.

Windows System

  • Windows Server 2008
  • Windows Server 2008 R2
  • Windows Server 2012
  • Windows Server 2012 R2
  • Windows Server 2016
  • Windows Server 2019

Windows server applications

  • Activce Directory
  • DNS
  • DHCP
  • Exchange Server
  • Fileserver
  • Hyper-V
  • Failover Clustering
  • Storage Spaces Direct
  • Storage Replica
  • Printserver
  • IIS Web Services

Windows basic configuration

  • network adapter
  • network teaming
  • Disks
  • Firewall
  • Proxy
  • Registry
  • files and folders

Third Party Storage Hardware Administration

  • Disks
  • SMB
  • Raid Controller
  • SAN
  • iSCSI
  • Storage Controller

Hyper-V Administration

  • VMs
  • Hyper-V Hosts
  • VMs Disks
  • virtual network
  • virtual disks

Azure Administration

  • VMs in Azure
  • Azure Site Recovery
  • Azure Ressource Manager
  • Azure Services

But before you can administer the individual systems with PowerShell, let’s first go into the PowerShell basics, which I would like to show you now.

PowerShell commands

PowerShell Module und CMDLETS

PowerShell itself is a platform that provides an interpreter. The real PowerShell power comes from the modules that are developed by the manufacturers and by the community. For example, Microsoft develops PowerShell modules for Active Directory, Windows Server and so on. For their products. Another company develops PowerShell modules for your applications or hardware.

A single module usually consists of several functions, these are called cmdlets in PowerShell.

Here’s an example:

If you want to administrate Active Directory with PowerShell, then you have to load the “ActiveDirectory” module in PowerShell. If you log on to a domain controller and call up PowerShell there, the PowerShell module is already preinstalled.

Remote Server Administration Tools – RSAT

If you want to administrate Active Directory via your Windows client with PowerShell, then install the RSAT package.

After installing RSAT on your client, open the PowerShell console and type Get-Module.

Remote Server Administration Tools - RSAT

Import the Active Directory module with Import-Module activedirectory

If you now run the “Get-Module” command, you will now see the imported Active Directory module.

Get-Module

As soon as the “ActiveDirectory” module is installed or if you are logged on to a domain controller, you can use the “CMDLETS” such as

New-ADUSer
Get-brought the

The CMDLETS are basically functions that can do something. Like creating new users with “New-ADuser” or displaying users with “Get-ADUser”.

The most common PowerShell command types – Get, Set, Enable, Remove, Disable, Add, New
As you have already noticed, the PowerShell commands always follow the same syntax. Depending on the function of the command, it begins with a specific word. e.g. “Get-“. Get means to get in English. Say with this command you want something displayed.

Here is a representation of the basic types of commands that you will find in PowerShell, among other things. Of course, the correctness depends on the module or CMDLET that you use and who programmed it.

  • Get display a value.
    • Get-Process
    • Get-NetAdapter
    • Get-Host
  • Set Add a value i.e. adjust something.
    • Set-ACL
    • Set-DnsClient
    • Set-NetAdapter
  • New Create a new share or create a new file.
    • New-NetAdapterAdvancedProperty
    • New-FileShare
    • New-Item
  • Remove & Stop Delete a file or end a Windows process.
    • Remove-Item
    • Stop-Process

Whatever task you want to accomplish with PowerShell, first check the requirements.

Before you can use a command with PowerShell or before you write a PowerShell script, you should be clear about what you are doing, i.e. what the goal is and whether it is worth writing a PowerShell script.

Don’t get me wrong, I’m a big fan of PowerShell and it makes everyday IT life a lot easier. But before you want to complete a task with PowerShell, you should ask yourself a few questions to find out whether you just take a command, write a script, or prefer to complete the task in a different way.

I will describe the process in a little more detail; in everyday life, with a little experience, you would already have the decision in your head in a few seconds or minutes. The important thing is that you already have a few thoughts in mind.

So that you can quickly decide whether to complete a task with PowerShell or use another method, you should ask yourself the following questions:

  1. Is there a PowerShell interface that can be used to do the job?
  2. Does the task come up frequently or is it a one-time thing?
  3. If it’s a one-time thing? Is it possible easier and faster via the GUI?

If you find this to be a task that you have to do over and over again, then this is a wonderful candidate for PowerShell.

Is it a one time command? or do you need a script?

If you have to perform a task recurring every day, then it is worth writing a script. The script would then contain the command that you would otherwise have to run every day, such as deleting a file.

Remove-Item -Path "path to file"

It’s a simple example, but you get the point. Automate repetitive tasks that keep you from your essential work with PowerShell.

PowerShell & Pipes

In PowerShell, pipes are a method of routing something. Pipes means “tube” in German and is the synonym in PowerShell to transport something that is then processed on the other side and then possibly. is transported again.

An example:

You want to end the OneDrive process on your server or client.

With “Get-Process” you get all Windows processes and can check what the OneDrive process is called in Windows.

First of all, we only display the process name and the ID by further “pipening” the output. Piping is represented by the “|” character in PowerShell.

Get-Process | Format-Table ProcessName, Id
Get-Process | Format-Table ProcessName

Now that we know what the OneDrive Windows process is called, we can end it.

This can be done with the “Stop Process” command.

Stop-Process -Name onedrive

Alternatively, we could look for the “onedrive” process and then pipe to the “Stop-Process” command.

Get-Process -Name onedrive | Stop-Process

If we now look for the Windows process “onedrive”, it no longer exists because we have terminated it.

Stop-Process

You can also restart the process with PowerShell using the “Start-Process” command.

If we look for the “onedrive” process again, we see that it is accessible again.

PowerShell Filter

Of course, PowerShell also has filter functions. 

There are filters that are already provided by the command. However, if such a filter function is not sufficient or does not exist at all, then you can access the PowerShell filter functions.

The filter function in PowerShell is called “where” or simply “?”. The filter function is used using the pipe function. Let’s go straight to the examples to make it clearer.

Here is a filter function provided by the “Get-Process” command. You can enter the name of the window process and only this process will be displayed.

Get-Process -Name onedrive
Get-Process -Name

However, you can also achieve the same thing with the where command in PowerShell. Enter the command “where” after “pipe”.

Get-Process | where {$_.ProcessName -eq „onedrive“}
Get-Process-where

But let’s assume you know which Windows process you want, but don’t know the full name? Then you can work with the characters “*” and the parameter -like.

This will output all processes that begin with the name “one”. E.g. “onedrive” but also “onenow”.

Get-Process | where {$_.ProcessName -like „one*“}
ProcessName

Instead of the “where” command, you can also simply enter “?”. “?” is synonymous with “where” and is also interpreted as such in PowerShell. This shortens the command and is clearer.

Get-Process | ? ProcessName -eq „one*“

Save PowerShell output to variables

Variables in PowerShell are containers that can hold values. Let’s take the variant that you want to manually assign a value to the variable.

Suppose you want to work with the Windows processes in PowerShell. Then you wouldn’t be using the Get-Process command over and over again.

You can also store the output of Get-Process in a variable.

Example:

$oneddriveprocess=Get-Process -Name onedrive

If you now type the variable name into PowerShell, you will get back the saved output. In this example we have stored the output from the “onedrive” process in the variable $onedriveprocess.

oneddriveprocess

You can now also stop the process by piping the variable to the “Stop-Process” command.

$oneddriveprocess | Stop-Process

If you now enter the variable name back into PowerShell, you will see that the OneDrive process has ended because no values ​​are output. This means that the variables refer directly to the objects. Isn’t that great?

oneddriveprocess

PowerShell Scripts

You do not need any extra software or similar to create a PowerShell script.

Simply open an editor, for example “notepad.exe”. Now save this file with the extension filename.ps1.

If you now click on this file, the file will be executed as a PowerShell script.

PowerShell Scripts

Now we could fill the PowerShell script with life and do a task more easily and efficiently in the future.

But before we get into the creation of scripts and its techniques, I would like to go through the basics of PowerShell and its commands with you. Furthermore, in the following chapters we will go into the programming basics that you use in scripts to create dynamic and intelligent PowerShell scripts.

Additional information and an overview of PowerShell commands can be found in this blog post.

Programming with PowerShell

This chapter covers programming basics with PowerShell. 

You have to program or script if you write a dynamic or PowerShell script that has a certain intelligence.

I don’t want to show you all the programming techniques that are available here, after all you don’t want to do any programming training with this tutorial.

I will show you the programming techniques that I use myself in practice and that have mostly been sufficient for me so far. I just want to give you the most important programming skills you can use to write your own PowerShell scripts.

Variables

In PowerShell, variables are objects that store a specific value and can then be processed further.

Comparison operators

Comparison operators are used to determine whether a given value is equal to another value or not.

if queries

If statements are used for logical control in scripts.

Ribbons

Loops are used in scripts to control the frequency of a specific task.

Variables example

Create an array variable.

Create an empty array variable.

Create an ArrayList. This is an inheritance from the .Net Framework.

$Array = New-Object System.Collections.ArrayList

Comparison operators

Comparison operators are used when one value is to be compared with another value.

Let’s assume you have a variable that contains a value X and a variable that contains a value Y.

Now you want to compare these two values ​​to see if value X is greater than value Y.

If the value of X is greater than the value of Y then the value of Y should be added by 1.

The script would look like this in PowerShell:

$X= 5
$Y= 2
if($X -gt $y)
{
           $X+=1
}

There are various comparison operators that you can use.

Comparison OperatorMeaningExample
-eqsameif($X -eq $y)
-neunequalif($X -ne $y)
-ltkleinerif($X -lt $y)
-leSmaller or equalif($X -le $y)
-gtgreaterif($X -gt $y)
-gegreater or equalif($X -ge $y)

if queries

You control the script with an if statement. With an if query you check a certain value again and again and then decide what happens next.

As shown in the previous example, if X is greater than Y, then the value of X should be added by 1.

You can also decide to exit the script or do something else, like run a specific command.

For example, let’s say you want to check if the user wants to kill the onedrive process. We’ll simulate that. The variable X is the user’s input.

Then the script would look like this.

$X= „onedrive“
if($X -eq „onedrive“)
{
    Stop-Process -Name onedrive
}

In addition to the if query, “else” is also used. That’s why I always call this query if-else query.

With “if” you check a certain value and then decide what to do. But what if this value does not match, then you also want to do something, right?

Let’s take our example from above. You want to check if the user wants to kill the onedrive process. However, the user enters a different name. Then you want to make the user aware that the process does not contain the specified name.

The script would then look like this:

$X= „onedrive“
if($X -eq „onedrive“)
{
    Stop-Process -Name onedrive
}
else
{
    Write-Host "The process name $X does not exist. Do you mean the onedrive process?”
}

The “else” simply says if the if statement doesn’t match then do the following.

Now you know how to query if and else. Let’s go one step higher and assume that you want to check multiple values ​​in the if statement.

For example, you might want to allow the user to just type the word “one” to kill the “onedrive” process.

You can do this by using logical operators in the if statement.

Attached is the example with the logical operator “-or”. Or stands for or and means if one or the other value is correct, then do the following.

$X= „one“
if($X -eq „onedrive“ -or $X -eq „one“)
{
    Stop-Process -Name onedrive
}

There are 4 different logical operators in if queries that you can use depending on the situation.

Operatordescriptionexample
-andandif($X -eq "onedrive" -and $X -eq "one")
-ororif($X -eq "onedrive" -or $X -eq "one")
-xorEither or(Only if one of the values ​​is correct.) if($X -eq "onedrive" -xor $X -eq "one")
-notNot(If you want to prevent e.g. then the user enters a specific value.) if($X -eq "onedrive" -not $X -eq "one")

Ribbons

Loops are used to repeat a certain event over and over again until a certain value is reached.

The following loops are often used in practice and are usually sufficient for all tasks.

  • For
  • While
  • Foreach

The for loop

The For loop is very useful for tasks when you know what value you started with and what the end value will be.

Example: You only want to perform a certain task 9 times. Then you would build a For loop. Set the start value to 0 and the end value to 9. As long as the variable “$x” has a value less than 9, the loop is repeated.

for($x=0;$x -lt 9;$x++)
{
Write-Host "Executing code $x"
}

The while loop

The “while” loop is very useful when you have a task where you don’t know when the value will be reached.

Example: You have the variable “$x” with the value “0”. You want the loop to run until the variable “$x” has the value “10”. For each iteration of the loop, you can output the value in the variable “$x” with Host-Host.

Caution: the while loop would never end if we didn’t add the “$x+=1” command inside the loop. If we didn’t do that, the variable “$x” could never reach the value 10 and so the loop would run indefinitely.

$x=0

while($x -le 10)
{
Write-Host $x
$x+=1
}

The Foreach Loop

The “foreach” loop is very suitable for lists and arrays. Where multiple objects are stored in a variable and you want to manipulate each object individually.

Example: Let’s say you have an “array” with two values. You want to edit each value individually. Then you would use the foreach loop for that.

$array=“Wert1″,“Wert2″

foreach($wert in $Array)
{

Write-Host $wert
}

Create a PowerShell script

I will show you how to create and run a PowerShell script and what you need to pay attention to. If you’re excited, let’s get started.

However, before you can start a PowerShell script under Windows, the system must first be allowed to run scripts.

Set-Execution Policy

PowerShell is a powerful tool that allows you to control most Windows applications and system settings.

For this reason , a security mechanism is also set up under PowerShell , which prohibits the automatic execution of PowerShell scripts . However, you can deactivate or adjust this mechanism manually .

The command to change the settings is called. “Set ExectionPolicy”

Allow the execution of PowerShell scripts

To do this, open the PowerShell console (powershell.exe) in Administrator mode and then enter ” SetExecutionPolicy RemoteSigned ” .

Set-ExecutionPolicy RemoteSigned

In addition to the “ RemoteSigned ” variant, there are others that you can use as required.

Attached is a table that shows the effect of the individual commands.

CommandDescription
Set-ExecutionPolicy RemoteSignedOnly trusted scripts are allowed to run. Locally created scripts may also be executed after confirmation.
Set-ExecutionPolicy AllSignedAll scripts must be signed by a trusted authority, including scripts created locally.
Set-ExecutionPolicy RestrictedForbids loading PowerShell scripts on the system.
Set-ExecutionPolicy UnrestrictedAllows all scripts to be run. However, if you use a script that you have downloaded from the Internet, you will be asked again before execution.
Set-ExecutionPolicy BypassAll scripts are allowed. There is also no warning etc. displayed.
Set-ExecutionPolicy UndefinedRemoves the current settings for the ExectionPolicy.

After allowing the execution of PowerShell scripts , we can now create a PowerShell script together .

However, before you start creating a PowerShell script, let me first explain how a PowerShell script is structured.

Then I’ll show you three tools that I personally use to create and customize PowerShell scripts.

Script without input parameters

A script without input parameters is intended for static processing. No data can be given. Example:

param(
[Parameter(Mandatory=$true)][string]$wert
)
Write-Host $wert

Script with input parameters

A script with input parameters can be given data that can then be used in the script.
Example:

What is a PowerShell script ?

A PowerShell script is simply a sequence of functions that are automatically executed one after the other. 

Functions are commands that perform a specific task.

What file extension does a PowerShell script have ?

The file extension for PowerShell scripts is “ps1”.

Example: Scriptname.ps1

How do you create a PowerShell script ?

A PowerShell script is not a programming language that first has to be translated into machine code. This means that you can practically create a PowerShell script with a text editor. The PowerShell engine then takes care of the translation.

In practice, however, tools such as the PowerShell Integrated Scripting Environment (ISE) or Visual Studio Code are used.

With PowerShell ISE, you can also immediately test your scripts and check for logical function.

I will now introduce you to the three variants and show you how to create a PowerShell script.

3 top tools to create PowerShell scripts

Text editor
Right! You can create your PowerShell script with a text editor like Notepad. All you have to do is save the file with the file extension “.ps1”.

Here I create a PowerShell script with the command “Get-Process”.

PowerShell script
PowerShell script with the command "Get-Process".
PowerShell scripts file

PowerShell ISE

The PowerShell ISE was developed by Microsoft for creating PowerShell scripts.

This is installed by default on every Windows system.

The advantage of PowerShell ISE is that many predefined Windows PowerShell commands can be used easily. You can also run and test your PowerShell script directly in PowerShell ISE.

The PowerShell ISE only supports Windows PowerShell 5.0. If you want to use PowerShell Core or PowerShell 6.0/7.0, please use the “Visual Studio Code” tool.

Visual Studio Code

Visual Studio Code is a development interface based on Visual Studio. This was simplified by building it as a framework. In other words, if new functions are required, they must be downloaded and installed as Visual Studio modules.

You must download Visual Studio Code as it is not installed by default.

visual code

Before you start writing PowerShell scripts in Visual Studio Code, you should install the PowerShell module.

Go to the search bar and enter “powershell”.

Click on “Install” and then on “Reload”

PowerShell module

Now you can start writing a PowerShell script with File->New File.

Now save the script by selecting the file type PowerShell.
So now we have created the same script with 3 different tools.

Let’s go to the next point: How to run a PowerShell script.

How do you run a PowerShell script ?

You can start the PowerShell scripts you just created either with the right mouse button “Run with PowerShell” or directly with PowerShell.

But before you can run a script, you have to change a security setting.

To do this, open PowerShell as “Administrator”

PS>: Set-ExecutionPolicy –ExecutionPolicy RemoteSigned

PowerShell Script example

To make scripting easy for you, here we use creating and managing folders and files on Windows as an example.

What commands are used here to edit files and folders.

Script without input parameters

Suppose you have to place 10 folders with a specific name in the path C:\Temp every day. Then you can write a script for what this would do for you every day.

You want to create the following subfolders under the C:\Temp folder.

  • folder 1
  • folder 2
  • folder 3
  • folder 4
  • folder 5
  • folder 6
  • folder 7
  • folder 8
  • folder 9
  • folder 10

In the script we would then create a command for each subfolder, such as

New-Item -Path „c:\temp“ -Name „Ordner 1“ -ItemType Directory

Script with input parameters

Let’s assume that you need to create different folders every day. But she doesn’t want to adjust the script every day. To achieve this use input parameters in PowerShell.

To capture input parameters in PowerShell there is the command “Param”

The following command forces the user to enter a value when running your script. To do this, for example, write the command “param” and the variable in which you want to save the input in your PowerShell script at the beginning of the script. As usual, we use Write-Host to output the input value.

param(

[Parameter(Mandatory=$true)][string]$wert
)

Write-Host $wert

For example, save your script under C:\temp with the name myscript.ps1.

Open the PowerShell console and change to the directory c:\temp with “cd c:\temp”.

Enter the following: .\myscript.ps1 -value “Test”

You should now have the word Test as the output. Congratulations, you’ve written a great PowerShell script.

All right, now you know how to create and run a PowerShell script using the various tools.

I hope you enjoy scripting.

Functions in PowerShell

Functions are used in PowerShell to structure multiple tasks into logical subtasks. For example, if your script performs multiple tasks that are already complex to you, you could group those tasks as functions.

Let’s assume you want to read out all folders on a Windows system and then save this folder structure in a text file. Then you could split these tasks into two functions.

  1. Read folder structure
  2. Save the folder structure in a text file.

The functions for this would look like this in PowerShell.

function read folder structure()
{

}
function savefolderstructure()
{

}

You would run the functions in PowerShell by entering the function name.

In the two examples, you would call it in PowerShell by simply writing the function name.

The complete script for this looks like this.

function read folder structure()
{

}
function savefolderstructure()
{

}

read folder structure save
folder structure

Delete and create folders: With Windows PowerShell

Do you want to use PowerShell to delete, create and change the properties of your folders and files?
I’ll show you exactly how to do it with PowerShell.

To edit folders, you need the following PowerShell commands, also known as CMDlets.

  • Remove Item | Remove a folder or file
  • Get Item | View a folder or file
  • Set Item | Change folder or file properties
  • New Item | Create a new folder or file
  • Get-ChildItem | show subfolders

First, open PowerShell by searching for Windows PowerShell.

Please make a backup beforehand

When working with PowerShell on folders and files on a production system, always make a backup beforehand. Better safe than sorry.

Delete folders and files with Windows PowerShell

Delete a folder in PowerShell with the “Remove-Item” command
Example 1: Delete a folder

Remove-Item -Path "C:\Temp\TestFolder1\"

Example 2: Delete all subfolders from directory “C:\Temp\Test Folder1\”.

With Get-ChildItem we first display all subfolders and then pipe them to Remove-Item. Remove-Item then deletes each subfolder.

For Get-ChildItem we also entered “-Directory” so that only folders are listed.

If you want to delete files instead, use “-File”.
If you want to delete files and folders, simply omit the two parameters.

Get-ChildItem -Path "C:\Temp\TestFolder1\" -Directory | Remove item

Example 3: Only delete empty folders

For this we use a PowerShell script:

First we let all folders and subfolders of “C:\Temp” be displayed and then we check whether each folder is empty or not.

If a folder is empty, then we remove it with Remove-Item.

$showallfolders=Get-ChildItem -Path "C:\Temp\" -Directory -Recurse
foreach(show $folder in $allfolders)
{
    if(($folder | Get-ChildItem -Recurse).Count -eq 0)
    {
      Remove-Item -Path $folder.FullName
    }
}

Create folders and files with Windows PowerShell

You create folders in PowerShell with the “New-Item” command
Example 1: create folders

New-Item -Name "Test Folder" -ItemType Directory -Path "C:\Temp\"

Example 2: Create file

New-Item -Name "Filename.txt" -ItemType File -Path "C:\Temp\"

Conclusion

With PowerShell you can create and delete thousands of folders in minutes, and do most of your system administration from within PowerShell

Use this function consciously and efficiently but also carefully.

And don’t forget, before working on a production system, always make a backup first.

I wish you much success.


文章来源: https://kalitut.com/powershell-tutorial-for-beginners/
如有侵权请联系:admin#unsafe.sh