非交互模式的 Powershell 测试 [英] Powershell test for noninteractive mode

查看:45
本文介绍了非交互模式的 Powershell 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以手动运行或由计划任务运行的脚本.我需要以编程方式确定我是在 -noninteractive 模式(通过计划任务运行时设置)还是正常模式下运行.我已经用谷歌搜索了,我能找到的最好的方法是添加一个命令行参数,但我没有任何可行的方法来处理计划任务,也不能合理地期望用户在运行时添加参数手动.非交互模式是否设置了某种变量或我可以在脚本中检查的内容?

I have a script that may be run manually or may be run by a scheduled task. I need to programmatically determine if I'm running in -noninteractive mode (which is set when run via scheduled task) or normal mode. I've googled around and the best I can find is to add a command line parameter, but I don't have any feasible way of doing that with the scheduled tasks nor can I reasonably expect the users to add the parameter when they run it manually. Does noninteractive mode set some kind of variable or something I could check for in my script?

我实际上无意中回答了我自己的问题,但我将它留在这里以供后代使用.

I actually inadvertently answered my own question but I'm leaving it here for posterity.

我在脚本中插入了一个读取主机来询问用户一些事情,当它在非交互模式下运行时,繁荣,终止错误.将其卡在 try/catch 块中,并根据我所处的模式执行操作.

I stuck a read-host in the script to ask the user for something and when it ran in noninteractive mode, boom, terminating error. Stuck it in a try/catch block and do stuff based on what mode I'm in.

不是最漂亮的代码结构,但它有效.如果其他人有更好的方法,请添加它!

Not the prettiest code structure, but it works. If anyone else has a better way please add it!

推荐答案

您可以使用 Get-WmiObject 用于 WMI 对象:

You can check how powershell was called using Get-WmiObject for WMI objects:

(gwmi win32_process | ? { $_.processname -eq "powershell.exe" }) | select commandline

#commandline
#-----------
#"C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe" -noprofile -NonInteractive


更新:2020-10-08


UPDATE: 2020-10-08

从 PowerShell 3.0 开始,此 cmdlet 已被 Get-CimInstance

Starting in PowerShell 3.0, this cmdlet has been superseded by Get-CimInstance

(Get-CimInstance win32_process -Filter "ProcessID=$PID" | ? { $_.processname -eq "pwsh.exe" }) | select commandline

#commandline
#-----------
#"C:\Program Files\PowerShell\6\pwsh.exe"

这篇关于非交互模式的 Powershell 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆