Скрипт PowerShell для создания пакетного файла для удаления и переименования путей к файлам.

Переводчик Google

Malnutrition

Разработчик
Сообщения
394
Реакции
59
Код:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# Function to create a button
function Create-Button {
    param (
        [string]$text,
        [scriptblock]$onClickAction
    )
    $button = New-Object System.Windows.Forms.Button
    $button.Text = $text
    $button.Dock = "Top"
    $button.Add_Click($onClickAction)
    return $button
}

# Function to create a message box
function Show-MessageBox {
    param (
        [string]$message,
        [string]$title
    )
    [System.Windows.Forms.MessageBox]::Show($message, $title)
}

# Function to generate batch code for renaming files/folders
function Generate-RenameBatchCode {
    param (
        [string[]]$filePaths
    )
    $batchCode = ""
    foreach ($filePath in $filePaths) {
        $filePath = $filePath.Trim()
        if ($filePath -ne "") {
            $fileName = [System.IO.Path]::GetFileName($filePath)
            $fileDirectory = [System.IO.Path]::GetDirectoryName($filePath)
            $newFileName = "$fileName.bak"
            $newFilePath = Join-Path -Path $fileDirectory -ChildPath $newFileName
            
            # Check if it's a directory or a file
            if (Test-Path $filePath -PathType Container) {
                # For folders
                $batchCode += "takeown /f `"$filePath`"`n"
                $batchCode += "icacls `"$filePath`" /grant Everyone:F`n"
                $batchCode += "rename `"$filePath`" `"$newFileName`"`n"
            } else {
                # For files
                $processName = [System.IO.Path]::GetFileNameWithoutExtension($fileName)
                $batchCode += "takeown /f `"$filePath`"`n"
                $batchCode += "icacls `"$filePath`" /grant Everyone:F`n"
                $batchCode += "taskkill /F /IM `"$processName.exe`"`n"
                $batchCode += "rename `"$filePath`" `"$newFileName`"`n"
            }
        }
    }
    return $batchCode
}

# Function to generate batch code for deleting files/folders
function Generate-DeleteBatchCode {
    param (
        [string[]]$filePaths
    )
    $batchCode = ""
    foreach ($filePath in $filePaths) {
        $filePath = $filePath.Trim()
        if ($filePath -ne "") {
            if (Test-Path $filePath -PathType Container) {
                $batchCode += "takeown /f `"$filePath`"`n"
                $batchCode += "icacls `"$filePath`" /grant Everyone:F`n"
                $batchCode += "rmdir /s /q `"$filePath`"`n"
            } else {
                $fileName = [System.IO.Path]::GetFileName($filePath)
                $processName = [System.IO.Path]::GetFileNameWithoutExtension($fileName)
                $batchCode += "takeown /f `"$filePath`"`n"
                $batchCode += "icacls `"$filePath`" /grant Everyone:F`n"
                $batchCode += "taskkill /F /IM `"$processName.exe`"`n"
                $batchCode += "del /f /q `"$filePath`"`n"
            }
        }
    }
    return $batchCode
}






# Create the main form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Batch Code Assist"
$form.Width = 800
$form.Height = 600
$form.AllowDrop = $true

# Create the text box for pasting input
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Multiline = $true
$textBox.Dock = "Top"
$textBox.Height = 400
$textBox.ScrollBars = "Both"
$textBox.MaxLength = 2147483647
$form.Controls.Add($textBox)

# Create the copy and paste button
$copyPasteButton = Create-Button "Copy and Paste Input" {
    try {
        $textBox.Text = [System.Windows.Forms.Clipboard]::GetText()
    } catch {
        $errorMessage = $_.ToString()
        Show-MessageBox "Failed to get text from clipboard: $errorMessage" "Error"
    }
}
$form.Controls.Add($copyPasteButton)

# Create the rename button
$renameButton = Create-Button "Rename File" {
    $filePaths = $textBox.Text.Split([Environment]::NewLine)
    $batchCode = Generate-RenameBatchCode -filePaths $filePaths
    if ($batchCode -ne "") {
        $desktopPath = [Environment]::GetFolderPath("Desktop")
        $renameBatchPath = Join-Path -Path $desktopPath -ChildPath "rename.bat"
        $batchCode | Out-File -FilePath $renameBatchPath -Encoding ASCII
        Show-MessageBox "Rename batch file saved to desktop as rename.bat" "Success"
    }
}
$form.Controls.Add($renameButton)

# Create the delete button
$deleteButton = Create-Button "Delete File/Folder" {
    $filePaths = $textBox.Text.Split([Environment]::NewLine)
    $batchCode = Generate-DeleteBatchCode -filePaths $filePaths
    if ($batchCode -ne "") {
        $desktopPath = [Environment]::GetFolderPath("Desktop")
        $deleteBatchPath = Join-Path -Path $desktopPath -ChildPath "delete.bat"
        $batchCode | Out-File -FilePath $deleteBatchPath -Encoding ASCII
        Show-MessageBox "Delete batch file saved to desktop as delete.bat" "Success"
    }
}
$form.Controls.Add($deleteButton)

# Event handler for drag enter
$form.Add_DragEnter({
    if ($_.Data.GetDataPresent([Windows.Forms.DataFormats]::FileDrop)) {
        $_.Effect = [Windows.Forms.DragDropEffects]::Copy
    }
})

# Event handler for drag drop
$form.Add_DragDrop({
    $files = $_.Data.GetData([Windows.Forms.DataFormats]::FileDrop)
    foreach ($file in $files) {
        if ($file -match '\.(txt|log)$') {
            $textBox.Text += Get-Content -Path $file -Raw
            $textBox.Text += "`n"  # Add a new line for separation
        } else {
            [System.Windows.Forms.MessageBox]::Show("Only .txt and .log files are supported.", "Error")
        }
    }
})


# Show the form
$form.ShowDialog()



Пример вывода для: C:\Windows\System32\smartscreen.exe

Удалить:

Код:
takeown /f "C:\Windows\System32\smartscreen.exe"
icacls "C:\Windows\System32\smartscreen.exe" /grant Everyone:F
taskkill /F /IM "smartscreen.exe"
del /f /q "C:\Windows\System32\smartscreen.exe"


Переименовать:

Код:
takeown /f "C:\Windows\System32\smartscreen.exe"
icacls "C:\Windows\System32\smartscreen.exe" /grant Everyone:F
taskkill /F /IM "smartscreen.exe"
rename "C:\Windows\System32\smartscreen.exe" "smartscreen.exe.bak"
 
Я бы не назвал это скриптом Powershell.
У Powershell есть доступ к Net объектам, напрямую изменяющими отдельные права в DACL, без необходимости вызывать takeown, icacls.
Пример использования.

На счет batch, есть такой скрипт, делающий это надежней: Locker / Unlocker NTFS [усовершенствованная версия]
Потому что иногда недостаточно просто добавить привилегии. Иногда у объекта установлены запреты, которые имеют приоритет. Чтобы получить доступ к такому объекту, сперва необходимо очистить запреты.
 
Назад
Сверху Снизу