Reputation: 17
This is my code: It runs correctly but it prints my content together. I was told to use the Write-ouput command and write an empty string but its not coming out right. Does anyone have any suggestions
$file1='/Users/raelynsade/Documents/cpt180stuff/pets/dogs/dognames.txt'
$file2='/Users/raelynsade/Documents/cpt180stuff/pets/cats/catnames.txt'
$fileExist = (Test-Path -Path $file1) -AND (Test-Path -Path $file2)
if ($fileExist -eq $True) {
$file_content = Get-Content -Path $file1
Write-output -InputObject $file_content
$file_content = Get-Content -Path $file2
Write-output -InputObject $file_content
Add-Content -Path "/Users/raelynsade/Documents/cpt180stuff/pets/cats/catnames.txt"
-Value "Sammy"
Add-Content -Path "/Users/raelynsade/Documents/cpt180stuff/pets/cats/catnames.txt"
-Value "Luna"
Get-Content -Path "/Users/raelynsade/Documents/cpt180stuff/pets/cats/catnames.txt" } else {
Write-output -Inputobject "Unable to access one or more files" }
Upvotes: 0
Views: 47
Reputation: 17472
something like this?
$file1='/Users/raelynsade/Documents/cpt180stuff/pets/dogs/dognames.txt'
$file2='/Users/raelynsade/Documents/cpt180stuff/pets/cats/catnames.txt'
$fileExist = (Test-Path -Path $file1) -AND (Test-Path -Path $file2)
if ($fileExist)
{
#content to dog file
Get-Content -Path $file1
" "
#content to cat file with new values added
Add-Content -Path $file2 -Value "Sammy" ,"Luna"
Get-Content -Path $file2
}
else
{
"Unable to access one or more files"
}
Upvotes: 0
Reputation: 8868
If you put powershell's implicit output to work for you and enclose it all in a subexpression $(...)
then you can combine all the lines as you desire and output once. Add the -Passthru
parameter of Set-Content
and you don't need to read the file again after writing.
$file1='/Users/raelynsade/Documents/cpt180stuff/pets/dogs/dognames.txt'
$file2='/Users/raelynsade/Documents/cpt180stuff/pets/cats/catnames.txt'
$fileExist = (Test-Path -Path $file1) -AND (Test-Path -Path $file2)
if ($fileExist -eq $True){
$(Get-Content -Path $file1
""
Get-Content -Path $file2
"Sammy"
"Luna") | Set-Content -Path "/Users/raelynsade/Documents/cpt180stuff/pets/cats/catnames.txt" -PassThru
} else {
"Unable to access one or more files"
}
Upvotes: 1