如何在一个代码中执行脚本,在其中具有Write-Host命令的powershell shell?

我有一个我正在写的脚本,依赖于导入模块中的功能.由于IO(Web请求),这个脚本需要一段时间,我希望将其脚本块迭代数十万次.

在尝试了几种不同的方法(由于启动作业和其他事情的限制而取得的成功并不大)当前的实现依赖于通过$shell = [Powershell] :: Create()创建一个由“shell”组成的池.

我必须调用以引导shell(因此处于正确状态)的模块方法之一就是调用Write-Host.当我调用$shell.Invoke()时,会发生以下错误

Write-Host : A command that prompts the user Failed because the host program or the command type does not support user
interaction. Try a host program that supports user interaction,such as the Windows PowerShell Console or Windows
PowerShell ISE,and remove prompt-related commands from command types that do not support user interaction,such as
Windows PowerShell workflows.

现在,由于该模块是自定义的,我可以删除Write-Host调用,但是当终端用户直接运行时,可以降低用户友好性.如果参数为true,我可以创建一个不执行Write-Host的开关参数,但是要做到这一点,这是一个很好的工作(可行,但我宁愿不).

有什么办法可以让Write-Host在这种情况下不会出错吗?在这种情况下,我并不关心输入,我只是不想要错误.

让这个工作最快的方法是在脚本中定义一个虚拟的写入主机功能,或者在运行脚本之前,在runspace中单独定义它.
$ps.addscript("function write-host {}").invoke()
$ps.commands.clear()
# Now you can invoke scripts that use write-host
# feel free to implement a write-host that writes to a log file

就那么简单.你得到这个错误的原因是因为这样的程序化调用并不期望用户交互.有办法使这项工作,但它使用不同的API.

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...