Powershell脚本在脚本执行完毕后未保存文本文件

Powershell脚本在脚本执行完毕后未保存文本文件,powershell,Powershell,我有以下简单的脚本,只是提示用户输入文件夹名、文件名,然后输入5个人名。但完成后,文本不会保存在文本文件中。我希望文本文件在重新运行时被擦除,但在我重新运行脚本之前,文本将一直保留在文件中。帮忙 $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

我有以下简单的脚本,只是提示用户输入文件夹名、文件名,然后输入5个人名。但完成后,文本不会保存在文本文件中。我希望文本文件在重新运行时被擦除,但在我重新运行脚本之前,文本将一直保留在文件中。帮忙

$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

正如Etan所评论的,问题在于使用
写主机
。Write-Host cmdlet仅用于向屏幕(PS主机)发送文本,而不通过管道发送数据。事实上,所有PowerShell cmdlet的工作方式都是例外,因为您无法将其导入其他cmdlet。因此,您将文件的内容写入屏幕,然后通过管道将$null传递给Out文件,这将用null数据覆盖您的文件,删除所有内容


如果确实希望文本同时进入屏幕和文件,请按顺序将它们作为两个单独的命令执行,或者查看
Tee对象
cmdlet。

正如Etan所评论的,问题在于使用
写入主机
。Write-Host cmdlet仅用于向屏幕(PS主机)发送文本,而不通过管道发送数据。事实上,所有PowerShell cmdlet的工作方式都是例外,因为您无法将其导入其他cmdlet。因此,您将文件的内容写入屏幕,然后通过管道将$null传递给Out文件,这将用null数据覆盖您的文件,删除所有内容


如果确实希望文本同时进入屏幕和文件,可以将它们作为两个单独的命令依次执行,或者查看
Tee-Object
cmdlet。

在jbsmith的帖子上使用Piggy backing,只需将最后一行更改为:

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

这将导致输出到屏幕,并按照您的要求在文本文件中结束。

在jbsmith的文章中,只需将最后一行更改为:

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

这将导致输出到屏幕,并在文本文件中结束,根据您的请求。

使用除写入主机以外的其他方法写入管道。如果您从用户输入中获取文件名,您如何知道下次运行时要删除哪个文件?这是假设用户选择了相同的文件名和文件夹名。否则,它只会使新数据使用非
写入主机
的内容写入管道。如果从用户输入中获取文件名,您如何知道下次运行时要删除哪个文件?这是假设用户选择了相同的文件名和文件夹名。否则它只会生成新数据