3

I'm writing a small script that checks for the existence of directories, and if they exist then delete them. I am trying to have informative output, and as such I want to output a confirmation when a folder is deleted:

foreach ($e in $directoriesToRemove)
    {
        Write-Output "Deleting $e`..."
        Remove-Item $e -recurse
        Write-Output "Done"
    }

The output of this being:

Deleting C:\wherever\folder1...
Done
Deleting C:\wherever\folder2...
Done

While I am aiming for:

Deleting C:\wherever\folder1... Done
Deleting C:\wherever\folder2... Done

I understand that Write-Host can be used to achieve this with the -nonewline parameter, but I would like to avoid using Write-Host if possible.

Is there a workaround for this other than waiting until a folder is deleting and writing the entire line at once? I've found that this line works, but I don't know if putting a delete command inside a Write-Output command is safe/best practice:

Write-Output "Deleting $e`... $(Remove-Item $e -recurse) Done"
1
  • 2
    No, AFAIK. Also, putting the command inside will simply evaluate it before write-output is executed. Commented Nov 8, 2016 at 3:31

1 Answer 1

4

Here is the difference between the two CmdLets

Write-Output should be used when you want to create an object to send data in the pipe line, but not necessarily want to display it on the screen. The pipeline will eventually write it to out-default if nothing else uses it first.

Write-Host should be used when you want to do the opposite. [console]::WriteLine is essentially what Write-Host is doing behind the scenes

In my understanding what you ask can be translated as trying to concatenate two strings in the pipe, it can be done but why do not use Write-host here ?

$(foreach ($a in $animals){Write-Output "buying a $a"; Write-Output " ... done"}) | % {$action="";$i=0}{if(($i%2) -eq 0){$action=$_}else{Write-Output "$action $_"};$i++}
Sign up to request clarification or add additional context in comments.

Comments