将脚本输出到新的未保存的文本文件

时间:2018-09-20 08:06:42

标签: powershell powershell-v3.0 notepad

我在远程服务器上执行一些命令,并将输出保存到新的文本文件中。这里的问题是我想保留将文本文件保存或抓取给用户本身的选项。我被困在如何将所有输出写入新的记事本文件中。我也不确定是否可以将输出写入相同的未保存的记事本文件中。

当前$item的输出

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

必填:

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

我可以调用它,但不知道如何将foreach循环的输出写入此记事本实例。

3 个答案:

答案 0 :(得分:0)

我会做这样的事情:

$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"
}

答案 1 :(得分:0)

这是一个基于here的脚本。 我对其进行了修改,以允许您重新使用对应用程序的引用,以便您可以对同一方法进行后续调用,并访问同一记事本实例。此版本还允许您追加到记事本实例。这样一来,内容就不会在每次调用时都被覆盖(尽管如果希望新文本替换现有内容,则可以包含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

答案 2 :(得分:-1)

作为参考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)
  }
}