Blog   ❯   Author: Fabio MoschiniDate: 08.12.2022

PowerShell examples

alt text for image

PowerShell script examples

Version

To display the PowerShell version installed on the computer, you can use:
$PSVersionTable

Online help

The command:
Get-Help
provides information about commands (cmdlets) and their syntax.

Example:
Get-Help -Name Get-Process

Create a directory

Use the cmdlet:
New-Item -Path 'C:\path\to\newfoldername' -ItemType Directory
If you only specify the directory name, it will be created in the current directory.
The -ItemType option defines the type of object to create.
To create a file, you can use:
New-Item -Path 'C:\path\to\folder\newfilename' -ItemType File

Copy a directory

To copy a directory with all its content, use the cmdlet:
Copy-Item 'C:\path\to\sourcefolder' 'D:\path\to\destinationfolder' -Recurse
The copy can be between drives or within the same drive.

Remove a directory

To delete a directory with all its content, use:
Remove-Item 'C:\path\to\folder' -Recurse
If you omit -Recurse and the directory contains items, confirmation will be requested.

Move a directory

Use:
Move-Item 'C:path\to\folder' 'D:\another\path\to\folder'

Rename a directory

Use the cmdlet:
Rename-Item 'C:\path\to\folder' newfoldername

Check if a directory exists

Use:
Test-Path 'C:\path\to\foldertocheck'
Output will be true if the directory exists, otherwise false.

Create a file

Use New–Item as shown above to create files:
New-Item -Path 'C:\path\to\folder\newfilename' -ItemType File

Copy a file between directories

Use:
Copy-Item 'C:\path\to\sourcefolder\sourcefilename' 'D:\path\to\destinationfolder\destinationfilename'
If you omit the destination filename, the file keeps its original name.

Delete a file

Use:
Remove-Item 'C:\path\to\folder\filename'

Move a file

Use the same cmdlet as for directories:
Move-Item 'C:\path\to\sourcefolder\filename' 'D:\path\to\destinationfolder'
If you omit the destination filename, the file keeps its original name.

Rename a file

Use:
Rename-Item 'C:\path\to\folder\filename' newfilename

Check if a file exists

Use:
Test-Path 'C:\path\to\folder\filetocheck'
Output will be true if the file exists, orfalse if not.

Read file contents

Use:
Get-Content 'C:\path\to\folder\filename'

Show current date and time

Use:
Get-Date
By default the full format for date and time is displayed.
To display date and time in short format:
Get-Date -Format g
To display only the current date, use -DisplayHint Date:
Get-Date -DisplayHint Date
To display only the current time, use:
Get-Date -DisplayHint Time

Change system date/time

You can set the system date/time with:
Set-Date -date "31/12/2022 23:50"
To move system time back by 15 minutes:
Set-Date -Adjust -0:15:0 -DisplayHint Time

Create an XML file

We've already seen how to create a file with New–Item. To create an XML file specify the extension:
New-Item 'C:\path\to\folder\filename.xml' -ItemType File
To add content to the new file use Set-Content:
Set-Content 'C:\path\to\folder\filename.xml' '<title>This is the XML file content</title>'
To read the file content use:
Get-Content 'C:\path\to\folder\filename.xml'

Clear file contents

Use:
Clear-Content 'C:\path\to\folder\filename'

Append text to a file

Use:
Add-Content 'C:\path\to\folder\filename' "text appended to the file"

Variables

Variables in PowerShell start with $ followed by letters, numbers or _. To use special characters in a variable name, wrap the name in { and}. Example:
$variable $firstname_lastname ${variable-with-dash}
Assign values with =:
$variable = 3
You can assign multiple variables at once:
$variable = $value = $abc = 3
Also assign multiple values to a variable to create an array:
$list=1,12,134,55,78,100,55,12
Access an element by index:
$list[2]
The value will be 134. Sort and remove duplicates with:
$list | sort | get-unique
Get the count with:
$list.Count
Initialize a consecutive integer array with:
$list=4..10
To slice an array:
$sublist = $list[1..3]

Measurements

PowerShell provides Measure-Object for different measurements. Examples:
  • Count files and folders in the current directory:
Get-ChildItem | Measure-Object
  • Get minimum/maximum file size, sum and average:
Get-ChildItem | Measure-Object -Property length -Minimum -Maximum -Sum -Average
  • Count characters, words and lines in a text file:
Get-Content 'C:\path\to\folder\filename' | Measure-Object -Character -Word -Line

List directory contents

Use Get-ChildItem:
Get-ChildItem 'C:\path\to\folder'
Omitting the path lists the current directory:
Get-ChildItem
Filter by extension:
Get-ChildItem 'C:path o older' *.txt -Recurse -Force

Compare two text files

Use:
Compare-Object -ReferenceObject $(Get-Content 'C:\path\to\folder\firstfile.txt') -DifferenceObject $(Get-Content 'C:\path\to\folder\secondfile.txt')

Pause script execution

Use
Start-Sleep -m 2000
for milliseconds or
Start-Sleep -s 2
for seconds.

Aliases

Aliases are shortcuts for cmdlet names. For example create an alias for Get-Help:
New-Alias -Name Help -Value Get-Help
Aliases are valid only for the current session. Use Export-Aliasto save them and
Get-Alias
to list them.

PowerShell backtick

PowerShell supports escape sequences starting with the backtick `. Common sequences include:
SequenceDescription
`tHorizontal tab
`nNew line
`vVertical tab
`bBackspace
`eEscape
`0Null
`aAlert
`fForm feed
`rCarriage return
`u{x}Unicode escape sequence

Example:
Write-Host "This text appears on the first line `nSecond line`tTab example"
Output:
This text appears on the first line
Second line    Tab example

String operations: Split and Join

Split divides a string using a character or substring. In PowerShell use the -split operator.
For example split a sentence into words:
$string="This string processed with the -split operator" $array = $string -split ' ' $array
Output:
This
string
processed
with
the
-split

You can split using another substring:
$string="This string after being split" $array = $string -split 'st' $array
The output is:
Thi
s
ring after being
split

The opposite operation join merges strings. Example:
$array=("String"," obtained"," using"," -join") $string = -join$array $string
Output:
String obtained using -join