我希望我的PowerShell脚本打印如下内容:
Enabling feature XYZ......Done
该脚本如下所示:
Write-Output "Enabling feature XYZ......."
Enable-SPFeature...
Write-Output "Done"
但是Write-Output
总是在末尾打印一个新行,所以我的输出不是在一行上。有没有办法做到这一点?
发布于 2015-09-15 22:05:10
不幸的是,正如在一些回答和评论中指出的那样,Write-Host
可能是危险的,并且不能通过管道传输到其他进程,并且Write-Output
没有-NoNewline
标志。
但这些方法是显示进度的"*nix“方式," PowerShell”方式似乎是Write-Progress
:它在PowerShell窗口的顶部显示进度信息栏,从PowerShell 3.0开始提供,see manual提供详细信息。
# Total time to sleep
$start_sleep = 120
# Time to sleep between each notification
$sleep_iteration = 30
Write-Output ( "Sleeping {0} seconds ... " -f ($start_sleep) )
for ($i=1 ; $i -le ([int]$start_sleep/$sleep_iteration) ; $i++) {
Start-Sleep -Seconds $sleep_iteration
Write-Progress -CurrentOperation ("Sleep {0}s" -f ($start_sleep)) ( " {0}s ..." -f ($i*$sleep_iteration) )
}
Write-Progress -CurrentOperation ("Sleep {0}s" -f ($start_sleep)) -Completed "Done waiting for X to finish"
以OP的例子为例:
# For the file log
Write-Output "Enabling feature XYZ"
# For the operator
Write-Progress -CurrentOperation "EnablingFeatureXYZ" ( "Enabling feature XYZ ... " )
Enable-SPFeature...
# For the operator
Write-Progress -CurrentOperation "EnablingFeatureXYZ" ( "Enabling feature XYZ ... Done" )
# For the log file
Write-Output "Feature XYZ enabled"
发布于 2013-02-14 10:00:29
虽然它在您的情况下可能不起作用(因为您向用户提供了信息性输出),但您可以创建一个可用于附加输出的字符串。当需要输出时,只需输出字符串即可。
当然,忽略这个例子在你的例子中是愚蠢的,但在概念上是有用的:
$output = "Enabling feature XYZ......."
Enable-SPFeature...
$output += "Done"
Write-Output $output
显示:
Enabling feature XYZ.......Done
发布于 2012-03-06 19:34:42
要写入文件,可以使用字节数组。下面的示例创建一个空的ZIP文件,您可以向其中添加文件:
[Byte[]] $zipHeader = 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
[System.IO.File]::WriteAllBytes("C:\My.zip", $zipHeader)
或使用:
[Byte[]] $text = [System.Text.Encoding]::UTF8.getBytes("Enabling feature XYZ.......")
[System.IO.File]::WriteAllBytes("C:\My.zip", $text)
https://stackoverflow.com/questions/3896258
复制相似问题