Until now you typed single commands. From now on you write them into a file, and a series of commands becomes a script: repeatable, checkable, shareable. This lesson shows the tools for that: variables, strings, arrays, hashtables, comparisons, branches and loops, and how a script gets input through parameters. Along the way we build a small script that counts report files in a folder.
A script is a text file
A PowerShell script is a text file with the extension .ps1 that contains commands. You write it in an editor (Visual Studio Code) and start it by calling its path. In the current folder you need .\ in front of the name. PowerShell does not look for commands in the
current folder, so that a script that happens to be named like another command does not run by accident:
Der Begriff „berichte-zaehlen.ps1“ wird nicht als Name eines Cmdlets, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt.
This is the German version of the error message for berichte-zaehlen.ps1 without .\ (the language of the message follows the system; in English it says that the term is not recognized as the name of a cmdlet, function, script file, or executable program). With .\berichte-zaehlen.ps1 it runs. A script in
another place is called with the full path. From another program or a scheduler you start it with pwsh -NoProfile -File <path>.
The execution policy
Windows has an execution policy. Learn describes it like this: it controls under which conditions scripts run, and it is a safety feature meant to prevent the unintentional execution of malicious scripts, but not a security boundary, because a determined user can bypass it. It does not affect
commands typed interactively, only scripts. Get-ExecutionPolicy -List shows the setting per scope: MachinePolicy, UserPolicy, Process, CurrentUser, LocalMachine. The value on your machine can differ from the one on the course machine; common values are Restricted (scripts do not run) and
RemoteSigned (local scripts run, downloaded ones need a signature). Windows PowerShell and PowerShell 7 have separate settings. On Linux and macOS Unrestricted applies and cannot be changed. You change the policy for your user with
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser. What matters for you: do not rely on the policy as protection, and do not let a script change it that you do not understand.