Как найти файл и проверить, существует он с помощью powershell или netwrix auditor

In this post, our focus will be on demonstrating how “Get-ChildItem” can selectively list either files or directories. This feature is invaluable for specific file system operations, including system audits, organizing data, or processing multiple files simultaneously.

We’ll cover the cmdlet’s parameters that allow you to refine your listings to either files or directories. Through practical examples, we’ll illustrate how these functions can be applied effectively in various scenarios.

If you’re interested in our structured training and taking your PowerShell skills to the next level, then check out our full PowerShell course:

Course: Administration and Automation with Windows PowerShell

Get-ChildItem Cmdlet

Key Features:

  • Listing Items: At its core, “Get-ChildItem” provides a detailed list of all items in a given directory. This includes files, subdirectories, and hidden items.
  • Path Specification: You can specify the path where you want to list the items. If no path is given, it defaults to the current directory.
  • Filtering Capabilities: One of the cmdlet’s strengths is its ability to filter results. You can use parameters to list only files, only directories, or items that match certain criteria.
ArgumentDescription
-Path <String[]>Specifies the path(s) where the cmdlet should search for items. If omitted, it defaults to the current directory. Multiple paths can be provided, separated by commas.
-Filter <String>Filters items based on a provided search string. For example, -Filter "*.txt" will list all text files.
-Include <String[]>Lists items that match the specified names or paths, used in conjunction with -Path. E.g., -Include "*.txt" will list text files in the specified path.
-Exclude <String[]>Excludes specified items from the results. For instance, -Exclude "*.log" omits log files from the listing.
-RecurseSearches items in all child directories of the specified path(s), not just in the immediate directory.
-ForceShows hidden and system items, which are not displayed by default.
-NameReturns only the names of the items, excluding other details like the full path.
-Attributes <FileAttributes>Filters files based on specified attributes, such as ReadOnly, Hidden, etc. -Attributes Hidden lists only hidden files.
-DirectoryLists only directories, excluding files.
-FileLists only files, excluding directories.
-HiddenIncludes hidden items in the output, which are usually not listed by default.
PowerShell Get-ChildItem Arguments

You can use these arguments (pick and chose what you need) to fit whatever problem you’re trying to solve. You can output this same table in PowerShell by using the Get-Help Get-ChildItem cmdlet.

Get-ChildItem Examples

In this section, we’ll explore ten of the most common and practical examples of using the Get-ChildItem cmdlet. These examples will demonstrate the versatility and power of this cmdlet in various scenarios.

1. Listing All Files and Folders in a Directory

This basic command lists all files and folders in the specified directory:

Get-ChildItem -Path "C:\YourDirectory"

2. Recursively Listing All Files in a Directory and Subdirectories

Use the -Recurse parameter to include all subdirectories:

Get-ChildItem -Path "C:\YourDirectory" -Recurse

3. Finding Files with a Specific Extension

This command lists all .txt files in the given directory:

Get-ChildItem -Path "C:\YourDirectory" -Filter "*.txt"

4. Listing Only Directories

The -Directory parameter restricts the output to directories only:

Get-ChildItem -Path "C:\YourDirectory" -Directory

5. Listing Only Files

Conversely, the -File parameter lists only files, excluding directories:

Get-ChildItem -Path "C:\YourDirectory" -File

6. Excluding Specific Items

This example excludes all .log files from the listing:

Get-ChildItem -Path "C:\YourDirectory" -Exclude "*.log"

7. Listing Hidden Files

To see hidden files in the directory, use the -Hidden parameter:

Get-ChildItem -Path "C:\YourDirectory" -Hidden

8. Finding Large Files in a Directory

This command finds files larger than 50MB:

Get-ChildItem -Path "C:\YourDirectory" -Recurse | Where-Object { $_.Length -gt 50MB }

9. Listing Files Modified Before a Certain Date

Find files last modified more than 30 days ago:

Get-ChildItem -Path "C:\YourDirectory" | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) }

10. Listing Files and Directories with Specific Attributes

This example lists all read-only files and directories:

Get-ChildItem -Path "C:\YourDirectory" -Attributes ReadOnly

Each of these examples showcases a different aspect of the Get-ChildItem cmdlet, making it an indispensable tool for file system navigation and management in PowerShell.

Conclusion

In wrapping up our discussion on the Get-ChildItem cmdlet in PowerShell, it’s evident that this tool is a vital component for efficient file and system management. Throughout this guide, we’ve covered a range of functionalities, from basic file listing to advanced usage for specific scenarios like registry and certificate management.

Key Points

  • Versatility: Get-ChildItem goes beyond simple file listing, offering extensive capabilities for various administrative tasks.
  • Customization: The cmdlet’s diverse parameters and compatibility with other PowerShell commands allow for highly specific and useful queries.
  • Cross-Platform Functionality: With PowerShell Core, Get-ChildItem is useful across different operating systems, though there are some platform-specific considerations.

You can do crazy things in PowerShell, one of which is to get file names only. In this article, I will show you how to list file names only in PowerShell.

To list file names only in PowerShell, you can use the Get-ChildItem cmdlet combined with the -Name parameter. For example, Get-ChildItem -Path “C:\Your\Directory” -Name outputs all the file names in the specified directory. To exclude directories and list only files, append the -File parameter, like so: Get-ChildItem -Path “C:\Your\Directory” -File -Name.

Get File Names Only Using Get-ChildItem Cmdlet

Let us try the most simplest approach.

The primary command for listing files in PowerShell is Get-ChildItem. This cmdlet retrieves the items and child items in one or more specified locations. To list file names only, you can use this cmdlet in its simplest form.

Get-ChildItem -Path "C:\MyFolder" -Name

The -Path parameter specifies the directory, and the -Name parameter ensures that only the names of the files are displayed, excluding other details like size, type, or modification date.

You can see in the screenshot below that I executed the script using VS code.

Get File Names Only Using Get-ChildItem Cmdlet

Filter Out Directories

By default, Get-ChildItem lists both files and directories in PowerShell. If you want to list only files, you can filter out the directories using the -File parameter.

Get-ChildItem -Path "C:\MyFolder" -File -Name

This command will return a list of file names without their extensions, and it will ignore only the folder names.

Get File Names Excluding File Extensions

If you want to list the files but exclude their extensions, you can use a combination of Get-ChildItem and ForEach-Object cmdlets in PowerShell.

Get-ChildItem -Path "C:\MyFolder" -File | ForEach-Object { $_.BaseName }

This script lists the base names (file names without extensions) of all the files in the specified directory.

Get File Names Excluding File Extensions in PowerShell

Get File Names Only Recursively

To list files in the specified directory and all subdirectories, use the -Recurse parameter in the PowerShell Get-ChildItem cmdlets.

Get-ChildItem -Path "C:\MyFolder" -Recurse -File -Name

This command will list all file names, including those in all levels of subdirectories under the target directory.

:/>  «Изменение размера шрифта для устройств Nokia по сравнению с изменением общего масштаба шрифта приложения на Android с использованием Configuration.fontScale»?

Advanced Filtering with Where-Object

Here is the complete PowerShell script.

Get-ChildItem -Path "C:\MyFolder" -File | Where-Object { $_.Name -like '*myfile*' } | ForEach-Object { $_.Name }

Conclusion

The simplest way you can use the Get-ChildItem PowerShell Cmdlet.

Netwrix Auditor for Windows File Servers

  1. Open the PowerShell ISE.
  2. Run a script like the following, which will return all files in the Accounting folder whose filename includes the string “payroll”:

The results will show all matching files.

Как найти файл и проверить, существует он с помощью powershell или netwrix auditor
  • Using Get-Item to check if a file exists — You can use the Get-Item cmdlet in PowerShell to find a file by name. If the specified item path does not exist, the script will throw an error. Below is a PowerShell script that checks whether the file “Payroll 2022 – 2023.xlsx” exists using the Get-Item cmdlet. If the file exists, the script provides the file details; if not, it will display a message saying the file does not exist.

    Write-Host”The file exists. Details:”

    Write-Host”The file does not exist.”

Как найти файл и проверить, существует он с помощью powershell или netwrix auditor
  • Using Get-ChildItem to check if a file exists — The Get-ChildItem cmdlet is typically used to retrieve a list of items in a specified location, but it can also be used to check for the existence of a specific file. The script below attempts to retrieve the file “Payment_2021.rtf”. If the file exists, the script will return the file details and a success message; otherwise, no output will be returned by Get-ChildItem and the write host cmdlet will display the message “The file does not exist.”

    Write-Host”The file exists.”

    Write-Host”The file does not exist.”

Как найти файл и проверить, существует он с помощью powershell или netwrix auditor
  • Using Test-Path to check if a file exists — You can use the Test-Path cmdlet to check whether a specific file or folder exists. It returns True if the file or folder exists and False if it does not. For example, to check whether the “Payroll 2022 – 2023” file exists, run the following script:
Как найти файл и проверить, существует он с помощью powershell или netwrix auditor

You can also use Test-Path to check whether a path is a file or a directory. Add the ‑PathType with “leaf” as its value, and the cmdlet will return “true” if the path is a file.

Test-path -Path “C:\Temp\Temp*” -pathtype leaf

Test-Path -Path “\\FileServer\Backup”

  1. Run Netwrix Auditor → Navigate to Reports → Open User Behavior and Blind Spot Analysis → Go to Information Disclosure → Select File Names Containing Sensitive Data → Click View.
  2. Specify the following filters and parameters:
  3. Object UNC Path — Specify the path to your file share
  4. Disallowed Words — Specify the string you want to search for in filenames
  5. Click View Report.
Как найти файл и проверить, существует он с помощью powershell или netwrix auditor

Find Your Sensitive Files — and Get Critical Details about Them, Too

To maintain security and compliance, IT pros need to regularly search for files that might contain sensitive data and move them to a secure location. You can find and move files manually using Windows Explorer, but this method takes a lot of time so it is useful mainly when you need to secure a single file. To check multiple files more efficiently, you can use PowerShell. However, a PowerShell script for moving files will terminate with an error if the path is invalid, so before you run it, you need to meticulously check whether the files and folders exist, as shown in the examples above.

I’m trying to iterate on an existing powershell script I have. The script I have requires all files I’m parsing through to be in the same folder. The issue, is the files are originally in different folders by machine name, and then nested in another folder from there.
For example: /parent/hostname001/result/hostname001.xml , /parent/hostname002/result/hostname002.xml , etc.

What would be the most efficient way to do this- basically a “cp /parent//result/.xml /outputdirectory/” type function, to explain simply.
Appreciate the help!

Attempted a few things – using https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item?view=powershell-7.4 seemed like the best shot but I was getting an error when trying to use wildcards. I’m not at work at the moment so unfortunately don’t have specifics.

Julian Delphiki's user avatar

You can use wildcards in a Get-ChildItem search for files, so something like this:

Get-ChildItem -Path ".\Parent\*\result\*.xml" | Copy-Item -Destination .\OutputDirectory

That would get all XML files in the result folder for each host, but you could filter that in a Where-Object if needed.

Get-ChildItem -Path ".\Parent\*\result\*.xml" | Where-Object {$_.basename -eq $_.Directory.Parent.Name} | Copy-Item -Destination .\OutputDirectory

That would make sure the file name (excluding extension) would be the same as the folder 2 levels up.

TheMadTechnician's user avatar

3 gold badges45 silver badges59 bronze badges

With the rise of configuration files in various applications, understanding the ins and outs of INI files can elevate your productivity as a developer or software enthusiast. Despite their roots in the 16-bit Microsoft Windows platforms, INI files remain a crucial part of application configurations.

But, when it comes to handling INI files with PowerShell things can be a bit tricky. PowerShell, even though it’s a great tool, doesn’t have ready-made commands to work with these files. But don’t worry, we’re here to help!

In this article, we’ll show you how you can use PowerShell to read INI files and turn their content into a format that’s easy to use.

How to read INI files with PowerShell

You can read INI files with PowerShell using the Get-Content cmdlet:

Get-Content cmdlet to read INI files with PowerShell

However, there is a difference between reading the file content and transforming the file content into a usable format under a hash table. Let’s go into that.

Converting INI files into PowerShell hash tables

Microsoft offers a PowerShell cmdlet, ConvertFrom-StringData, which converts a string with key-value pairs into a hash table.

ConvertFrom-StringData PowerShell cmdlet

The sections return an error!

The cmdlet doesn’t capture the INI file structure accurately, as it expects a name=value format.

It ignores any characters where the # character is the first non-whitespace character, making it unsuitable for files with sections and comments or when there are duplicate element names in different sections.

For simpler INI files with no sections or comments, this will work perfectly:

ConvertFrom-StringData for Simple INI file

But if your INI file is more complex, we’ve got you covered.

Inspired by a script developed by Doctor Scripto in the Microsoft devblogs, we present an improved method for reading all types of INI files. We leverage regular expressions (regex) to determine whether a line is a comment, section, or key.

Here’s the magical function:

function Get-IniContent ($filePath)
{
	$ini = @{}
	switch -regex -file $FilePath
	{
    	“^\[(.+)\]” # Section
    	{
        	$section = $matches[1]
        	$ini[$section] = @{}
        	$CommentCount = 0
    	}
    	“^(;.*)$” # Comment
    	{
        	$value = $matches[1]
        	$CommentCount = $CommentCount + 1
        	$name = “Comment” + $CommentCount
        	$ini[$section][$name] = $value
    	}
    	“(.+?)\s*=(.*)” # Key
    	{
        	$name,$value = $matches[1..2]
        	$ini[$section][$name] = $value
    	}
	}
	return $ini
}

To call this function, store the output in a variable and then call the elements in the hash table as shown:

function Get-IniContent ($filePath)
{
	$ini = @{}
	switch -regex -file $FilePath
	{
    	“^\[(.+)\]” # Section
    	{
        	$section = $matches[1]
        	$ini[$section] = @{}
        	$CommentCount = 0
    	}
    	“^(;.*)$” # Comment
    	{
        	$value = $matches[1]
        	$CommentCount = $CommentCount + 1
        	$name = “Comment” + $CommentCount
        	$ini[$section][$name] = $value
    	}
    	“(.+?)\s*=(.*)” # Key
    	{
        	$name,$value = $matches[1..2]
        	$ini[$section][$name] = $value
    	}
	}
	return $ini
}
$test = Get-IniContent "C:\Users\User\Desktop\test.ini"
write-host $test.owner.name
write-host $test.database.port
PowerShell script to read all INI files

How to Read INI files with MSI

Microsoft’s built-in INI table for the MSI databases provides an alternative way to manage INI files.

:/>  Файлы - cmd. Работа с файлами из консоли. Часть 2.

And, with tools like Advanced Installer, reading and modifying INI files becomes even easier.

Here’s how you can use Advanced Installer to import the test INI file that we used to try our PowerShell scripts:

  1. Open Advanced Installer
  2. Create a project
  3. Navigate to the Files and Folders page.
  4. From the Add section in the top menu, select Import Files > Import INI (Advanced) and select the INI file.
Import INI files in Advanced Installer

As you can see, Advanced Installer reads the INI file and adds it to the INIFile table. From here, you can easily manipulate the INIFile table by using:

  • dehardcoding,
  • Properties,
  • Custom Actions.

Excited about your new INI file skills? Try Advanced Installer’s 30-day free trial now and put them into play!

Conclusion

Even though INI files have been with us for a long time, they present certain hurdles when it comes to reading and modifying them with PowerShell. But as we’ve demonstrated, there are handy workarounds that make the process less stressful and more efficient. We hope this guide offers a valuable resource in your journey of mastering INI files with PowerShell.

Ensure to bookmark this page for future reference, and do not hesitate to leave a comment if you have any queries or suggestions.

See author's page

Alex Marin

Application Packaging and SCCM Deployments specialist, solutions finder, Technical Writer at Advanced Installer.

In PowerShell, there are a couple of ways to create a file. The most common method is to use the new-item cmdlet. This cmdlet can not only be used to create files but also folders. But new-item is not always the best option.

Other options to create a file in PowerShell are for example to redirect the results of a cmdlet to a file, or we can use the Set-Content to create a file and store the results.

In this article, we will look at the different options, and I will give you some tips on creating files.

Let’s start with the basics, to create a new file in PowerShell we are going to use the cmdlet New-Item. This cmdlet can be used to create files, folders, or symbolic links. We will focus on creating a file in this article.

To create an empty file we will at least specify the name of the file and set the -ItemType property to file. If you don’t specify the path where you want to create the file, then the file will be created in the current directory.

New-Item -Name "test01.txt" -ItemType File

# Create a file in c:\temp
New-Item -Path "c:\temp" -Name "test01.txt" -ItemType File

The path parameter also accepts wildcards. Now you might think, why would I need a wildcard in the path, but this allows you for example to create a new file in every subfolder of the path:

New-Item -Path C:\Temp\* -Name temp.txt -ItemType File

# Result
C:\Temp\One\temp.txt
C:\Temp\Three\temp.txt
C:\Temp\Two\temp.txt

The new-item cmdlet won’t create a file if it already exists. In some cases you might just want to overwrite the file or make sure that your script continues without throwing any errors. If you want to overwrite a file if it already exists, then you can use the -force parameter.

This will overwrite the file if it exists, which also means that any content in the file will be lost:

New-Item -Path "c:\temp" -Name "test01.txt" -ItemType File -Force

Another option is to check if the file exists, we can do this with the Test-Path cmdlet:

$path = "c:\temp\test1.txt"

# Create the folder is the path doesn't exist
If (-not(test-path -Path $path)) {
    New-Item -Path $path -ItemType File
}

As you can see in the example above, we actually don’t have to specify the filename, we can also include it in the file path. The New-Item cmdlet will then still create the required file.

Create a File with Content

As mentioned in the beginning, there are other methods to create a file in PowerShell. These methods can be used when you not only want to create the file but also want to add content to it. For example, when you retrieve data with a cmdlet and want to store it in a text file, then we can use the Out-File cmdlet or use a redirect operator

Get-LocalUser | Select name | Out-File c:\temp\localusers.txt

# Or with the redirect operator
Get-LocalUser | Select name > c:\temp\localusers.txt
powershell create file

We can also create a file and save the content with the New-Item cmdlet or the Set-Content cmdlet. Both cmdlets work pretty much the same, only the Set-Content cmdlet will replace the contents when the file already exists, whereas New-Item will throw an error when the file already exists.

# Create a file and set the content
Set-Content -Path c:\temp\newFile.txt -Value "New file with Content"

# Or use New-Item to create the file with content
New-Item -Path c:\temp\ -name "newFile.txt" -Value "New file with Content"

Creating Multiple Files

To create multiple files we have two options, we can either specify each file inside the path parameter or use an ForEach loop. If you only need to create two or three files then you could just specify them in the path parameter:

New-Item -Path "c:\temp\test01.txt","c:\temp\test02.txt" -ItemType File

But a more readable option is to use a small ForEach loop and an array with the files that you want to create. This way it is easier to add or change files in the array and also add some logic to it when needed.

# Specify the directory where you want to create the files
$targetDirectory = "C:\temp\"

# Create an array of file names
$fileNames = @("File1.txt", "File2.txt", "File3.txt")

# Loop through each file name and create a file with content
foreach ($fileName in $fileNames) {
    New-Item -Path $targetDirectory -Name $filename -ItemType file
    
    $filePath = Join-Path -Path $targetDirectory -ChildPath $fileName
    Write-Host "Created file: $filePath"
}

Another option, when you don’t want to specify the file names, is to iterate over an index and create some text files using the index number:

1..10 | ForEach-Object {
    New-Item -Path "C:\temp\" -Name "$_.txt" -ItemType file
}

Creating Special Files

Until now we have only created TXT files. But with PowerShell, we are not limited to TXT files alone. We can also create CSV, JSON, HTML, or XML files for example. To do this we will need to make sure that the content of the file is converted to the correct format.

:/>  Как установить dll файл? » Полезные компьютерные программы и советы

Basically, you can create any file type with the New-Item cmdlet. If you would for example set the file type to .pdf, then you will get a “PDF” file in the given directory. The only problem is that you can’t open it, because the content of the file is not in the correct format.

This means that if you want to create a CSV file for example, that you will need to use the Export-CSV cmdlet. Or for an XML file, you will need to use the Export-CliXml cmdlet:

$xmlData | Export-CliXml -Path "c:\temp\test.xml" -Encoding UTF8

Wrapping Up

Creating files in PowerShell is pretty easy with the new-item cmdlet. Make sure that the contents of your file match the file type, by using the correct cmdlets to store the data inside the file.

I hope you found this article helpful, if you have any questions, just drop a comment below.

PowerShell script

(Image credit: Mauro Huculak)

On Windows 11 (or 10), PowerShell is a command-line interface (CLI) to run commands and scripts to automate tasks and change settings on your device, similar to Command Prompt. However, PowerShell is a more powerful CLI, offering more tools and flexibility. In addition, unlike Command Prompt, PowerShell is available across platforms, including Windows, macOS, and Linux.

A script is a collection of instructions written to a text file (using the “.ps1” extension) that PowerShell understands and executes in sequence to run different actions.

The only caveat is that the default security protocol prevents scripts from running on your computer. This means that when double-clicking a “.ps1” file, the system won’t do anything, and if you try to run the script within PowerShell, you will see the “cannot be loaded because running scripts is disabled on this system” error message. However, running scripts on your device is possible. You only need to enable the correct execution policy.

In this how-to guide, I will walk you through the steps to create and run your first script file on PowerShell using Visual Studio Code, Notepad, and the PowerShell Integrated Scripting Environment (ISE) console, whether you use Windows 10 or 11.

How to create PowerShell script file on Windows 11 and 10

It’s possible to create PowerShell script files using any text editor or the legacy ISE application. However, the Visual Studio Code editor is the preferred option for writing scripts moving forward.

Create a script with VS Code

Visual Studio Code (VS Code) is a free, extensible, cross-platform code editor that works to write virtually any programming language. And when adding the PowerShell extension, you get an interactive scripting editing experience, which even comes with IntelliSense (code-completion) support.

You can still use PowerShell ISE, but Visual Studio Code with the PowerShell extension is meant to be the new default experience. Also, consider that the legacy experience won’t get any new features and doesn’t support PowerShell 7 or future releases.

All the latest news, reviews, and guides for Windows and Xbox diehards.

Install VS Code

To install Visual Basic Code on Windows 11 (or 10), use these steps:

  1. Open the Visual Studio Download page.
  2. Click the Windows button to download the installation file.

Visual Studio Code

(Image credit: Mauro Huculak)
  1. Double-click the installer to begin the process.
  2. Select the “I accept the agreement” option.
  3. Click the Next button.
  4. Confirm additional tasks as necessary.
  5. Click the Next button again.

VS Code Setup

(Image credit: Mauro Huculak)
  1. Click the Install button.
  2. Click the Finish button.

Once you complete the steps, you can continue installing the PowerShell extension for VS Code.

Install PowerShell extension

To install the PowerShell extension on VS Code, use these steps:

  1. Open VS Code.
  2. Click the Extensions tab (“Ctrl + Shift + X” keyboard shortcut) from the left pane.
  3. Search for PowerShell and select the top result.
  4. Click the Install button.

VS Code install PowerShell

(Image credit: Mauro Huculak)
  1. Click the “Trust Workspace & Install” button.

VS Code trust workspace and install

(Image credit: Mauro Huculak)

After you complete the steps, you can start writing PowerShell scripts from Visual Studio Code.

Create PowerShell script with Visual Studio Code

To create a script with Visual Basic Code on Windows 11 (or 10), use these steps:

  1. Open VS Code.
  2. Click the File menu and select the “New Text File” option.
  3. Click the File menu and select the Save As option.

VS Code create new ps1 file

(Image credit: Mauro Huculak)
  1. In the “File name” field, specify a name for the file with the “.ps1” extension — for example, first_script.ps1.
  2. Click the Save button.
  3. Write a new or paste the script you want to run — for example, Write-Host “Congratulations! Your first script executed successfully”
  • Quick note: The above script will output on the screen that says: “Congratulations! Your first script executed successfully.”
  1. (Optional) Open the Run menu, select the Start Debugging option from the command bar, or press the F5 key) to run the script.

Write-Host "Congratulations! Your first script executed successfully"

(Image credit: Mauro Huculak)
  1. Click the File menu.
  2. Click the Save option.

Create PowerShell script with Notepad

To create a PowerShell script with the Notepad app, use these steps:

  1. Open Start.
  2. Search for Notepad, and click the top result to open the app.
  3. Write a new or paste your script in the text file — for example, Write-Host “Congratulations! Your first script executed successfully”

PowerShell Notepad script

(Image credit: Mauro Huculak)
  • Quick note: Although the Notepad app looks a little different on Windows 11, the instructions will also apply.
  1. Click the File menu.
  2. Select the Save As option.
  3. Confirm a descriptive name for the script — for example, first_script.ps1.

Notepad save script file

(Image credit: Mauro Huculak)
  1. Click the Save button.

Create PowerShell script with Integrated Scripting Environment

You can also use the built-in PowerShell ISE app to code your scripts on Windows.

The Integrated Scripting Environment (ISE) is a complex tool, but you can get started using these easy steps:

  1. Open Start.
  2. Search for Windows PowerShell ISE, right-click the top result, and select the Run as administrator option.
  3. Click the File menu.
  4. Select the New option to create a new empty “.ps1” file.
  5. Write a new script or paste the script you want to run — for example, Write-Host “Congratulations! Your first script executed successfully”

PowerShell ISE script

(Image credit: Mauro Huculak)
  1. Click the File menu.
  2. Click the Save option.
  3. Type a name for the script — for example, first_script.ps1.

PowerShell ISE Script Ps1 Save

(Image credit: Mauro Huculak)
  1. Select the folder to save the script file.
  2. Click the Save button.
  3. (Optional) Click the Run button on the top-right side (or press the F5 key) to run the script.

How to run PowerShell script file on Windows 11 and 10

Whether you use Windows 11 or 10 on your computer, you must change the execution policy to run a script with PowerShell.

To change the execution policy to run PowerShell scripts on Windows 11 (or 10), use these steps:

  1. Open Start.
  2. Search for PowerShell, right-click the top result, and select the Run as administrator option.
  3. Type the following command to allow scripts to run and press Enter: Set-ExecutionPolicy RemoteSigned
  4. Type “A” and press Enter (if applicable).
  5. Type the following command to run the script and press Enter: & “C:\PATH\TO\SCRIPT\first_script.ps1”

Run PowerShell script on Windows 10

(Image credit: Mauro Huculak)

After you complete the steps, the script will run, and if it was written correctly, you should see its output on the screen without issues.

PowerShell includes four execution policies that apply to the operating system:

  • Restricted — Prevents any script from running.
  • RemoteSigned — Allows scripts created on the computer, but scripts created on another device won’t run unless they include a trusted publisher’s signature.
  • AllSigned — All the scripts will run, but only if a trusted publisher has signed them.
  • Unrestricted — Runs any script without any restrictions.

Оставьте комментарий