Добавьте префикс и суффикс к любому слову, чтобы получить помощь в сценарии PowerShell...

Переводчик Google

Malnutrition

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

# Create the main form
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Advanced Text Modifier'
$form.Size = New-Object System.Drawing.Size(500, 450)
$form.StartPosition = 'CenterScreen'

# Create input TextBox
$inputTextBox = New-Object System.Windows.Forms.TextBox
$inputTextBox.Location = New-Object System.Drawing.Point(10, 10)
$inputTextBox.Size = New-Object System.Drawing.Size(460, 100)
$inputTextBox.Multiline = $true
$inputTextBox.ScrollBars = 'Vertical'

# Create prefix TextBox
$prefixLabel = New-Object System.Windows.Forms.Label
$prefixLabel.Location = New-Object System.Drawing.Point(10, 120)
$prefixLabel.Size = New-Object System.Drawing.Size(100, 20)
$prefixLabel.Text = 'Prefix:'

$prefixTextBox = New-Object System.Windows.Forms.TextBox
$prefixTextBox.Location = New-Object System.Drawing.Point(10, 140)
$prefixTextBox.Size = New-Object System.Drawing.Size(200, 20)

# Create suffix TextBox
$suffixLabel = New-Object System.Windows.Forms.Label
$suffixLabel.Location = New-Object System.Drawing.Point(220, 120)
$suffixLabel.Size = New-Object System.Drawing.Size(100, 20)
$suffixLabel.Text = 'Suffix:'

$suffixTextBox = New-Object System.Windows.Forms.TextBox
$suffixTextBox.Location = New-Object System.Drawing.Point(220, 140)
$suffixTextBox.Size = New-Object System.Drawing.Size(200, 20)

# Create output TextBox
$outputTextBox = New-Object System.Windows.Forms.TextBox
$outputTextBox.Location = New-Object System.Drawing.Point(10, 170)
$outputTextBox.Size = New-Object System.Drawing.Size(460, 150)
$outputTextBox.Multiline = $true
$outputTextBox.ScrollBars = 'Vertical'
$outputTextBox.ReadOnly = $true

# Create radio buttons for modification type
$radioPanel = New-Object System.Windows.Forms.Panel
$radioPanel.Location = New-Object System.Drawing.Point(10, 330)
$radioPanel.Size = New-Object System.Drawing.Size(460, 50)

$radioOriginal = New-Object System.Windows.Forms.RadioButton
$radioOriginal.Location = New-Object System.Drawing.Point(10, 10)
$radioOriginal.Size = New-Object System.Drawing.Size(150, 20)
$radioOriginal.Text = 'Keep Original'
$radioOriginal.Checked = $true

$radioModified = New-Object System.Windows.Forms.RadioButton
$radioModified.Location = New-Object System.Drawing.Point(170, 10)
$radioModified.Size = New-Object System.Drawing.Size(150, 20)
$radioModified.Text = 'Modified Only'

$radioBoth = New-Object System.Windows.Forms.RadioButton
$radioBoth.Location = New-Object System.Drawing.Point(330, 10)
$radioBoth.Size = New-Object System.Drawing.Size(150, 20)
$radioBoth.Text = 'Both'

# Create Modify button
$modifyButton = New-Object System.Windows.Forms.Button
$modifyButton.Location = New-Object System.Drawing.Point(10, 390)
$modifyButton.Size = New-Object System.Drawing.Size(100, 30)
$modifyButton.Text = 'Modify Text'

# Create Save button
$saveButton = New-Object System.Windows.Forms.Button
$saveButton.Location = New-Object System.Drawing.Point(120, 390)
$saveButton.Size = New-Object System.Drawing.Size(100, 30)
$saveButton.Text = 'Save to File'

# Button click event for modification
$modifyButton.Add_Click({
    # Get input lines
    $inputLines = $inputTextBox.Text -split "`r`n"
  
    # Get prefix and suffix
    $prefix = $prefixTextBox.Text
    $suffix = $suffixTextBox.Text
  
    # Process lines based on radio button selection
    $modifiedLines = @()
  
    foreach ($line in $inputLines) {
        if ($line.Trim() -ne '') {
            # Original line with quotes and comma
            $originalLine = '"' + $line + '",'
          
            # Modified line with prefix and suffix
            $modifiedLine = '"' + $prefix + $line + $suffix + '",'
          
            # Add lines based on radio button selection
            switch ($true) {
                $radioOriginal.Checked { $modifiedLines += $originalLine }
                $radioModified.Checked { $modifiedLines += $modifiedLine }
                $radioBoth.Checked {
                    $modifiedLines += $originalLine
                    $modifiedLines += $modifiedLine
                }
            }
        }
    }
  
    # Join modified lines and display in output
    $outputTextBox.Text = $modifiedLines -join "`r`n"
})

# Button click event for saving
$saveButton.Add_Click({
    $desktopPath = [Environment]::GetFolderPath('Desktop')
    $outputTextBox.Text | Out-File -FilePath "$desktopPath\modified.txt"
    [System.Windows.Forms.MessageBox]::Show('File saved to Desktop as modified.txt', 'Save Successful')
})

# Add controls to form
$form.Controls.Add($inputTextBox)
$form.Controls.Add($prefixLabel)
$form.Controls.Add($prefixTextBox)
$form.Controls.Add($suffixLabel)
$form.Controls.Add($suffixTextBox)
$form.Controls.Add($outputTextBox)
$form.Controls.Add($radioPanel)
$radioPanel.Controls.Add($radioOriginal)
$radioPanel.Controls.Add($radioModified)
$radioPanel.Controls.Add($radioBoth)
$form.Controls.Add($modifyButton)
$form.Controls.Add($saveButton)

# Show the form
$form.Add_Shown({$form.Activate()})
$form.ShowDialog()

Сохраните как угодно.ps1

Работа продолжается.
 
Последнее редактирование модератором:
Добавьте префикс и суффикс к любому слову
А можно пример? :)

Кстати, вы сперва писали в Visual Studio, а потом использовали конвертор C# -> PS. Или сразу на PS?
 
прямо в PS


Код:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# Create the main form
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Advanced Text Modifier'
$form.Size = New-Object System.Drawing.Size(600, 500)
$form.StartPosition = 'CenterScreen'

# Create input TextBox
$inputLabel = New-Object System.Windows.Forms.Label
$inputLabel.Location = New-Object System.Drawing.Point(10, 10)
$inputLabel.Size = New-Object System.Drawing.Size(200, 20)
$inputLabel.Text = 'Input Words:'

$inputTextBox = New-Object System.Windows.Forms.TextBox
$inputTextBox.Location = New-Object System.Drawing.Point(10, 30)
$inputTextBox.Size = New-Object System.Drawing.Size(560, 100)
$inputTextBox.Multiline = $true
$inputTextBox.ScrollBars = 'Vertical'

# Create prefix TextBox for input
$inputPrefixLabel = New-Object System.Windows.Forms.Label
$inputPrefixLabel.Location = New-Object System.Drawing.Point(10, 140)
$inputPrefixLabel.Size = New-Object System.Drawing.Size(200, 20)
$inputPrefixLabel.Text = 'Input Prefix:'

$inputPrefixTextBox = New-Object System.Windows.Forms.TextBox
$inputPrefixTextBox.Location = New-Object System.Drawing.Point(10, 160)
$inputPrefixTextBox.Size = New-Object System.Drawing.Size(270, 20)

# Create suffix TextBox for input
$inputSuffixLabel = New-Object System.Windows.Forms.Label
$inputSuffixLabel.Location = New-Object System.Drawing.Point(300, 140)
$inputSuffixLabel.Size = New-Object System.Drawing.Size(200, 20)
$inputSuffixLabel.Text = 'Input Suffix:'

$inputSuffixTextBox = New-Object System.Windows.Forms.TextBox
$inputSuffixTextBox.Location = New-Object System.Drawing.Point(300, 160)
$inputSuffixTextBox.Size = New-Object System.Drawing.Size(270, 20)

# Checkbox for quote handling
$quoteCheckBox = New-Object System.Windows.Forms.CheckBox
$quoteCheckBox.Location = New-Object System.Drawing.Point(10, 190)
$quoteCheckBox.Size = New-Object System.Drawing.Size(200, 20)
$quoteCheckBox.Text = 'Add Quotes'
$quoteCheckBox.Checked = $true

# Create output TextBox
$outputLabel = New-Object System.Windows.Forms.Label
$outputLabel.Location = New-Object System.Drawing.Point(10, 220)
$outputLabel.Size = New-Object System.Drawing.Size(200, 20)
$outputLabel.Text = 'Output:'

$outputTextBox = New-Object System.Windows.Forms.TextBox
$outputTextBox.Location = New-Object System.Drawing.Point(10, 240)
$outputTextBox.Size = New-Object System.Drawing.Size(560, 150)
$outputTextBox.Multiline = $true
$outputTextBox.ScrollBars = 'Vertical'
$outputTextBox.ReadOnly = $true

# Create Modify button
$modifyButton = New-Object System.Windows.Forms.Button
$modifyButton.Location = New-Object System.Drawing.Point(10, 400)
$modifyButton.Size = New-Object System.Drawing.Size(100, 30)
$modifyButton.Text = 'Modify Text'

# Create Save button
$saveButton = New-Object System.Windows.Forms.Button
$saveButton.Location = New-Object System.Drawing.Point(120, 400)
$saveButton.Size = New-Object System.Drawing.Size(100, 30)
$saveButton.Text = 'Save to File'

# Create Clear button
$clearButton = New-Object System.Windows.Forms.Button
$clearButton.Location = New-Object System.Drawing.Point(230, 400)
$clearButton.Size = New-Object System.Drawing.Size(100, 30)
$clearButton.Text = 'Clear All'

# Button click event for modification
$modifyButton.Add_Click({
    # Get input lines
    $inputLines = $inputTextBox.Text -split "`r`n"
    
    # Get prefixes and suffixes
    $inputPrefix = $inputPrefixTextBox.Text
    $inputSuffix = $inputSuffixTextBox.Text
    
    # Process lines
    $modifiedLines = @()
    
    foreach ($line in $inputLines) {
        if ($line.Trim() -ne '') {
            # Modify input line with input prefix/suffix
            $modifiedLine = $inputPrefix + $line + $inputSuffix
            
            # Handle quotes based on checkbox
            if ($quoteCheckBox.Checked) {
                $finalLine = '"' + $modifiedLine + '",'
            }
            else {
                $finalLine = $modifiedLine + ''
            }
            
            $modifiedLines += $finalLine
        }
    }
    
    # Join modified lines and display in output
    $outputTextBox.Text = $modifiedLines -join "`r`n"
})

# Button click event for saving
$saveButton.Add_Click({
    $desktopPath = [Environment]::GetFolderPath('Desktop')
    $outputTextBox.Text | Out-File -FilePath "$desktopPath\modified.txt"
    [System.Windows.Forms.MessageBox]::Show('File saved to Desktop as modified.txt', 'Save Successful')
})

# Button click event for clearing
$clearButton.Add_Click({
    $inputTextBox.Clear()
    $inputPrefixTextBox.Clear()
    $inputSuffixTextBox.Clear()
    $outputTextBox.Clear()
})

# Add controls to form
$form.Controls.Add($inputLabel)
$form.Controls.Add($inputTextBox)
$form.Controls.Add($inputPrefixLabel)
$form.Controls.Add($inputPrefixTextBox)
$form.Controls.Add($inputSuffixLabel)
$form.Controls.Add($inputSuffixTextBox)
$form.Controls.Add($quoteCheckBox)
$form.Controls.Add($outputLabel)
$form.Controls.Add($outputTextBox)
$form.Controls.Add($modifyButton)
$form.Controls.Add($saveButton)
$form.Controls.Add($clearButton)

# Show the form
$form.Add_Shown({$form.Activate()})
$form.ShowDialog()

1732521727018.webp


1732521832512.webp


1732522389657.webp
 
Понятно. А в чем практический смысл? Это заготовка к какому-то большему проекту?
 
Это инструмент для работы с Powershell и пакетными файлами, я кое-что к этому добавлю. Я не работаю несколько дней, поэтому вчера вечером добавил перетаскивание. Также несколько незначительных изменений.

Это просто для упрощения задачи, которую люди на самом деле часто делают. Сократите количество ошибок.

Также может использоваться для сценариев FRST.


Вот обновленное:

Код:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# Function to process log file
function Process-LogFile {
    param([string]$filePath)
    
    try {
        # Read the contents of the text file
        $fileContents = Get-Content -Path $filePath -Raw
        
        # Populate the input TextBox with file contents
        $inputTextBox.Text = $fileContents
    }
    catch {
        [System.Windows.Forms.MessageBox]::Show("Error reading file: $($_.Exception.Message)", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
    }
}

# Create the main form
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Advanced Text Modifier'
$form.Size = New-Object System.Drawing.Size(600, 550)
$form.StartPosition = 'CenterScreen'

# Enable drag-and-drop directly on the form
$form.AllowDrop = $true

# Create a label for drag-and-drop area
$dropLabel = New-Object System.Windows.Forms.Label
$dropLabel.Location = New-Object System.Drawing.Point(10, 10)
$dropLabel.Size = New-Object System.Drawing.Size(560, 20)
$dropLabel.Text = 'Drag and Drop a .txt file here'
$dropLabel.TextAlign = 'MiddleCenter'
$dropLabel.BorderStyle = 'FixedSingle'

# Drag Enter Event
$form.Add_DragEnter({
    if ($_.Data.GetDataPresent([Windows.Forms.DataFormats]::FileDrop)) {
        $_.Effect = [Windows.Forms.DragDropEffects]::Copy
    }
    else {
        $_.Effect = [Windows.Forms.DragDropEffects]::None
    }
})

# Drag Drop Event
$form.Add_DragDrop({
    $files = $_.Data.GetData([Windows.Forms.DataFormats]::FileDrop)
    
    foreach ($file in $files) {
        if ($file -like "*.txt") {
            try {
                $content = Get-Content $file -Raw
                $inputTextBox.Text = $content
                break  # Stop after first txt file
            }
            catch {
                [System.Windows.Forms.MessageBox]::Show("Error reading file: $($_.Exception.Message)")
            }
        }
    }
})

# Create input TextBox
$inputLabel = New-Object System.Windows.Forms.Label
$inputLabel.Location = New-Object System.Drawing.Point(10, 40)
$inputLabel.Size = New-Object System.Drawing.Size(200, 20)
$inputLabel.Text = 'Input Paths (one per line):'

$inputTextBox = New-Object System.Windows.Forms.TextBox
$inputTextBox.Location = New-Object System.Drawing.Point(10, 60)
$inputTextBox.Size = New-Object System.Drawing.Size(560, 100)
$inputTextBox.Multiline = $true
$inputTextBox.ScrollBars = 'Vertical'

# Create prefix TextBox for input
$inputPrefixLabel = New-Object System.Windows.Forms.Label
$inputPrefixLabel.Location = New-Object System.Drawing.Point(10, 170)
$inputPrefixLabel.Size = New-Object System.Drawing.Size(200, 20)
$inputPrefixLabel.Text = 'Input Prefix:'

$inputPrefixTextBox = New-Object System.Windows.Forms.TextBox
$inputPrefixTextBox.Location = New-Object System.Drawing.Point(10, 190)
$inputPrefixTextBox.Size = New-Object System.Drawing.Size(270, 20)

# Create suffix TextBox for input
$inputSuffixLabel = New-Object System.Windows.Forms.Label
$inputSuffixLabel.Location = New-Object System.Drawing.Point(300, 170)
$inputSuffixLabel.Size = New-Object System.Drawing.Size(200, 20)
$inputSuffixLabel.Text = 'Input Suffix:'

$inputSuffixTextBox = New-Object System.Windows.Forms.TextBox
$inputSuffixTextBox.Location = New-Object System.Drawing.Point(300, 190)
$inputSuffixTextBox.Size = New-Object System.Drawing.Size(270, 20)

# Checkbox for quote handling
$quoteCheckBox = New-Object System.Windows.Forms.CheckBox
$quoteCheckBox.Location = New-Object System.Drawing.Point(10, 220)
$quoteCheckBox.Size = New-Object System.Drawing.Size(200, 20)
$quoteCheckBox.Text = 'Add Quotes'
$quoteCheckBox.Checked = $true

# Create output TextBox
$outputLabel = New-Object System.Windows.Forms.Label
$outputLabel.Location = New-Object System.Drawing.Point(10, 250)
$outputLabel.Size = New-Object System.Drawing.Size(200, 20)
$outputLabel.Text = 'Output:'

$outputTextBox = New-Object System.Windows.Forms.TextBox
$outputTextBox.Location = New-Object System.Drawing.Point(10, 270)
$outputTextBox.Size = New-Object System.Drawing.Size(560, 150)
$outputTextBox.Multiline = $true
$outputTextBox.ScrollBars = 'Vertical'
$outputTextBox.ReadOnly = $true

# Create Modify button
$modifyButton = New-Object System.Windows.Forms.Button
$modifyButton.Location = New-Object System.Drawing.Point(10, 430)
$modifyButton.Size = New-Object System.Drawing.Size(100, 30)
$modifyButton.Text = 'Modify Text'

# Create Save button
$saveButton = New-Object System.Windows.Forms.Button
$saveButton.Location = New-Object System.Drawing.Point(120, 430)
$saveButton.Size = New-Object System.Drawing.Size(100, 30)
$saveButton.Text = 'Save to File'

# Create Clear button
$clearButton = New-Object System.Windows.Forms.Button
$clearButton.Location = New-Object System.Drawing.Point(230, 430)
$clearButton.Size = New-Object System.Drawing.Size(100, 30)
$clearButton.Text = 'Clear All'

# Button click event for modification
$modifyButton.Add_Click({
    # Get input lines
    $inputLines = $inputTextBox.Lines
    
    # Get prefixes and suffixes
    $inputPrefix = $inputPrefixTextBox.Text
    $inputSuffix = $inputSuffixTextBox.Text
    
    # Process lines
    $modifiedLines = @()
    
    foreach ($line in $inputLines) {
        if ($line.Trim() -ne '') {
            # Modify input line with input prefix/suffix
            $modifiedLine = $inputPrefix + $line + $inputSuffix
            
            # Handle quotes based on checkbox
            if ($quoteCheckBox.Checked) {
                $finalLine = '"' + $modifiedLine + '",'
            }
            else {
                $finalLine = $modifiedLine + ''
            }
            
            $modifiedLines += $finalLine
        }
    }
    
    # Join modified lines and display in output
    $outputTextBox.Text = $modifiedLines -join "`r`n"
})

# Button click event for saving
$saveButton.Add_Click({
    $desktopPath = [Environment]::GetFolderPath('Desktop')
    $outputTextBox.Text | Out-File -FilePath "$desktopPath\modified.txt"
    [System.Windows.Forms.MessageBox]::Show('File saved to Desktop as modified.txt', 'Save Successful')
})

# Button click event for clearing
$clearButton.Add_Click({
    $inputTextBox.Clear()
    $inputPrefixTextBox.Clear()
    $inputSuffixTextBox.Clear()
    $outputTextBox.Clear()
})

# Add controls to form
$form.Controls.Add($dropLabel)
$form.Controls.Add($inputLabel)
$form.Controls.Add($inputTextBox)
$form.Controls.Add($inputPrefixLabel)
$form.Controls.Add($inputPrefixTextBox)
$form.Controls.Add($inputSuffixLabel)
$form.Controls.Add($inputSuffixTextBox)
$form.Controls.Add($quoteCheckBox)
$form.Controls.Add($outputLabel)
$form.Controls.Add($outputTextBox)
$form.Controls.Add($modifyButton)
$form.Controls.Add($saveButton)
$form.Controls.Add($clearButton)

# Show the form
$form.Add_Shown({$form.Activate()})
$form.ShowDialog()
 
Понял, тогда удачи!

Последний вариант кода кстати, не хочет запускаться.

Так-то удобнее и создавать, и использовать сразу через Visual Studio, или через VS Code, чтобы скомпилировать в exe. Заодно и форма, и дизайнер форм всегда перед лицом, меньше времязатрат.
А на чистом коде Powershell, я даже не представляю, как вы извращаетесь )))
 
У меня проблемы с размером формы, и я использую для этого искусственный интеллект.
 
Да, все нормально. Извиняюсь, возможно неправильно сохранил.
 
Я не настаиваю, это просто как дружеский совет: под Visual Studio есть дизайнер форм. Под C# там подобную форму можно написать в течении 1-2 минуты. При этом, код будет выглядеть почти одинаково с вашим текущим, т.к. по сути вы используете объекты .NET и здесь, и там. Однако, работать с визуальной частью гораздо проще, особенно с типом проекта Windows Forms, тем более если сложность проекта будет расти.
Единственный минус - объем редактора (около 15 ГБ).

Вижу плюс Powershell в том, что сразу открытый исходный код. Если у вас с ним много опыта и готовых примеров, а форма достаточно простая, то пожалуй в таком случае соглашусь, что это какой-то смысл имеет.
 
Спасибо. Я рассмотрю это.

Я действительно не могу себе представить, чтобы я создавал сценарий, который делал бы нечто большее, чем пару вещей. Я просто склонен заставлять их помогать в тех делах, которые я часто делаю. По сути, это просто экономия времени, уменьшающая количество ошибок в приложениях.
 
Назад
Сверху Снизу