我在编写的多个脚本中都遇到过这个问题,我不太清楚为什么会发生这种情况,但我会遇到类似以下情况:
#What Server
$Server = Read-Host "Enter the name of the target server: "
#Get initial volume info
$IDisk = invoke-command -ComputerName $server -ScriptBlock{Get-volume}
$IDisk
#Ask which disk to expand
$WhatDisk = Read-Host "Which disk would you like to expand: "
#Update the disk info
Invoke-Command -ComputerName $server -ScriptBlock{Update-HostStorageCache}
#Display before and after for the target drive
Write-Host "Disk $WhatDisk is currently: " -ForeGroundColor "Cyan"
$IDisk | Select DriveLetter, FileSystemLabel, @{Name='Size(GB)';Exp={$_.Size /1gb -as [int]}} | Where {$_.DriveLetter -eq $WhatDisk}
脚本不会在下一次输出之后输出来自 $IDisk 的信息。例如:
Enter the name of the target server: : server443
Which disk would you like to expand: : l
Disk l is currently:
DriveLetter FriendlyName FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining Size
----------- ------------ -------------- --------- ------------ ----------------- ------------- ----
E (V2) NTFS Fixed Healthy OK 12.75 GB 24.98 GB
L (V3) NTFS Fixed Healthy OK 1.89 GB 1.98 GB
U (V5) NTFS Fixed Healthy OK 2.04 GB 4.98 GB
P (V4) NTFS Fixed Healthy OK 18.99 GB 19.98 GB
Z (V6) NTFS Fixed Healthy OK 4.06 GB 4.98 GB
B Unknown CD-ROM Healthy Unknown 0 B 0 B
System Reserved NTFS Fixed Healthy OK 67.12 MB 100 MB
C NTFS Fixed Healthy OK 32.12 GB 79.33 GB
NTFS Fixed Healthy OK 114.61 MB 578 MB
DriveLetter : L
FileSystemLabel : (V3)
Size(GB) : 2
有人知道为什么 $IDisk 的输出被保留到下一次输出被调用(在本例中是第二次调用 $IDisk)为止?我该如何阻止这种情况发生?
再说一次,这只是一个例子,但我在这方面遇到了很多麻烦。
答案1
像您这样的表格格式的间接控制台输出$IDisk
在 Powershell 中稍微异步,并且与其他输出混合时有时会在控制台窗口中无序显示。
Out-Host
要修复此问题,您可以通过将输出传输到以下位置或类似方式强制 powershell 预先进行格式化Format-Table
:
#Get initial volume info
$IDisk = invoke-command -ComputerName $server -ScriptBlock{Get-volume}
$IDisk | Out-Host
#Ask which disk to expand
$WhatDisk = Read-Host "Which disk would you like to expand: "
这里有关于此行为的详尽解释:https://stackoverflow.com/a/43691123/7411885