0

I have the following simple script just prompting a user for a folder name, file name and then 5 names of people. But after I am done, the text is not saved inside the text file. I'd like for the text file to be erased when it is rerun but to have the text in the file until I rerun the script. Help?

$folderName = Read-Host "Please enter the name you want the new folder to have: "
$fileName = Read-Host "Please enter the name you want the new file to have: "
$count = 1
$folder = New-Item C:\Users\Administrator\Desktop  -ItemType directory -Name $folderName -force
$file = New-Item C:\Users\Administrator\Desktop\$folderName\$fileName.txt  -ItemType file -force
while($count -lt 6){
    $name = Read-Host "Please enter the name for person" $count
    $name | Add-Content $file 
    $count++
}
$display = Read-Host "How many names from 1 to 5 would you like to see? "
Write-Host (Get-Content $file -TotalCount $display | Out-String)  "`n", "`r`n" | Out-File $file
3
  • Use something other than Write-Host to write to the pipeline. Commented Mar 24, 2015 at 15:53
  • How will you know which file to delete on the next run if you're taking the file name from user input? Commented Mar 24, 2015 at 15:57
  • This is assuming that the user chose the same file name and same folder name. Otherwise it will just make the new data Commented Mar 24, 2015 at 16:12

2 Answers 2

2

The problem, as Etan commented, is the use of Write-Host. The Write-Host cmdlet is intended solely for sending text to the screen (the PS host), and does NOT send data on through the pipeline. It's an exception to how virtually all PowerShell cmdlets work, in that you can't pipe it into other cmdlets. So you're writing the contents of the file to the screen, then passing $null on through the pipeline to Out-File, which overwrites your file with null data, deleting all the contents.

If you really want the text to go to both the screen and the file, either do them as two separate commands in sequence, or look at the Tee-Object cmdlet.

Sign up to request clarification or add additional context in comments.

Comments

2

Piggy-backing on jbsmith's post, simply change the final line to this:

Write-Output (Get-Content $file -TotalCount $display | Out-String)  "`n", "`r`n" | Tee-object -File $file -Append

Which will result in output to screen and also ending up in the text file, as you've requested.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.