我正在编写一个PowerShell脚本来删除各种文件,并且想要编写一个函数来提示用户完成每个文件删除的百分比,以便用户不会认为脚本已崩溃。而不是像{000000 ....这样的进度条。我宁愿屏幕打印出诸如10%完成的百分比数字。
#Variables
$Comp_Name = $env:COMPUTERNAME
$DateTime = Get-Date -Format "DMM-dd-yyyy_THH-mm-ss"
#Log Errors
Start-Transcript -Path C:\TEMP\error_Log-$Comp_name-$DateTime.log -Append
# Get the date and time and remove the directory specified in the function
Function Remove-Directory
{
Param([string]$Location)
$files = Get-ChildItem -Path $Location -Recurse | Where-Object {!$_.PSIsContainer}
for ($i = 1; $i -lt $Files.count; $i++) {
Write-Progress -Activity 'Deleting files...' -Status $Files[$i].FullName -PercentComplete ($i / ($Files.Count*100))
Try
{
Get-ChildItem $Location -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue -Verbose 4>&1 | Add-Content C:\TEMP\ModifiedData-$Comp_Name-$DateTime.log
#Write-Output "SUCCESS: $Location has been been Modified Successfully"
}
Catch{Write-Output "ERROR: $Location could be Modified. Please Verify This Location Manually."}
}
}
#Remove the below files from computer
If ($Comp_Name -eq "X")
{
Remove-Directory "C:\Users\X"
}
Stop-Transcript
Write-Output "Script Process Complete. Please Check logs for additional details"
答案 0 :(得分:2)
除了使用-percentcomplete
之外,您还可以使用其他状态指示器之一
-CurrentOperation "($i / ($Files.Count*100))% complete"
您可能希望将百分比四舍五入或强制转换为整数,例如:
-CurrentOperation "$([int]($i / $Files.Count*100))% complete"
参数显示的顺序如下,因此根据您希望消息层次结构的显示方式使用哪个参数。
-Activity
-Status
-CurrentOperation