Part 11: Working with the Windows File System and Shell Using PowerShell

23 November 2023 22 minutes Author: Lady Liberty

PowerShell: Your Guide to the Windows File System

Working with the Windows file system and shell using PowerShell is a key skill for anyone working in IT and cybersecurity. PowerShell is a powerful command-line tool and scripting language developed by Microsoft that allows you to automate complex tasks and manage configurations. Using PowerShell to work with the file system includes creating, deleting, modifying files and directories, and searching and filtering data. This tool also allows you to perform complex operations on system resources, such as the Windows registry, startup and process and service management.

Knowledge of PowerShell is essential for understanding the inner workings of Windows, automating routine tasks, and improving work efficiency. In this article, we cover the basics of working with PowerShell, provide useful commands for working with the file system and the shell, and provide practical tips for using PowerShell in everyday work. In this article, you’ll find everything you need to work efficiently with the Windows file system and shell using PowerShell. We cover the basics of PowerShell, show you how to automate routine tasks, and share practical tips and useful commands. This information will help you improve your work efficiency and expand your Windows management skills.

Working with the file system and the Windows shell

All people who work with computers make many calls to the file system every day, reading and saving files, creating directories, copying files from one place to another, and so on.

REMARK. Remember to use file and directory extensions when working with the command line. You don’t need to type all the long paths – just type the first characters, press the <Ta> key, and the shell will substitute the appropriate filesystem path. Let’s consider the most common operations when working with files and directories.

File system navigation

In the cmd.exe and bash shell, you can navigate through directories using the cd command. In PowerShell, the cd command has the same meaning, but it is the default alias for the Set-Location cmdlet. For example, the following command makes the current directory C:\Windows:

PS С:\> cd C:\WINDOWS PS C:\WINDOWS>

As with the cmd.exe shell, you can specify .. (to jump to the parent directory) and \ (to jump to the root directory of the current drive). Example:

PS C:\WINDOWS> cd \
PS С:\>

Getting a list of files and directories

Recall that in the cmd.exe shell, the list of files and directories is formed using the internal dir command, which has many keys that allow, for example, to display only files with certain attributes, process nested subdirectories, sort the list by various fields, etc.

In PowerShell, you can also use the dir command, which here is an alias for the Get-Chi1dItem cmdlet. Running this command with no parameters will display the contents of the current directory:

Каталог: С:\
Mode LastWriteTime Length Name
d---- 03.03.2021 19:02 Far3x64
d---- 29.08.2020 22:01 Intel
d---- 13.05.2021 21:38 MRSU
d---- 07.12.2019 12:14 PerfLogs

Wildcards can be used in the path specified for the dir command. For example, the following command will output all log files from the C:\Windows directory:

PS С:\> dir C:\WINDOWSV.log
Каталог: C:\WINDOWS
Mode LastWriteTime Length Name
—a--- 28.09.2020 16:16 762 comsetup.log
-a--- 07.12.2019 12:17 776 Dtclnstall.log
-a--- 26.05.2021 3:20 63456 PFRO.log
-a--- 11.05.2021 22:03 623 setupact.log
-a--- 28.09.2020 16:13 0 setuperr.log
-a--- 04.06.2021 16:14 276 WindowsUpdate.log

The -Exc1ude option allows you to specify a mask of files that will not be processed by the dir command. For example, the following command will list all log files in the C:\Windows directory, except those whose names begin with the letter d:

PS С: \> dir С: \WINDCWS\* . log -exclude d* . log
Каталог: C:\WINDOWS
Mode LastWriteTime Length Name
-a--- 28.09.2020 16:16 762 comsetup.log
-a--- 26.05.2021 3:20 63456 PFRO.log
-a--- 11.05.2021 22:03 623 setupact.log
-a--- 28.09.2020 16:13 0 setuperr.log
-a--- 04.06.2021 16:14 276 WindowsUpdate

The -Name option allows you to display only file names, for example:

PS С:\> dir C:\WINDCWSV.log -Name comsеtup.log Dtclnstall.log PFRO.log setupact.log setuperr.log WindowsUpdate.log

The -Recurse option enables recursion mode, in which the dir command acts not only on the contents of the specified directory, but also on all its subdirectories:

PS С:\> dir .\Users\ -Recurse
Каталог: С:\Users
Mode LastWriteTime Length Name
d---- 31.05.2021 7:04 andrv
d-r- 28.09.2020 16:06 Public
Каталог : C:\Users\andrv
Mode LastWriteTime Length Name
d---- 15.02.2021 20:30 .config
d---- 10.10.2020 22:02 .dbus-keyrings
d---- 11.02.2021 16:12 .local

By default, the dir cmdlet does not “see” hidden files. If you want to include the following tayuke files in the list, you need to specify the -Force option:

Каталог: С:\
Mode LastWriteTime Length Name
d—hs- 01.10.2020 14:17 $Recycle.Bin
d—h— 28.09.2020 4:27 $WinREAgent
d—hsl 29.08.2020 21:52 Documents and Settings
d---- 03.03.2021 19:02 Far3x64
d---- 29.08.2020 22:01 Intel

Hidden files have the letter h (Hidden attribute) in the attribute list (Mode property). Sometimes it is necessary to form a list consisting of only subdirectories or only files. The -Directory and -File keys are used for this, respectively. Example:

PS С:\> dir 'C:\program files\Windows Defender\' -Directory
Каталог: C:\program filesWindows Defender
Mode LastWriteTime Length Name
d---- 20.12.2020 22:19 en-US
d---- 20.12.2020 22:19 Offline
d---- 28.09.2020 16:18 platform
d---- 12.05.2021 21:23 ru-RU
PS C:\> dir 'C:\program files\Windows Defender\' -File
Каталог: C:\program files\Windows Defender
Mode LastWriteTime Length Name
-a--- 07.12.2019 12:08 9398 AmMonitoringlnstall.mof
-a--- 23.01.2021 8:51 204624 AMMonitoringProvider.dll
-a--- 07.12.2019 12:08 21004 AmStatusInstall.mof
-a--- 07.12.2019 12:08 2460 ClientWMIInstall.mof
-a--- 07.12.2019 12:08 318776 ConfigSecurityPolicy.exe
-a--- 07.12.2019 12:08 210872 DefenderCSP.dll
-a--- 07.12.2019 12:08 733200 EppManifest.dll
-a--- 07.12.2019 12:08 361 FepUnregister.mof

The list of file system objects created by the directory can be sorted by any field using a pipeline with the Sort-Object cmdlet. For example, the following command will list all the files and directories on the C:\ drive, sorted in reverse order by the time they were accessed:

PS С:\> dir | Sort-Object -descending LastWriteTime
Каталог: C:\
Mode LastWriteTime Length Name
d---- 13.05.2021 21:38 MRSU
d---- 12.05.2021 21:23 Windows
d-r— 04.04.2021 11:19 Program Files (x86)
d---- 03.04.2021 21:39 sqlite
d---- 01.04.2021 19:17 projects
d---- 03.03.2021 T9: 02 Far3x64
d-r— 15.02.2021 22:15 Program Files
d---- 15.02.2021 16:09 Python39
d---- 11.02.2021 16:12 vifm
d---- 11.02.2021 16:10 Soft
d-r-- 01.10.2020 14:19 Users
d---- 29.08.2020 22:01 Intel
d---- 07.12.2019 12:14 PerfLogs

Determining the size of directories

Any file system directory in PowerShell corresponds to an object of type System. IO DirectoryInfo that does not have a property that stores the size of this directory. Therefore, to determine the size of a directory, you need to calculate the total size of the files written to this directory and all its subdirectories. You can do this by using the Measure-Obj cmdlet to sum the values of the Length property of the file objects passed by the dir (Get-Chi1dItem) cmdlet.

For example, the following command shows the size in bytes of the C:\Program Files directory (sun property) and the number of files and subdirectories in that directory (Count property):

PS С:\> dir "C:\Program Files" -Recurse | Measure-Object -Property length -Sum
Count
Average
Sum
Maximum
Minimum
Property
21539
2492086334
length

If you want to specify the size in megabytes or gigabytes, then the value of the sum property should be divided by the corresponding suffix constant (1Mb or 1Gb):

PS С:\> (dir "C:\Program Files" -Recurse | Measure-Object -Property length
-Sum) .Sum/1Mb
2376,63873100281

As you can see, the result contains decimal places. You can round the received number to two digits:

PS С:\> $FolderSize = (dir "C:\Program Files" -Recurse | Measure-Object
-Property length -Sum) .Sum/1Mb
PS C:\> [math]::round($FolderSize,2)
2376, 64

Creation of files and directories

You can create a new file or directory in PowerShell using the New Item cmdlet (abbreviated ni). The path to the item to be created is specified as the value of the -Path parameter, and the value of the -ItemType parameter is specified as “directory” if you want to create a directory and “fi1e” if you want to create a file.

For example, the following command creates a directory on the C:\ drive named Test:

PS С:\> New-Item -Path C:\Test -Type "directory”
Каталог: C:\
Mode LastWriteTime Length Name
d---- 04.06.2021 20:03 Test

Sometimes you need to create up-to-date catalogs in a certain format. The required text representation of the date can be obtained using the -ufornat option of the Get-Date cmdlet. For example, the following command will create a directory on drive C:\ with the same name as the current date in YYMMDD format:

PS С:\> New-Item -Path С:\ -Name "$ (Get-Date -uformat '%y%m%d')"
-Type ’’directory”
Каталог: C:\
Mode LastWriteTime Length Name
d---- 04.06.2021 22:30 210604

If four digits are required in the year number, the format specifier should be changed to ‘ %Y%m%d’:

PS С:\> New-Item -Path С:\ -Name ”$ (Get-Date -uformat ’%Y%m%d')"
-Type "directory"
Каталог: C:\
Mode LastWriteTime Length Name
d---- 04.06.2021 22:31 20210604

When creating a file, you can immediately write a line to it, specifying it as the value of the -value parameter, for example:

PS С:\> New-Item -Path C:\Test\test_file.txt -Type "file" -Value "Test"
Каталог: C:\Test
Mode
-a---
LastWriteTime Length Name
04.06.2021 22:34 4 test file.txt

Create multiple files

As the value of the -Path parameter, you can specify multiple files separated by commas, all of which will be created:

PS С:\Users\andrv> New-item -Path C:\Test\testl.txt, .\test2.txt, .\test3.txt
Каталог: С:\Test
Mode
-а---
LastWriteTime
12.06.2021 6:28
Length Name
0 testl.txt
Каталог: C:\Users\andrv
Mode
-a---
-a---
LastWriteTime
12.06.2021 6:28
12.06.2021 6:28
Length Name
0 test2.txt
0 test3.txt

Converting a file

If you try to create a file with the name of an existing file, you will get an error:

PS С:\> New-item -Path C:\Test\test_file.txt -Type "file” -Value "Test2"
new-item : Файл "C:\Test\test_file.txt" уже существует.
строка:1 знак:1
+ new-item -path C:\Test\test_file.txt -type "file" -value "Test2 ...
+ Categoryinfo : WriteError: (C:\Test\test_file.txt:String)
[New-item], IOException
+ FullyQualifiedErrorld : NewItemlOError,Microsoft.PowerShell.Commands.
Newl temCommand
Для перестворення існуючого файлу потрібно вказати параметр -Force:
PS С:\> New-item -Path C:\Test\test_file.txt -Type "file" -Value "Test2" -Force
Каталог: C:\Test
Mode
-a---
LastWriteTime Length Name
04.06.2021 22:37 5 test file.txt

Creating a file in a non-existent directory

The -Force option also helps when we need to create a file in a directory that doesn’t exist yet. By default, without this parameter, an error will occur in this case. For example, let’s try to create a file in the non-existent inner subdirectory:

PS С:\Users\andrv> New-item -Path C:\Test\inner\test_file.txt
New-item : He удалось найти часть пути "C:\Test\inner\test_file.txt".
строка:1 знак:1
+ New-Item -Path C:\Test\inner\test_file.txt
+ Categoryinfo : WriteError: (С:\Test\inner\test_file.txt:String)
[New-Item], DirectoryNotFoundException
4- FullyQualifiedErrorld : NewItemlOError,Microsoft.PowerShell.Commands.
NewItemCommand
Якщо вказати параметр -Force, підкаталог inner буде створений автоматично:
PS С:\Users\andrv> New-Item -Path C:\Test\inner\test_file.txt -Force
Каталог: С:\Test\inner
Mode
-а---
LastWriteTime
12.06.2021 6:34
Length Name
0 test file.txt

Reading the contents of files

In the cmd.exe shell, there is a type command that displays the contents of a text file on the screen. In PowerShell, the type command is an alias for the GetContent cmdlet (also known as cat and dc), which is designed to read the contents of a text file line by line, returning an object for each line (with the lines displayed on the screen). Example:

PS С:\> Get-Content C:\WINDCWS\win.ini
; for 16-bit арр support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1
CMCDLLNAME32=mapi32.dll
CMC=1
MAPIX=1
MAPIXVER=1.0.0.1
OLEMessaging=l

The -Encoding option of the Get-Content cmdlet allows you to explicitly specify the encoding of a file so that its contents are processed correctly. Valid values for this parameter are: Unicode, Byte, BigEndianUnicode, UTF8, UTF7, Ascii.

By default, the Get-Content cmdlet reads all lines from a file; you can limit their number using the -Tota1Count option. For example, the following command reads the first five lines from the C:\WINDOWS\win.ini file:

PS С:\> Get-Content C:\WINDOWS\win.ini -TotalCount 5
; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]

You can store the result of the Get-Content cmdlet in a variable and call it an array of strings, for example:

PS С:\> $f = Get-Content C:\WINDOWS\win.ini -TotalCount 5
PS C:\> $f.Length
5
PS C:\> $f[0]
; for 16-bit app support
PS C:\> $f[l]
[fonts]

Of course, the returned array of strings can be passed directly to be processed by other cmdlets, for example, to be converted and written to another file (see the next section for an example). The -Raw option allows you to read the entire contents of a file into one line, for example:

PS С:\Users\andrv> $s = Get-Content C:\WINDCWS\win.ini -Raw
PS C:\Users\andrv> $s
; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1
CMCDLLNAME32=mapi32.dll
CMC-1
MAPIX=1
MAPIXVER=1.0.0.1
OLEMessaging=l
PS C:\Users\andrv> $s.Length
167

Copying files and directories

In PowerShell, copying files and directories is done by the Soru Item cmdlet, which has the alias Soru. In this case, the path to the copied files is specified as the value of the -Path parameter (this parameter is used by default), and the path to the destination directory to which the files should be copied is specified by the value of the -Destination parameter.

For example, the following command copies the win.ini file from the C:\Windows directory to the C:\Test directory:

PS С:\Users\andrv> New-Item С:\Script\l.psi, C:\Script.psl, C:\Script\
3.txt -Force
Mode LastWriteTime Length Name
-а--- 11.06.2021 23:23 0 l.psl
-а--- 11.06.2021 23:23 0 2.psi
-а--- 11.06.2021 23:23 0 3.txt

Now copy the C:\Script directory to C:\Test:

PS С:\Users\andrv> сору C:\Script -Destination C:\Test -PassThru
Каталог: C:\Test
Mode LastWriteTime Length Name
d----- 11.06.2021 23:25 Script

As you can see, only the directory without the files in it was copied.

Copying nested directories

The -Recurse option allows you to copy the contents of nested directories, for example:

PS С:\Users\andrv> copy C:\Script -Destination C:\Test -Recurse -PassThru
Каталог: C:\Test\Script
Mode LastWriteTime Length Name
-а--- 11.06.2021 23:25 0 l.psl
-а--- 11.06.2021 23:25 0 2.psi
-а--- 11.06.2021 23:25 0 3.txt

Copying files using a mask

You can copy not all files from the directory, but only those that correspond to a particular mask. In this case, the mask can be specified inside the path to be copied, or as the value of the -Inc1ude parameter. For example, the following command copies all files with the psl extension from the C:\Script directory to the C:\Test folder:

PS С:\Users\andrv> сору С:\Script\*.psi -Destination C:\Test -PassThru
Каталог: C:\Test
Mode LastWriteTime Length Name
-a--- 11.06.2021 23:25
-a--- 11.06.2021 23:25
0 l.psl
0 2.psi

However, if you want to mask files from all nested subdirectories, you won’t be able to use a single Copy Item cmdlet. Prerequisite files must be marked with the Get-Chi1dItem (dir) cmdlet and then passed to the Copy Item cmdlet.

For example, let’s create two files in the Posh and Misc subdirectories:

PS С:\Users\andrv> New-Item C:\Script\Posh.ps!, C:\Script\Misc.ps! -Force
Каталог: C:\Script\Posh
Mode
-a---
LastWriteTime
12.06.2021 6:39
Length Name
0 4.psi
Каталог: C:\Script\Misc
Mode LastWriteTime Length Name
-a--- 12.06.2021 6:39 0 5.psi

The following command copies all files with the psl extension from the C:\Script directory and all its subdirectories to the C:\Test folder:

PS С:\Users\andrv> dir -Recurse -Include *.psl C:\script\* |
copy -Destination C:\Test -PassThru
Каталог: C:\Test
Mode LastWriteTime Length Name
-а--- 12.06.2021 6:39 0 5.psi
-а--- 12.06.2021 6:39 0 4.psi
-а--- 11.06.2021 23:20 0 l.psl
-а--- 11.06.2021 23:20 0 2.psi

Concatenation of files

The command cmd.exe shell soru allowed to combine several files together (file concatenation). In PowerShell, you can merge files by using the Get-Content (alias type) cmdlet and redirecting the output to the resulting file. Let’s consider an example. Let’s create the files C:\Test\l .txt and C:\Test\2.txt:

PS С:\Users\andrv> New-Item -Path C:\Test\l.txt -Type "file" -Value "File 1"
Каталог: C:\Test
Mode
-a---
LastWriteTime
12.06.2021 6:56
Length Name
6 l.txt
PS C:\Users\andrv> New-Item -Path C:\Test.txt -Type "file" -Value "File 2"
Каталог: C:\Test
Mode
-a---
LastWriteTime
12.06.2021 6:56
Length Name
6 2.txt
Наступна команда поєднує файли l.txt и 2.txt в файл 3.txt:
PS С:\Users\andrv> type C:\Test\l.txt, C:\Test.txt > C:\Test.txt
Проверим содержимое файла 3.txt:
PS С:\Users\andrv> type C:\Test.txt
File 1
File 2

As you can see, the merging of files 1.txt and 2.txt was successful.

Renaming and moving files and directories

You can rename a file or directory using the Rename-Item (alias ren) cmdlet. The value of the -Path parameter of this cmdlet specifies the path to the elements to be renamed, and the value of the -NewName parameter specifies the new name. The names of these parameters can be omitted (in this case, the value of the -Path parameter must be specified first). For example, let’s create a .tmp file and rename it to 2.tmp file:

PS С:\Users\andrv> New-item -Path C:\Test\l.tnq?
Каталог: C:\Test
Mode
-a---
LastWriteTime
12.06.2021 7:01
Length Name
0 1. tmp
PS C:\Users\andrv> ren C:\Test\l.tmp 2.tmp

To see the result of the Rename-Item cmdlet, you need to specify the -PassThru option:

PS С:\Users\andrv> ren C:\Test.tinp 3.tmp -PassThru
Каталог: C:\Test
Mode
-a---
LastWriteTime
12.06.2021 7:01
Length Name
0 3.tmp

Moving files

The Renane-Item cmdlet allows you to rename files or directories only in the directory where the original object was located. If you need to move a file or directory to a different folder, use the Rename (alias rename) cmdlet. The value of the -Path parameter of this cmdlet specifies the path of the files or directories to be moved (wildcards are allowed in this path), and the value of the -Destination parameter specifies the path of the directory where the files or directories will be moved.

The result of the move can be seen on the screen by specifying the -PassThru option. For example, the following command moves the C:\Test\inner directory with all its contents to the root directory of the C:\ drive:

PS С:\Users\andrv> Move-Item -Path C:\Test\inner С:\ -PassThru
Каталог: С:\
Mode LastWriteTime Length Name
d---- 12.06.2021 6:34 inner

Let’s put the inner directory back in place:

PS C:\Users\andrv> Move-Item -Path C:\inner C:\Test -PassThru
Каталог: C:\Test
Mode LastWriteTime Length Name
d---- 12.06.2021 6:34 inner

Deleting files and directories

You can remove file system objects using the remove-item cmdlet (alias de1). The value of the -Path parameter of the cmdlet specifies the path to the files or directories to be deleted (the name of the parameter in the command does not need to be specified). Wildcards are allowed in the path, and the Exclude-Item cmdlet has a -Inc1ude option that specifies the files that will be affected by the command, and an -Exc1ude option that specifies exception files that will not be removed.

For example, the following command will delete all files with a .psl extension in the C:\Test directory:

PS С:\> del С:\Test\*.psi

If you try to delete all files in a directory that contains subdirectories, the system will issue a warning:

PS С:\Users\andrv> del C:\Test\*

To delete all items in a directory without warning, including subdirectories, specify the -Recurse option:

PS С:\> del C:\Test\* -Recurse

Search for text in files

In principle, to find text in a file, you can read its contents into an array of strings using the Get-Content cmdlet and apply one of the comparison operators to it. However, PowerShell has a cmdlet called Se1ectString that is specifically designed to find strings of text in one or more files (similar to the console utility findstr on Windows and grep on UNIX).

For example, the following command searches for the word “Error” in all log files in the Windows system directory (the -Pattern and -Path parameter names can be omitted, remembering that the search pattern must come first after the cmdlet name):

PS С:\Users\andrv> Select-String -Pattern Error -Path $env:windir\*.log
C:\WINDOWS\DtcInstall.log:1:12-07-2019 09:17 : DTC Install error = 0,
Enter MsDtcAdvancedlnstaller::Configure, base\wcp
\plugins\msdtc\msdtcadvancedinstaller\msdtcadvancedinstaller.cpp (367)
C:\WINDOWS\DtcInstall.log:2:12-07-2019 09:17 : DTC Install error = 0,
Action: None, base\wcp\plugins\msdtc\msdtcadvance
dinstaller\msdtcadvancedinstaller.cpp (396)

As you can see, by default it displays the path to the file being checked, the line number in which the match was found, and the line itself. line. Basically, the search result is an object of type Microsoft. PowerShe11. . MatchInfo, which contains the following properties: Path (file path), Pattern (pattern search), LineNumber (number of the line found in the file), Line (content of the line found) and others:

PS С:\Users\andrv> Select-String Error $env:windir\*.log | Format-List *
IgnoreCase : True
LineNumber : 1
Line : 12-07-2019 09:17 : DTC Install error = 0, Enter
MsDtcAdvancedlnstaller::Configure, base\wcp\plugins\msdtc\
msdtcadvancedinstaller\msdtcadvancedinstaller.cpp (367)
Filename : Dtclnstall.log
Path : C:\WINDOWS\DtcInstall.log
Pattern : Error
Context :
Matches : {0}
IgnoreCase : True
LineNumber : 2
Line
Filename
Path
Pattern
Context
Matches
: <12-07-2019 09:17 : DTC Install error = 0, Action: None,
base\wcp\plugins\msdtc\msdtcadvancedinstaller\msdt
cadvancedinstaller.cpp (396)
: Dtclnstall.log
: C:\WINDOWS\DtcInstall.log
: Error
: {0}

Replacing text in files

Recall that text in lines is replaced by the -rep1ace operator, which supports regular expressions (see Chapter 8). Therefore, to replace text in a file, you can read its contents into an array of strings using the Get-Content cmdlet, process the required strings with the -rep1ace operator, and save the result to the same or a different file using the Set-Content cmdlet.

Let’s consider a simple example. Let’s create a file C:\Test\test.txt from three lines:

PS С:\> "11111", "2222", "33333" > C:\Test\test.txt
PS С:\> type C:\Test\test.txt
11111
2222
33333

Now let’s replace all the “1” characters in this file with “a”:

PS С:\> (Get-Content C:\Test\test.txt) | ForEach-Object {$_ -replace "1”, "а”} |
Set-Content С:\Test\test.txt

The first command in the pipeline is used here in parentheses so that the SetContent cmdlet doesn’t start working until the Get-Content cmdlet has read the file completely (otherwise you might encounter an error when accessing the file C:\Test\test.txt at the same time while reading and recording). We make sure that the replacement was successful:

PS С:\> type C:\Test\test.txt
ааааа
2222
33333

Working with Jarl files

Shortcuts in Windows are a special type of files that have the extension .lnk or url and serve as pointers to other objects (files, directories, web resources, applications, commands). PowerShell does not have a separate built-in cmdlet for working with shortcuts, but you can create a shortcut using the external methods of COM objects available in the operating system.

Create a desktop shortcut

For example, we will create a PSHome.lnk shortcut on the desktop of the active user for the folder where the PowerShell shell is installed. The first task is to determine the path to the desktop of the current user. To do this, we will use the SpecialFolders collection, storing a reference to it in the $folders variable:

PS С:\> $folders = $shell.SpecialFolders
PS C:\> $folders
C:\Users\Public\Desktop
C:\ProgramData\Microsoft\Windows\Start Menu
C:\ProgramData\Microsoft\Windows\Start Menu\Programs
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
C:\Users\andrv
PS С:\> $folders = $shell.SpecialFolders
PS C:\> $folders
C:\Users\Public\Desktop
C:\ProgramData\Microsoft\Windows\Start Menu
C:\ProgramData\Microsoft\Windows\Start Menu\Programs
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
C:\Users\andrv\0neDrive\Pa6o4wn стол
C:\Users\andrv\AppData\Roaming
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Templates
C:\Windows\Fonts
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Network Shortcuts
C:\Users\andrv\0neDrive\Pa6o4wn стол
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Start Menu
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\SendTo
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Recent
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
C:\Users\andrv\Favorites
C:\Users\andrv\OneDrive\Documents
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
neDrive\Pa6o4wn стол C:\Users\andrv\AppData\Roaming C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Printer Shortcuts C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Templates C:\Windows\Fonts C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Network Shortcuts C:\Users\andrv
PS С:\> $folders = $shell.SpecialFolders
PS C:\> $folders
C:\Users\Public\Desktop
C:\ProgramData\Microsoft\Windows\Start Menu
C:\ProgramData\Microsoft\Windows\Start Menu\Programs
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
C:\Users\andrv\0neDrive\Pa6o4wn стол
C:\Users\andrv\AppData\Roaming
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Templates
C:\Windows\Fonts
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Network Shortcuts
C:\Users\andrv\0neDrive\Pa6o4wn стол
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Start Menu
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\SendTo
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Recent
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
C:\Users\andrv\Favorites
C:\Users\andrv\OneDrive\Documents
C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
neDrive\Pa6o4wn стол C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Start Menu C:\Users\andrv\AppData\Roaming\Microsoft\Windows\SendTo C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Recent C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup C:\Users\andrv\Favorites C:\Users\andrv\OneDrive\Documents C:\Users\andrv\AppData\Roaming\Microsoft\Windows\Start Menu\Programs

We save the path to the user’s desktop in the $desktop variable:

PS С:\> $desktop = $folders.Item('desktop')
PS C:\> $desktop
C:\Users\andrv
PS С:\> $desktop = $folders.Item('desktop')
PS C:\> $desktop
C:\Users\andrv\0neDrive\Pa6o4Mn стол
neDrive\Pa6o4Mn стол

To create a shortcut on the desktop, call the Createshortcut method, passing it the path to the shortcut (recall that inside the line in double quotes, the name of the variable is replaced by its value):

PS С:\> $lnk = $shell.CreateShortcut("$desktop\PSHome.lnk")
PS C:\> $lnk = $Shell.Createshortcut("$Home\Рабочий стол\PSHome.Ink")

Let’s see what properties and methods the object stored in the $ink variable has:

PS С:\> $lnk | Get-Member
TypeName: System.__ComObject#{f935dc23-lcf0-lld0-adb9-00c04fd58a0b}
Name MemberType Definition
Load Method
Save Method
Arguments Property
Description Property
FullName Property
Hotkey Property
IconLocation Property
RelativePath Property
TargetPath Property
Windowstyle Property
WorkingDirectory Property
void Load (string)
void Save ()
string Arguments () {get} {set}
string Description () {get} {set}
string FullName () {get}
string Hotkey () {get} {set}
string IconLocation () {get} {set}
string RelativePath () {set}
string TargetPath () {get} {set}
int Windowstyle () {get} {set}
string WorkingDirectory () {get} {set}

To create a shortcut for a folder, simply store the folder path in the TargetPath property and call the Save method to save the shortcut. The path to the PowerShell home folder is stored in the special $PSHome variable, so run the following commands:

PS С:\> $Ink.TargetPath = $₽SHome
PS C:\> $Ink. Save ()

The problem is solved, and a shortcut to the desktop of the active user is created.

Removing incorrect shortcuts

Shortcuts (files with the Ink extension) are an important part of the Windows graphical interface. However, if the object referenced by the shortcut is deleted or moved, the corresponding shortcut becomes useless. Let’s break down the commands that can be used to find and remove such incorrect shortcuts on the desktop. As in the previous section, let’s create an instance of the wscript class. shell (variable $sheii):

PS С:\> $shell = New-Object -ComObject WScript.Shell

Let’s put the path to the active user’s desktop in the $desktop variable:

PS С:\> $folders = $shell.SpecialFolders
PS C:\> $desktop = $folders.Item ("desktop")

Now, using the dir (Get-Chi1dItem) and ForEach-Object cmdlet pipeline, we go through all the files on the desktop with the lnk extension. For each such file, we’ll use the CreateShortcut method to create the corresponding shortcut object and use the Test-Path cmdlet to verify the existence of the object referenced by this shortcut (the path to this object is stored in the TargetPath property of the shortcut object ). If the object does not exist (the Test-Path cmdlet returns Fa1se), the file being tested with the lnk extension is deleted:

PS С:\> dir "$desktop\*.Ink" | ForEach-Object{
>> $shortcut = $shell. CreateShortcut ($_.FullName) ;
» if (-not (Test-Path $shortcut.TargetPath)) (del $_. FullName};
» }
»

Results

  • PowerShell has cmdlets to perform standard operations on files and directories.

  • You can use the COM object wscript.shell to create shortcut files and manage them. The New Object cmdlet with the ComObject parameter allows you to work with COM objects.

Thanks to our team of volunteers for providing information from open sources.

Other related articles
Found an error?
If you find an error, take a screenshot and send it to the bot.