0

I want to scan the whole desktop for .bat and then view the .bat file's content and delete the file if it includes ipconfig for a project. Is there any way I can do it? I'd like to NOT use third party tools

10
  • 1
    Why don't you just open the file with Notepad? You can just use "cat filename" within a PowerShell prompt.
    – Ramhound
    Commented Aug 17, 2021 at 16:58
  • it doesnt work i tried it on test.bat which had the code "echo test123" and it showed some broken characters Commented Aug 17, 2021 at 17:14
  • 1
    You can use type to spit out the file content to the prompt. Commented Aug 17, 2021 at 17:17
  • 3
    TheCodeExpert is a funny name given the question you are asking. Commented Aug 17, 2021 at 19:02
  • 1
    Your question says you know nothing or very little about PowerShell. As this is a day one learning thing. Plety of examples all over the web and via Youtube. This is not a PowerShell issue or specific feaqture. You can do this in cmd.exe just a easily or any other scripting language. You learn by doing one thing at a time, then putting it together. Not asking others to do your work for you.
    – postanote
    Commented Aug 18, 2021 at 0:28

4 Answers 4

2

The Powershell script below gets the content of the file myfile.bat, check if the string ipconfig is present. If yes, the file is deleted.

$file = 'c:\temp\myfile.bat`
$a = Get-Content $file | Select-String ipconfig
if( $a.Length -gt 0){Remove-Item $file}

To include a folder for example your Desktop, change the script as shown below. Replace mthecodeexpert with your real username.

$folder = 'c:\users\thecodeexpert\*.bat'
$files = Get-ChildItem $folder -file
$files | ForEach-Object{ $a = Select-String -Path $_.Fullname ipconfig; if ($a.Length -gt 0){Remove-Item $_.Fullname}}
5
  • this works but not as I wanted. It needs to check the desktop for *.bat's and then do this... Commented Aug 17, 2021 at 18:54
  • Please expand this answer with the function to search for batch files at a given location. Yes, I could do it but it is your answer and beats the cmd.exe method (IMHO).. and yes, I love batch too.. but powershell is usually a better tool when it comes to grepping files. Your answer can even be used on non MS operating systems. Commented Aug 17, 2021 at 19:01
  • select-string already grabs the contents from files Commented Aug 17, 2021 at 23:50
  • 1
    @SeñorCMasMas See edit. Commented Aug 18, 2021 at 5:37
  • 1
    @TheCodeExpert See edit. Commented Aug 18, 2021 at 5:38
1

Continuing from my comment...

# Find the files by type
(Get-ChildItem -Path "$env:USERPROFILE\Desktop" -Filter '*.bat' -Recurse).FullName
# Results
<#
C:\Users\WDAGUtilityAccount\Desktop\SomeBatFile.bat
#>

# Test planned action on the file to find the string pattern
(Get-ChildItem -Path "$env:USERPROFILE\Desktop" -Filter '*.bat' -Recurse).FullName | 
ForEach-Object {
    If (Select-String -Path $PSItem -Pattern 'ipconfig')
    {Remove-Item -Path $PSItem -WhatIf}
}

# Results
<#
What if: Performing the operation "Remove File" on target "C:\Users\WDAGUtilityAccount\Desktop\SomeBatFile.bat".
#>


# Take action on the file to find the string pattern
(Get-ChildItem -Path "$env:USERPROFILE\Desktop" -Filter '*.bat' -Recurse).FullName | 
ForEach-Object {
    If (Select-String -Path $PSItem -Pattern 'ipconfig')
    {Remove-Item -Path $PSItem -Force -Verbose}
}
# Results
<#
VERBOSE: Performing the operation "Remove File" on target "C:\Users\WDAGUtilityAccount\Desktop\SomeBatFile.bat".
#>

# Validate removal
(Get-ChildItem -Path "$env:USERPROFILE\Desktop" -Filter '*.bat' -Recurse).FullName
# Results
<#
No results
#>
1
  • Hmm, didn't cross my mind to account if there was no file containing the word. I'm getting old:( Commented Aug 18, 2021 at 0:41
0

To search all files, use a for loop:

@echo off
cd /d "%userprofile%\desktop"
for %%a in (*.bat) do (
  type "%%a"|find /i "ipconfig" && echo del "%%a"
)

There is another way (looks slightly more complicated but in programmer's view is more elegant because it doesn't have to process files that don't contain the search string). This will be much faster, if there are a lot of files (and I mean a lot of). You won't notice the speed advantage in your desktop folder though.

findstr /m returns not the found lines, but the filenames, where such lines were found. Put a for /f around to capture those filenames and delete them:

@echo off
for /f "delims=" %%a in ('findstr /im "ipconfig" "%userprofile%\desktop\*.bat"') do del "%%a"

(Note: your Desktop might be at a different location - check it)

9
  • what if its in a folder on desktop Commented Aug 17, 2021 at 18:44
  • If the folder name is known, just add it. If you want "anywhere in desktop or a subfolder, change to findstr /sim.
    – Stephan
    Commented Aug 17, 2021 at 18:48
  • Its unknown.... Commented Aug 17, 2021 at 18:49
  • and your code gives errors: %%a was unexpected at this time. Commented Aug 17, 2021 at 18:50
  • 1
    @TheCodeExpert While there are technical differences between them, using either extension is unlikely to make a difference in this case. Both should likely be run through cmd.exe. Commented Aug 17, 2021 at 23:40
0

You can use Select-String in PowerShell which allows you to search through a directory (for specific file types - extensions) allowing you to find a pattern match in the files filtered for:

$Paths = Select-String -Path "$env:USERPROFILE\Desktop\*" -Include '*.bat','*.cmd' -Pattern 'ipconfig'  | Select-Object -ExpandProperty Path 
    if ($null -ne $Paths) {
        foreach ($Path in $Paths){
            "Match found in filepath: $Path"
            Remove-Item -Path $Path -WhatIf
        }
    }
    else {
        'No file found containing pattern'
    }
  • By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.
  • It also allows you to use Regex pattern matching for more complicated tasks.

Storing the output to a variable, we can explicitly select the Full Path referencing the Path property. Finally, we can add some simple if conditions to evaluate against our variable, and using a foreach loop we can iterate through the capture output.

  • Storing the output to a variable is necessary (at least in this scenario) so the file doesn't stay in use - Thank you dave_thompson_085 for pointing out my mistake.

The draw back of using just this cmdlet is that, it only allows to list a single directory. Luckily, PowerShell can chain commands and all you would need is to slightly modify the code by using a Get-ChildItem with a -Recurse switch to allow for directory (folder) recursion.

$Paths = Get-ChildItem -Path "$env:USERPROFILE\Desktop" -Include '*.cmd','*.bat' -Recurse |
    Select-String -Pattern 'ipconfig' | Select-Object -ExpandProperty Path

    if ($null -ne $Paths) {
        foreach ($Path in $Paths){
            "Match found in filepath: $Path"
            Remove-Item -Path $Path -WhatIf
        }
    }
    else {
        'No file found containing pattern'
    }

Basically the same concept, so when you're ready, remove the -WhatIf common parameter and it will allow the removal of the file(s) found containing that pattern.

3
  • When you're ready and remove -whatif the remove-item FAILS because the file is in use (repeated for every file/match) Commented Aug 18, 2021 at 3:28
  • Good catch, probably helps if I actually test the code without assuming huh? lol easy enough fix. Updated. Thanks. Commented Aug 18, 2021 at 3:59
  • @dave, see my update. Commented Aug 18, 2021 at 4:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .