简体   繁体   中英

Write-Output without a newline in Powershell?

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"

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++}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM