Windows: H10 - PowerShell

[Pages:30]Windows: H10 - PowerShell

Introductie

Windows PowerShell getting started ? a new Windows command-line shell, designed especially for system administrators ? includes an interactive prompt and a scripting environment (onafhankelijk of in combinatie) ? built on top of the .NET Framework common language runtime (CLR) and the .NET Framework ? accepts and returns .NET Framework objects ? introduces the concept of a cmdlet

o a simple, single-function command-line tool built into the shell o you can use each cmdlet separately, but their power is realized when you use these

simple tools in combination to perform complex tasks o more than one hundred basic core cmdlets o you can write your own cmdlets and share them with other users. ? gives you access to the file system on the computer ? Windows PowerShell providers enable you to access other data stores o such as the registry and the digital signature certificate stores o as easily as you access the file system ? Windows PowerShell is not a scripting language, or at least it is not only a scripting language. ? PowerShell is an engine designed to execute commands that perform administrative tasks. o Creating user accounts, Configuring services, Deleting mailboxes, ... ? The Windows PowerShell ISE required the Microsoft .NET Framework 3.5 with Service Pack 1.

Interesting keys Page up Page down Up Arrow Down Arrow Home End Ctrl+LeftArrow Ctrl+RightArrow Tab

F7

Jumps to the first command in the history buffer Jumps tot he last command in the history buffer goes back one command in the history buffer goes forward one command in the history buffer jumps tot he beginning of the command line jumps tot he end of the command line goes to the left one word at a time goes to the left right on word at a time Completes input (in the console type get-c and press tab, press tab again...) Shows history buffer (use the up and down arrow keys to navigate the buffer)

Verifying PowerShell version Control your PowerShell version: $PSVerionTable

How to Start with the Import System Modules Task? ? you can add all available modules to a Windows PowerShell session.

get-module -listAvailable | import-module

How to Start with Administrator Privileges? WinServer1 & eigen PC ? Rechtermuisknop PowerShell > Run as Administrator

start-process powershell-verb runAs Update-Help

Pagina 1 van 30

Windows: H10 - PowerShell

Asking for Help Get-Help commandName

? You can also use Help ? PowerShell's help system uses several parameters to reveal more information about commands

o -detailed o -examples o -full (toont alles, inclusief detailed help, per-parameter help, and usage examples) o -online (opent een webbrowser en toont de cmdlet help van de Microsoft Web site)

Reading Help and Using Parameters ? Sommige parameters verwachten geen waarde (bvb. switches): -Recurse ? Voor andere parameters is er een waarde vereist, waarbij het helpbestand aangeeft wat voor

soort waarde de parameter verwacht: -Exclude ? Andere parameters hebben waarden nodig die moeten worden opgegeven om de cmdlet te

laten functioneren: [-Name] ? Sommige parameters zijn optioneel: [-Include ]

Extending the Shell Extra cmdlets zijn beschikbaar via snap-ins en modules. ? Get-PSSnapin ? Add-PSSnapin ? Remove-PSSnapin ? Import-Module ? Remove-Module ? Get-Module (Get-Module -ListAvailable | Import-Module)

Navigating the File System ? PowerShell recognizes many command names you already know

o Most common file-and-folder management commands from both cmd.exe and common Unix shells are available

o However, the parameters of the commands are often different. o For example, the following command will generate an error: dir /s ? External commands, such as ipconfig.exe, pathping.exe, and so on, continue to run exactly as they always have o The distinction is that external commands are external executables, whereas commands

such as "dir" are internal (or, intrinsic) commands

Hierarchical Storage ? The Windows file system is a hierarchical storage system

o It consists of containers (folders, directories), which can contain leaf objects (files) as well as other containers

? The file system is not the only hierarchical storage system in Windows o The registry, The certificate store, Active Directory

? One of PowerShell's key design strategies is to adopt a set of techniques or processes, and then use them for similar tasks o The commands to navigate the registry are the same as those used to navigate the file system o The commands to navigate Active Directory are the same as those used to navigate the file system

Pagina 2 van 30

Windows: H10 - PowerShell

On Set of Commands for Many Forms of Storage

? The ability to use a single set of commands to navigate many forms of storage is made possible by a PowerShell feature called a PSDrive provider

? The PSDrive provider is an adapter that connects to a storage system and presents it to PowerShell o This enables common commands, like cd and dir, to be used against different kinds of storage o Commands are passed to the provider of the drive you are accessing, and the provider does whatever is necessary to implement the command

? Several providers ship with PowerShell by default: o The file system, The registry, The environment variables, The certificate store, IIS, SQL Server, Active Directory

Managing PSDrives

? Get-PSDrive: geeft een overzicht van alle momenteel beschikbare schijven. ? New-PSDrive: cre?ert een nieuwe schijf. U moet de naam van de drive opgegeven, de naam van

de te gebruiken provider en een startlocatie of pad. ? Remove-PSDrive: verwijdert een bestaand schijf.

PowerShell as cmd.exe or Bash

Path Manipulation

PowerShell PowerShell cmd.exe bash Purpose

Cmdlet

alias

Set-Location sl, cd, chdir ch, chdir cd

Verander dir

Get-Location gl, pwd

cd

pwd

Toont huidige dir

Get-ChildItem gci, dir, ls dir

ls

lijst van de huidige dir-inhoud

Push-Location pushd

pushd

pushd Bewaar het huidige pad op een stack

Pop-Location popd

popd

popd Verander neet de laatst pushed dir

File Manipulation

PowerShell PowerShell alias cmd.exe

bash

Purpose

Cmdlet

Copy-Item

cpi, copy, cp

copy

cp

Kopie?r file of dir

Remove-Item ri, del, erase,

del, erase, rmdir, rd rm, rmdir Verwijder file of dir

rmdir, rd, rm

Rename-Item rni, ren

ren, rename

mv

Hernoem file of dir

Move-Item mi, move, mv

move

mv

Verplaats file of dir

Tekst Manipulation

PowerShell PowerShell cmd.exe

bash Purpose

Cmdlet

alias

Get-Content gc, type, cat type

cat

Geef file inhoud

Select-String

find, findstr grep Toon teksten die overeenkomen met een

patroon

Env var Manipulation

PowerShell PowerShell cmd.exe bash

Purpose

Cmdlet

alias

Write-Output echo, write echo

echo

Print strings, variabelen, ... naar

standaarduitvoer

Set-Variable sv, set

set

set

Stel de waarde van een variabele in

/ maak een variabele

Pagina 3 van 30

Windows: H10 - PowerShell

Process Manipulation

PowerShell PowerShell

Cmdlet

alias

Get-Process gps, ps

Stop-Process spps, kill

Help Manipulation

PowerShell PowerShell

Cmdlet

alias

Clear-Host

cls, clear

Get-Help

help, man

cmd.exe bash

tlist, tasklist ps kill, taskkill kill

cmd.exe

cld help

bash

clear man

Purpose

Lijst van alle huidige runnende processen Stop een runnend proces

Purpose

Wis het scherm Help over commands

Consistency is Discoverability ? Get-Command

o Geeft eenvoudige lijst met beschikbare commando's (cmdlets) en functies van alle geladen modules

o retourneert meer dan Get-Help (ook applications) o Get-Command accepteert wildcards, Get-Command *proc* toont cmdlets die "proc"

bevatten o Get-Command heeft een verb parameter, Get-Command -verb get: je ziet alle "Get"

cmdlets o Get-Command heeft een noun parameter, Get-Command -noun *event* toont alle

cmdlets that "event" hebben als deel van noun

Managing Aliases ? You can create your own aliases. You can import and export aliases to share them with

colleagues and coworkers. ? Get-Alias toon teen lijst van alle gedefinieerde aliassen. U kunt ook Dir Alias uitvoeren om een

directory lijst te zien van ALIAS: drive ? New-Alias cre?ert een nieuwe alias. Je moet de aliasnaam opgeven en de naam van het

commando waar het een alias voor is. ? Del of Rm kan gebruikt worden om aliassen te verwijderen van de ALIAS: drive ? Import-Alias en Export-Alias: aliaslijsten van en naar een bestand importeren en exporteren

Pagina 4 van 30

Windows: H10 - PowerShell

Hoofdstuk 1: Algemeen overzicht

Starten met PowerShell

Tips:

? "Ctrl+C":

uitvoer script afbreken

? commando "CLS": shell interface schoonmaken

? Tab-completion:

PowerShell commando automatisch aanvullen

De Shell

? 2 omgevingen: Windows PowerShell

? Windows PowerShell ISE (Integrated Scripting Environment)

Syntax

Get-ChildItem -Path C:\Windows\System32 -Filter *.exe -Recurse

Meestal een WW; met een "Get-Verb" vraag je alle mogelijke werkwoorden; soms geen ww

zoals "New". Wordt gevolgd door een `-e' of een `/'.

WW wordt gevolgd door ZN

Parameters (opties) met daarachter de value (waarde)

Betekenis: toon alle bestanden (Get-ChildItem) uit de map "System32" (-Path) die eindigen op

extensie ".exe" (-Filter), alsook uit alle submappen (-Recurse)

Wildcards `*': vervanging voor alle tekens (*.txt, verslag*.docx, Get-Serv*, *verslag*.txt) `?': vervanging door 1 teken (verslag?.docx, verslag??.docx, verslag?.*, *verslag*.doc?)

Commando's ? Show: "Show-Command Get-ChildItem" u krijgt een venster om parameters in te vullen, vervolgens kiest u copy om commando in de shell te kunne plakken ? Provider: "Get-PSProvider" lijst van providers zoals: FileSystem, Certificaten, Windows Register, ...

Pipeline |-teken uitkomst van een commando doorgeven aan een volgend commando Vb. print spooler stoppen: Get-Service -Name Spooler | Stop-Service

Cmdlets in de shell Get commando ? Get-Help ? Get-Command ? Get-History ? Get-Item ? Get-ChildItem

Set commando ? Opgelet: Voorzichtig! ? Set-ACL: rechten op files en shares aanpassen ? Set-ADGroup: AD groepen aanpassen of toevoegen ? Set-ADUser: AD gebruikers aanpassen of toevoegen ? Set-Alias: aliassen aanmaken of wijzigen ? Set-Date: datum en tijd aanpassen

Pagina 5 van 30

Windows: H10 - PowerShell

In- & output

Exporteren

? Export-CSV "Get-ChildItem -Path `C:\windows' | Export-Csv C:\scripts\archief\log.csv"

? Export-XML "Get-ChildItem -Path `c:\windows' -Recurse | Export-Clixml

C:\scripts\archief\log.xml"

? Out-File

"Get-ChildItem `C:\scripts\archief\*.*' | Out-File -FilePath

C:\scripts\archief.txt"

? Out-Gridview "Get-ChildItem `C:\scripts\archief\*.* | Out-GridView"

? Get-Command -verb out = alle opties met "Out"

? Conversie: "Get-ChildItem -Path C:\scripts\archief\*.* |

? ConvertTo-Html \ Out-File c:\scripts\archief.html" (inhoud van de map "archief"

wegschrijven naar html)

Importeren ? "Import-Clixml -Path C:\scripts\archief\log.xml" ? "Get-Content -Path c:\ scripts\archief\log.xml" (enkel lezen)

Werken vanaf de commandline Door een bestandsysteem "browsen" PowerShell ondersteunt oude DOS-commando's (mbv. aliassen)

? cd: Set-Location ? dir: Get-ChildItem

Aanmaken en verwijderen van bestanden ? Idem als van een object ? New-Item: "New-Item -ItemType file C:\scripts\new.txt" ? Remove-Item: "Remove-Item -Path C:\scripts\new.txt" ? Ook aliassen "del" en "rd" zijn mogelijk

PowerShell drives ? PowerShell herkent standaard uw drives (bv. "C:") ? Echter is er veel meer mogelijk, nl.: certificaten (Cert), register (HKCU, HKLM), ...

Eenvoudige scripts Een aantal commando's na elkaar uitvoeren (automatiseren!) Vereiste: eenvoudige teksteditor als Kladblok of scripteditor als Notepad++ Kan ook in de PowerShell Integrated Scripting Environment (ISE) Extensie: ".ps1"

Uitvoeren van een script 2 manieren om een script uit te voeren:

1. Via de commandline (cmd): "powershell.exe -noexit c:\script.ps1" 2. In PoweerShell zelf (volledige pad moet worden opgegeven): ".\script.ps1"

Pagina 6 van 30

Windows: H10 - PowerShell

Executionpolicy ? Standaard geen scripts uit te voeren ? Get-ExecutionPolicy o Restricted: scritps niet toegelaten o AllSigned: enkel scripts ondertekend door trusted publisher o RemoteSigned: gedownloade scripts ondertekend door trusted publisher & eigen scripts o Unrestricted: alle scripts worden uitgevoerd ? "Set-ExecutionPolicy RemoteSigned" of via ISE (pop-up)

Variabelen Variabelen in PowerShell $-teken om variabele te defini?ren (Vb. $var = `computername' en ${My Variable} = 5 ) =-teken om waarde toe te kennen

Enkele en dubbele aanhalingstekens ? Enkele aanhalingstekens: letterlijke weergave van een tekst (zoveel mogelijk toepassen) ? Dubbele aanhalingstekens: variabelen worden ingevuld in de tekst; echter niet meer ge?pdatet achteraf ? `-teken: variabele als exacte tekst lezen

Verwijderen van een variabele ? "Dir Variabele" lijst variabelen opvragen ? "Del Variable:" variabele verwijderen ? "Get-Variable | Remote-Variabele" alle variabelen verwijderen (foutmelding: standaardvariabelen kunnen niet verwijderd orden, de rest is wel verdwenen) ? "Remove-Variable -Name " nette manier om variabele te verwijderen ? Opgelet: geen $-teken plaatsen, enkel de naam!

Declareren van een variabele ? Van tevoren aangeven wat de inhoud/type (getal, tekst, ...) van een variabele is ? Getal: [int]$a = 5 ? Tekst: [string]$b = `3' of [string]$b = `drie'

Condities

De If-conditie

if(conditie){if actie}[optioneel]elseif(conditie){elseif actie}[optioneel]else{else actie}

PowerShell-conditie

Betekent

Ook wel bekend als

-eq

gelijk aan

=

-lt

kleiner dan

<

-gt

groter dan

>

-le

kleiner of gelijk aan

=<

-ge

groter of gelijk aan

=>

-like

lijkt op

& of *

Pagina 7 van 30

Geneste If

Windows: H10 - PowerShell

Switch

Loops Do until Do {actie} until (conditie) Expressies gescheiden door `;'

Do while Do {actie} while (conditie) Nieuwe expressie op nieuwe regel

For loops For (conditie){actie} Oneindige lus? Afbreken met Ctrl+C!

Foreach loop Foreach (item IN set){actie} Een set kan ook opgevraagd worden... Een array (@-teken)

Procedures en functies ? Procedure

o Afgescheiden blok code dat een duidelijk op zichzelf staand doel of gebruik heeft o Meestal niet als zodanig in een script aangeduid ? Functie o Met keywords aangeduid en duidelijk gedefinieerd o Blokken code die vaak meermaals worden uitgevoerd o Heeft duidelijk een kop en een staart

Functies ? Argumenten en return codes Function naam ($arg1, $arg2) {actie; return $output}

Pagina 8 van 30

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download