Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· openaiHugging Face Suzhen/CodeChat

Make a powershell script taking a directory dirname from command line. The script should…

  1. User

    Make a powershell script taking a directory dir_name from command line. The script should find and delete files with names from a list [file1, file2, file3] and any extension recursively in all subdirectories under dir_name.

  2. Assistant

    Below is a PowerShell script that takes a directory name from the command line and searches for files named "file1", "file2", and "file3" (regardless of their extensions) in the specified directory and all its subdirectories. It then deletes the found files. Make sure you have the necessary permissions to delete files in the specified directory and its subdirectories.

    # Save this script as DeleteSpecificFiles.ps1
    
    param (
        [string]$dir_name # Take directory name as a command line argument
    )
    
    # List of file names to search and delete
    $file_names = @('file1', 'file2', 'file3')
    
    # Check if the directory exists
    if (Test-Path $dir_name) {
        # Loop through each file name in the list
        foreach ($file_name in $file_names) {
            # Search for the files recursively in all subdirectories
            $files_to_delete = Get-ChildItem -Path $dir_name -Recurse -Force | Where-Object { $_.BaseName -eq $file_name }
    
            # Loop through each file found and delete it
            foreach ($file in $files_to_delete) {
                Remove-Item $file.FullName -Force
                Write-Host "Deleted file: $($file.FullName)"
            }
        }
    }
    else {
        Write-Error "Directory not found: $dir_name"
    }
    

    How to Use the Script

    1. Save the script: Copy the above script into a new file named DeleteSpecificFiles.ps1.

    2. Open PowerShell: Use an account with the necessary permissions to delete files in the target directories.

    3. Execute the script with a directory parameter: Run the script followed by the -dir_name parameter and the path to your target directory. For example:

      .\DeleteSpecificFiles.ps1 -dir_name "C:\ExampleDirectory"
      
    4. Running the Script with Elevated Permissions: If you encounter permission issues, you might need to run PowerShell as an administrator (right-click the PowerShell icon and select "Run as administrator").

    Important Considerations

    • The script deletes files without confirmation, use it with caution.
    • Ensure you have backups if necessary, as deleted files might not be recoverable.
    • The script currently is set to delete files named exactly "file1", "file2", and "file3" regardless of their extension. Modify the $file_names array if you need to target different or additional files.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.