PSConsoleReadLine的奇怪行为

时间:2019-04-11 07:57:28

标签: powershell

试图在Powershell控制台中生成文本(结果是预先确定的),由于不断闪烁,所以不喜欢cls + Write-Host,尝试使用PSConsoleReadLine。下面的代码在某些情况下有效,而在其他情况下则无效。

代码在以下情况下有效:

  • 直接复制粘贴到Powershell窗口中

  • 存储在脚本文件中并从Powershell窗口调用该文件时

在以下情况下代码不起作用

  • 在ISE中推出(已知问题)

  • 右键单击脚本文件/使用powershell运行

试图通过Add-Type解决该错误,但是它以IOException和null引用结尾。出现在下面的代码中,但已注释。

试图以一种在新的Powershell流程中重新启动自身来处理该脚本的方式编写脚本,没有帮助。

代码本身(可能可以用一行代码来重现该问题,但指南说一行代码是不够的):

 function tryOne($oldExpression, $targetExpression, $currentPosition, $src)
{ 
    While($targetExpression[$currentPosition] -cne $triedCharacter)
    {
        [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()#here problem
        $triedCharacter = Get-Random -InputObject $src
        $expression = $oldExpression + $triedCharacter
        [Microsoft.PowerShell.PSConsoleReadLine]::Insert($expression)#here problem
        Start-sleep -Milliseconds 50
    }
    Return $expression
}
cd $PSScriptRoot
#Add-Type -path "C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.2\Microsoft.PowerShell.PSReadLine.dll"
#above helps with not found error, with it uncommented the errors at RevertLine and Insert are IOException and null reference
$targetExpression = "Not ideal"
$oldExpression = ""
$currentPosition = 0

#region AllowedCharacters
    $src = New-Object System.Collections.ArrayList
    for($i=65;$i-le 90;$i++)
    {
        $src.Add([char]$i) | Out-Null
    }
    for($i=97;$i-le 122;$i++)
    {
        $src.Add([char]$i) | Out-Null
    }
    for($i=0;$i-le 9;$i++)
    {
        $src.Add($i) | Out-Null
    }
    $src.Add(" ") | Out-Null #allowed characters in the target sentence - A-Z, a-z, 0-9, space
#endregion

While($currentPosition -lt ($targetExpression.length))
{
$oldExpression = tryOne $oldExpression $targetExpression $currentPosition $src
$currentPosition++;
}

我希望能够通过右键单击/使用Powershell运行来启动脚本。

0 个答案:

没有答案
相关问题