尝试在c:\上自动运行chkdsk

时间:2019-05-10 20:19:50

标签: powershell sendkeys

尝试在计算机的所有驱动器上运行chkdsk。遇到C:\问题。

尝试使用SendKeys回答“您是否希望安排该卷在下次系统重新启动时进行检查?(是/否)”,但是没有运气。我要去哪里错了?

$host.ui.RawUI.WindowTitle = "BOHCdrivefix"

$FixCDrive = Start-Job -Name cDriveFix -ScriptBlock {chkdsk c:/f} 
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('BOHCdrivefix')
sleep 3
$wshell.SendKeys('y') 
$wshell.SendKeys('~')
wait-job $FixCDrive
Receive-Job $FixCDrive | Out-File -FilePath D:\temp\cDriveFix.txt
shutdown -r -f -t 0

我想对这个问题回答Y,然后关闭PC并启动chkdsk

1 个答案:

答案 0 :(得分:0)

来自Start-Job document

  

Start-Job cmdlet在以下位置启动Windows PowerShell后台作业   本地计算机。

     

Windows PowerShell后台作业运行命令而没有   与当前会话进行交互

因此,您不能将当前会话中的任何键发送到后台作业中运行的命令。发送密钥必须在后台作业内部。幸运的是,chkdsk.exe接受pipeline operator的使用(将前一个命令的结果发送到下一个命令),如下所示:

$FixCDrive = Start-Job -Name cDriveFix -ScriptBlock {Write-Output 'y'|chkdsk.exe c:/f}

或(对于echo cmdlet使用Write-Output别名):

$FixCDrive = Start-Job -Name cDriveFix -ScriptBlock {echo 'y'|chkdsk.exe c:/f}

请注意

The type of the file system is NTFS.
Cannot lock current drive.

Chkdsk cannot run because the volume is in use by another
process.  Would you like to schedule this volume to be
checked the next time the system restarts? (Y/N)

要对chkdsk c:/f提出的上述问题回答“是”(启动分区上的修复文件系统错误),必须按 Y ,然后按 Enter

老实说,我不确定Write-Output cmdlet是否将 Enter 发送到管道中。如果不是,则强制输出新行,如下所示:

Write-Output "y$([System.Environment]::NewLine)"|chkdsk.exe c:/f}