在 PowerShell 中,如何测试全局范围内是否存在特定变量? [英] In PowerShell, how do I test whether or not a specific variable exists in global scope?
问题描述
我将 PowerShell 脚本用于 WPF 应用程序的某些 UI 自动化.通常,脚本根据全局变量的值作为一个组运行.当我只想运行一个脚本时,手动设置这个变量有点不方便,所以我正在寻找一种方法来修改它们以检查这个变量并在找不到时设置它.
I'm using PowerShell scripts for some UI automation of a WPF application. Normally, the scripts are run as a group, based on the value of a global variable. It's a little inconvenient to set this variable manually for the times when I want to run just one script, so I'm looking for a way to modify them to check for this variable and set it if not found.
test-path variable:\foo 似乎不起作用,因为我仍然收到以下错误:
test-path variable:\foo doesn't seem to work, since I still get the following error:
无法检索变量$global:foo",因为它尚未设置.
The variable '$global:foo' cannot be retrieved because it has not been set.
推荐答案
使用 stej 的回答 下面.我自己的(部分不正确)仍然在这里转载以供参考:
Use stej's answer below. My own (partially incorrect) one is still reproduced here for reference:
你可以使用
Get-Variable foo -Scope Global
并捕获变量不存在时引发的错误.
and trap the error that is raised when the variable doesn't exist.
这篇关于在 PowerShell 中,如何测试全局范围内是否存在特定变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!