Вывод скрипта в новый несохраненный текстовый файл - PullRequest
0 голосов
/ 20 сентября 2018

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

в настоящее время $item имеет вывод

$item >> C:\Users\Documents\$(get-date -f yyyy-MM-dd).txt

обязательно:

$x = Start-Process 'C:\windows\system32\notepad.exe'

Я могу вызвать его, но не знаю, как записать вывод из цикла foreach в этот экземпляр блокнота.

Ответы [ 3 ]

0 голосов
/ 20 сентября 2018

Вот скрипт на основе одного здесь .Я изменил его, чтобы позволить вам повторно использовать ссылку на приложение, чтобы вы могли делать последующие вызовы одного и того же метода и получать доступ к одному и тому же экземпляру блокнота.Эта версия также позволяет добавлять к экземпляру блокнота;чтобы контент не перезаписывался при каждом вызове (хотя вы можете включить параметр Flush, если хотите, чтобы новый текст заменял существующий контент; как если бы вы сначала запускали команду Clear-Notepad.

Поскольку эта версия позволяет вам передавать Process, чтобы разрешить повторное использование существующего экземпляра блокнота (без риска захвата любого произвольного запущенного экземпляра блокнота путем извлечения любого экземпляра блокнота из запущенных процессов), я имею в видутакже оставлена ​​возможность использовать любой процесс, так что вы можете использовать другую программу, если хотите ... Однако этот скрипт не тестируется для других программ / не имеет специальной логики для их обслуживания, поэтому должен быть протестировандля приложений перед использованием с ними.

#requires -Version 2

#based on Out-Notepad script from http://community.idera.com/powershell/powertips/b/tips/posts/send-text-to-notepad; only amended to allow appending.
function Out-Application {
    [CmdletBinding(DefaultParameterSetName = 'ByString')]
    Param (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName = 'ByString')]
        [AllowEmptyString()] 
        [String]$InputString
        ,
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName = 'ByObject')]
        [AllowEmptyString()] 
        [PSObject]$InputObject
        ,
        [Parameter(Mandatory=$false, ValueFromPipeline=$false)]
        [System.Diagnostics.Process]$TargetApplication = (Start-Process 'notepad' -PassThru) #default the target application to a new instance of notepad
        ,
        [Parameter(Mandatory=$false, ValueFromPipeline=$false)]
        [String]$SubWindowName = "Edit" #this is the notepad edit box; for other apps we may want a different class/window name (or this may be completely innappropriate; only really designed for notepad, but with some pieces left flexible in case we can re-use elsewhere)
        ,
        [Parameter(Mandatory=$false, ValueFromPipeline=$false)]
        [Switch]$ReturnProcess
        ,
        [Parameter(Mandatory=$false, ValueFromPipeline=$false)]
        [Switch]$Flush
    )
    begin {
        [int]$WM_SETTEXT = 0x000C
        [int]$WM_GETTEXTLENGTH = 0x000E
        [int]$EM_SETSEL = 0x00B1
        [int]$EM_REPLACESEL = 0x00C2
        [Type]$winApi = 'Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes.APISendMessage' -as [Type]
        if ($winApi -eq $null) {
            $winApiImports = '
                [DllImport("user32.dll", EntryPoint = "FindWindowEx")]public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
                [DllImport("User32.dll", EntryPoint = "SendMessage")]public static extern int SendMessageGetTextLength(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
                [DllImport("User32.dll", EntryPoint = "SendMessage")]public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
            '
            $winApi = Add-Type -MemberDefinition $winApiImports -Name APISendMessage -PassThru
        }
    }
    process {
        [pscustomobject]$pipelineOutput = [pscustomobject]@{}
        if ($PSCmdlet.ParameterSetName -eq 'ByObject') {
            $pipelineOutput | Add-Member -MemberType 'NoteProperty' -Name 'InputObject' -Value $InputObject
            $InputString = $InputObject | Format-List | Out-String
        } else {
            $pipelineOutput | Add-Member -MemberType 'NoteProperty' -Name 'InputString' -Value $InputString
        }
        if ($ReturnProcess) {
            $pipelineOutput | Add-Member -MemberType 'NoteProperty' -Name 'TargetApplication' -Value $TargetApplication        
        }
        $TargetApplication.WaitForInputIdle() | Out-Null
        $hwnd = $TargetApplication.MainWindowHandle
        [IntPtr]$childWindow = $winApi::FindWindowEx($hwnd, [IntPtr]::Zero, $SubWindowName, $null) 
        if ($Flush) {
            #specifying flush removes all content and pastes the new data in its place; useful if you wanted to watch the latest value in notepad without having a historic feed
            $winApi::SendMessage($childWindow, $formFeed, [IntPtr]::Zero, $InputString) | Out-Null
        } else {
            #if not flushing then we append content after existing content
            [int]$length = $winApi::SendMessageGetTextLength($childWindow, $WM_GETTEXTLENGTH, [IntPtr]::Zero, [IntPtr]::Zero)
            $winApi::SendMessage($childWindow, $EM_SETSEL, $length, $length) | Out-Null
            $winApi::SendMessage($childWindow, $EM_REPLACESEL, 1, $InputString) | Out-Null
        }
        $pipelineOutput
    }
}
Clear-Host
$notepad = Get-Process | Out-String | Out-Application -ReturnProcess | Select-Object -ExpandProperty 'TargetApplication' -First 1
Get-Service | Out-Application -TargetApplication $notepad | Out-Null
0 голосов
/ 20 сентября 2018

как ref http://community.idera.com/powershell/powertips/b/tips/posts/out-notepad-send-information-to-notepad

  requires -Version 2
    function Out-Notepad
{
  param
  (
    [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
    [String]
    [AllowEmptyString()] 
    $Text
  )

  begin
  {
    $sb = New-Object System.Text.StringBuilder
  }

  process
  {
    $null = $sb.AppendLine($Text)
  }
  end
  {
    $text = $sb.ToString()

    $process = Start-Process notepad -PassThru
    $null = $process.WaitForInputIdle()


    $sig = '
      [DllImport("user32.dll", EntryPoint = "FindWindowEx")]public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
      [DllImport("User32.dll")]public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
    '

    $type = Add-Type -MemberDefinition $sig -Name APISendMessage -PassThru
    $hwnd = $process.MainWindowHandle
    [IntPtr]$child = $type::FindWindowEx($hwnd, [IntPtr]::Zero, "Edit", $null)
    $null = $type::SendMessage($child, 0x000C, 0, $text)
  }
}
0 голосов
/ 20 сентября 2018

Я бы сделал что-то вроде этого:

$Trace = "Start log`r`n"

#Do stuff

$Trace += "Log output`r`n"

if ($UserInput -eq $true) {
    $Trace | Out-File -FilePath "YourFile"
}

РЕДАКТИРОВАТЬ

Это быстрое решение, как отображать текст в облаке, не записывая его в файл испросите пользователя потом.

$Trace | Out-GridView -Wait

$Result = [System.Windows.Forms.MessageBox]::Show("Do you want to save the file","Save",1)

If ($Result -eq "Yes")
{
    $Trace | Out-File -FilePath "YourPath"
}
...