当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 获取变量

作者:精品下载站 日期:2024-12-14 22:01:48 浏览:15 分类:玩电脑

PowerShell 获取变量


Get-Variable cmdlet 用于获取当前范围内的 PowerShell 变量。您只能获取 PowerShell 变量名称或值。

PowerShell 变量是存储值的内存单元。 PowerShell 变量是以美元符号 ($) 开头的文本字符串,例如 $test、$my_func 等。

在本文中,我们将讨论如何使用 Get-Variable cmdlet 在 PowerShell 中获取变量并列出当前作用域中创建的所有变量。

PowerShell 获取变量

PowerShell 中的 Get-Variable cmdlet 会列出变量。

语法

Get-Variable
   [[-Name] <String[]>]
   [-ValueOnly]
   [-Include <String[]>]
   [-Exclude <String[]>]
   [-Scope <String>]
   [<CommonParameters>]

参数

-名称:指定变量的名称。您可以使用通配符来获取变量。

-ValueOnly:获取变量的值。

-范围:指定范围内的变量。可接受的参数值为全局、本地和脚本或数字。

在 PowerShell 中获取变量

使用 Get-Variable cmdlet 获取 PowerShell 中在当前作用域中创建的变量。

Get-Variable proc*

在上面的 PowerShell 脚本中,Get-Variable 获取名称以 proc* 开头的变量。它还获取变量的值。

上述命令的输出显示变量及其值。在下面的输出中,它显示 PowerShell $proces 变量及其值。

[玩转系统] PowerShell 获取变量

按字母获取 PowerShell 变量值

使用 Get-Variable cmdlet ValueOnly 参数,您可以在 PowerShell 中按字母获取变量值。

Get-Variable te* -ValueOnly

在上面的 PowerShell 脚本中,Get-Variable 使用 -ValueOnly 参数来显示名称以 te 开头的变量值。

在 PowerShell 中获取变量值的上述脚本的输出是:

Welcome to
ShellGeek Website

在PowerShell中通过多个字母获取变量

您可以使用 Get-Variable cmdlet 在 PowerShell 中通过多个字母获取变量。

Get-Variable t*, m*

在上面的 PowerShell 脚本中,Get-Variable cmdlet 获取名称以 tm 开头的变量。

上述脚本的输出在 PowerShell 中显示变量及其值。

PS C:\> Get-Variable t*, m*                                                                                             
Name                                    Value
----                                           ----
test                                         Shell
teststring                               Welcome to ...
true                                         True
MaximumAliasCount              4096
MaximumDriveCount              4096
MaximumErrorCount              256
MaximumFunctionCount           4096
MaximumHistoryCount            4096
MaximumVariableCount           4096
my_profile                     ShellGeek
MyInvocation                   System.Management.Automation.InvocationInfo

按范围在 PowerShell 中获取变量

要按范围获取 PowerShell 中的变量,请使用 Get-Variable -Scope 参数。

Get-Variable -Scope Local 

在上面的 PowerShell 脚本中,它获取在本地范围内定义的变量。

结论

希望上面关于如何使用Get-Variable在PowerShell中获取变量的文章对您有所帮助。

您可以使用 Scope 参数查找当前或全局脚本作用域中的变量。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯