Выполнение сценария powershell поднято и тихо

While working with files in PowerShell, you may get requirements to check if a file contains a specified string. PowerShell provides different methods to check if a file contains a string. Let us check each method with examples.

To check if a file contains a specific string in PowerShell, you can use the Select-String cmdlet with the -Pattern parameter specifying your search term, and the -Path parameter to define the file’s location. For a simple true or false return, add the -Quiet switch. For example: $containsString = Select-String -Path “C:\MyFolder\MyFile.txt” -Pattern “searchTerm” -Quiet will return True if “searchTerm” is found, otherwise False.

I am using Visual Studio code to execute all the PowerShell scripts. You can also use Windows PowerShell ISE to execute the examples.

And for each method, I will take a .txt file.

Now, let us check various methods of PowerShell to check if a file contains a specific string.

1. Using the Select-String Cmdlet

The Select-String cmdlet in PowerShell is similar to the grep command in Unix or Linux. This command you can use to search for text patterns within files. It uses regular expression matching to search for text patterns in input strings and files.

Here’s a simple example of how to use Select-String in PowerShell to check if a file contains a specific string.

Select-String -Path "C:\MyFolder\MyFile.txt" -Pattern "powershellfaqs"

This command searches for the string “powershellfaqs” in the file “MyFile.txt” located in “C:\MyFolder”. If the string is found, Select-String will return the line or lines containing the string, along with some additional context information.

The screenshot below shows that this file contains the string twice and displays both lines.

Check if a File Contains a String in PowerShell

2. Check for a String in Multiple Files in PowerShell

Sometimes, you may want to check for a sting in all the files in the folder, and this is easy to do in PowerShell.

To check for a specific string across multiple files in PowerShell, you can combine Get-ChildItem with Select-String:

Get-ChildItem -Path "C:\MyFolder\*.txt" | Select-String -Pattern "powershellfaqs"

This script searches for “powershellfaqs” in all text files within “C:\MyFolder”. It lists any files containing the string, along with the lines where the string was found.

3. Using the -Quiet Switch

This is another simple method if you just want to know if the string is presented in the file or not in PowerShell. It just returns true or false.

:/>  Как удалить файл или папку из командной строки

If you only need to know whether the string exists in the file and don’t need to see the specific lines, you can use the -Quiet switch in PowerShell. This will return a boolean value: True if the string is found, and False otherwise.

$containsString = Select-String -Path "C:\MyFolder\MyFile.txt" -Pattern "powershellfaqs" -Quiet
$containsString

Here, you can see the output in the screenshot below; it returns true as the string is presented in the file.

How to Check if a File Contains a String in PowerShell

4. Checking if a String Exists with -match Operator

Here is also another method to check if a string exists within a file is to use the -match operator in PowerShell. First, you’ll need to read the file content into a variable and then use -match to search for the string.

$content = Get-Content -Path "C:\MyFolder\MyFile.txt"
$containsString = $content -match "powershellfaqs"

This approach is useful when you want to perform additional operations on the file content after checking for the string.

5. Using .Contains() Method

This is another simple method to check if a string contains in a file in PowerShell. In PowerShell, you can use the .Contains() method on a string object. After reading the file into a variable, you can check if the string contains your specified term.

$content = Get-Content -Path "C:\MyFolder\MyFile.txt" -Raw
$containsString = $content.Contains("powershellfaqs")

Note that .Contains() is case-sensitive. For a case-insensitive search, you can convert both the content and the search term to the same case using .ToLower() or .ToUpper().

Here is the PowerShell script for case-insensitive search.

$content = Get-Content -Path "C:\MyFolder\MyFile.txt" -Raw
$lowercaseContent = $content.ToLower()
$containsString = $lowercaseContent.Contains("powershellfaqs".ToLower())

6. Using -like Operator with Wildcards

In PowerShell, the -like operator allows you to use wildcards for pattern matching. This can be useful when you want to check if a string contains a specific word or pattern.

$content = Get-Content -Path "C:\MyFolder\MyFile.txt"
$containsString = $content -like "*powershell*"

The asterisks * are wildcards that represent any number of characters. This command will return True if “powershell” is found anywhere in the content.

7. Using Regular Expressions

In PowerShell, you can also use regular expressions to do a pattern-matching search. You can use regular expressions with Select-String. This allows you to search for complex patterns within the text.

Select-String -Path "C:\MyFolder\MyFile.txt" -Pattern "powershell\w+"

Conclusion

PowerShell provides several methods to check if a file contains a specific string or pattern. In this PowerShell tutorial, I have explained with examples how to check if a file contains a string using the below methods:

  1. Using the Select-String Cmdlet
  2. Check for a String in Multiple Files in PowerShell
  3. Using the -Quiet Switch
  4. Checking if a String Exists with -match Operator
  5. Using .Contains() Method
  6. Using -like Operator with Wildcards
  7. Using Regular Expressions
:/>  Как использовать DiskPart Utility в Windows

You may also like:

Getting PowerShell MSI file

Here, we will be installing PowerShell core 7.2.2 which is the latest stable version at the time of writing this blog, on Windows 11. You can download PowerShell core MSI file from here. You can also download this MSI file from PowerShell by using the script given below.

Invoke-WebRequest -Uri "https://github.com/PowerShell/PowerShell/releases/download/v7.2.2/PowerShell-7.2.2-win-x64.msi" -OutFile C:\Temp\PowerShell-7.2.2-win-x64.msi
Installing PowerShell Core

I am using Visual Studio code in this demo. You may use native PowerShell console to perform further steps. However, if you too want to use VS code, ensure that you have PowerShell extension installed in VS code.

Once you have the MSI file, you can use this file to check the options available for installation. You can do so by adding /? to the MSI file name. Here we will enter

Once you enter this, you will be presented with a dialog box, that will list out the options that are available to us. You can choose from multiple options including logging of the installation. For this demo, we will only be using quiet and passive switches. Quiet switch will do the installation silently and passive switch will display the progress bar.

Выполнение сценария powershell поднято и тихо

– This property controls the option for adding the Open PowerShell item to the context menu in Windows Explorer.

– This property controls the option for adding the Run with PowerShell item to the context menu in Windows Explorer.

– This property controls the option for enabling PowerShell remoting during installation.

– This property controls the option for registering the Windows Event Logging manifest.

– This property has two possible values:

1 (default) – Opts into updating through Microsoft Update, WSUS, or Configuration Manager

0 – Do not opt into updating through Microsoft Update, WSUS, or Configuration Manager

:/>  Как узнать ключ Windows 7, 8, 10 с помощью программ и средств

1 (default) – Opts into using Microsoft Update for Automatic Updates

0 – Do not opt into using Microsoft Update

Выполнение сценария powershell поднято и тихо

I will then use command to initiate the installation. I will pass switches and options in Argumentlist parameter. I’ll then hit enter and the installation will start.

Start-Process .\PowerShell-7.2.2-win-x64.msi -ArgumentList "/quiet /passive ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1 USE_MU=1 ENABLE_MU=1"
Выполнение сценария powershell поднято и тихо

You can install PowerShell core on remote machines using . The example given below will install PowerShell core on remote system named LabMachine2k19.

Once the installation is completed, I will now go to start and search for pwsh. The PowerShell core icon here ensures PowerShell core is installed successfully on this system. However, we will still verify the version from VS code.

Выполнение сценария powershell поднято и тихо

I will then restart VS code editor and once I’m in, I’ll click on ‘+’ sign to add a new terminal.

Выполнение сценария powershell поднято и тихо

A new PowerShell core terminal start named ‘pwsh’. VS code will use PowerShell core as it’s default PowerShell.

Выполнение сценария powershell поднято и тихо

I will then enter to check for the PowerShell version. Here, we can see PowerShell 7.2.2 is installed on this system.

Выполнение сценария powershell поднято и тихо

This method can be used to deploy PowerShell core on multiple systems in your organization using any deployment tool that supports MSI installation or simply using as shown in the above example.

Here is a test script:

$LastExitCode = 99
$sItem_1 = "C:\temp\file 1.txt"
$sItem_2 = "C:\temp\file 2.txt"
write-output "Do FC:"
cmd.exe /c "FC /b ""$sItem_1"" ""$sItem_2"" > null"
write-output $LastExitCode
$LastExitCode = 99
write-output "Do comp:"
cmd.exe /c "echo N | comp ""$sItem_1"" ""$sItem_2"" > null"
write-output $LastExitCode

and here is the console output of that script:

PS> test 2.ps1
Do FC:
0
Do comp:
cmd.exe : Compare more files (Y/N) ?
At test 2.ps1:9 char:1
+ cmd.exe /c "echo N | comp ""$sItem_1"" ""$sItem_2"" > null"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Compare more files (Y/N) ? :String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError
PS> 

In the second line of output, the zero exit code means that FC found the files to be identical. But when PowerShell attempted to run comp, it choked on the “Compare more” prompt.

How can I get this to run?