Average Rating:

3.50 by 2 users.

31 Downloads, 70 Views

1 Comment(s)

bpfinn_adv10.ps1

By: 98d0d0c4b2ec3108763ceb1cc9a64141 18 Apr 2011 07:19 PM UTC in the category: Advanced Event 10

Description:

This script creates a temporary text file in the current user's temporary directory. It accepts piped input and places it in this file. If you provide the -OpenInNotepad argument, the script will open the temporary file that has just been created in Notepad.


# 2011 Scripting Games
# Advanced Event #10
# Written by Brian Finn
# Written on April 18, 2011
# Due Date: April 22, 2011

function create-temptextfile
{
  <#
    .SYNOPSIS
     
     Creates a temporary file in which to put text data.

    .DESCRIPTION

     This script creates a temporary text file in the current user's temporary directory. It accepts piped input
     and places it in this file. If you provide the -OpenInNotepad argument, the script will open the temporary
     file that has just been created in Notepad.

    .EXAMPLE
    get-content "somefile.txt" | create-temptextfile

    .EXAMPLE
    get-content "somefile.txt" | create-temptextfile -OpenInNotepad $true

  #>
  param(
    [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
    [PSObject[]]$InputObject,
    [Parameter(Mandatory=$false, Position=1)]
    $OpenInNotepad
  )
  begin
  {
    $tempdir = $env:temp
    $random = New-Object System.Random
    $randomnumberstring = $random.Next(1,65000).ToString()
    $randomfilename = "temp_" + $randomnumberstring + ".txt"
    $fullfilepath = $tempdir + "\" + $randomfilename
  }
  process
  {
    out-file -filepath $fullfilepath -append -encoding ASCII -inputObject $InputObject
  }
  end
  {
    if ($OpenInNotepad -eq $true)
    {
      start-process -FilePath "notepad.exe" -ArgumentList $fullfilepath
    }
    $fullfilepath
  }
}

get-content ".\machines_adv10.txt" | create-temptextfile -OpenInNotepad $true

Top

Comments:

4/24/2011 7:43 PM
Your script works
One thing to consider.. If you want to create temp files there is actually a function for doing so [System.IO.Path]::GetTempFileName()