powershell - 在脚本块内使用脚本中的变量
问题描述
我正在尝试编写一个将注销当前登录用户的 Powershell 脚本。我Invoke-Command
在脚本内使用带有脚本块的 cmdlet。
我在脚本中定义了一些我试图传递给脚本块的参数,但我完全可以让它工作。
这是脚本:
param(
[Parameter()]
[string]$ComputerName,
[Parameter()]
[string]$Username
)
$ScriptBlock = {
$ErrorActionPreference = 'Stop'
try {
## Find all sessions matching the specified username
$sessions = quser | Where-Object {$_ -match "$args[0]"}
## Parse the session IDs from the output
$sessionIds = ($sessions -split ' +')[2]
Write-Host "Found $(@($sessionIds).Count) user login(s) on computer."
## Loop through each session ID and pass each to the logoff command
$sessionIds | ForEach-Object {
Write-Host "Logging off session id [$($_)]..."
logoff $_
}
} catch {
if ($_.Exception.Message -match 'No user exists') {
Write-Host "The user is not logged in."
} else {
throw $_.Exception.Message
}
}
}
Invoke-Command -ComputerName $ComputerName -Argumentlist $Username -ScriptBlock $ScriptBlock
我正在启动这样的脚本:
.\Logoff-User.ps1 -Computername some_server -Username some_user
现在这实际上有效,但它注销了一个随机用户(可能不是随机的)。
我理解它的方式是 (the $Username
) 变量-ArgumentList
被传递给脚本块,它似乎被正确解释。我可以使用进一步向下打印出$args
变量Write-Host
并返回正确的用户名。
仅使用$args
错误输出但指定第一个位置 ( $args[0]
) 有效,但会断开随机用户的连接。
我显然做错了什么,但我不明白为什么。脚本的行为可能不像我认为的那样。
谢谢!
解决方案
感谢Theo,我想通了。我在脚本中使用的$Username
变量未正确传递给脚本块。我必须在脚本块内重新定义一个参数,然后使用-Argument
fromInvoke-Command
将变量作为字符串传递(第一个脚本也没有这样做。
这是最终的脚本:
param(
[Parameter()]
[string]$ComputerName,
[Parameter()]
[string]$Username
)
$ScriptBlock = {
param($User)
$ErrorActionPreference = 'Stop'
try {
## Find all sessions matching the specified username
$sessions = quser | Where-Object {$_ -match $User}
## Parse the session IDs from the output
$sessionIds = ($sessions -split ' +')[2]
Write-Host "Found $(@($sessionIds).Count) user login(s) on computer."
## Loop through each session ID and pass each to the logoff command
$sessionIds | ForEach-Object {
Write-Host "Logging off session id [$($_)]..."
logoff $_
}
} catch {
if ($_.Exception.Message -match 'No user exists') {
Write-Host "The user is not logged in."
} else {
throw $_.Exception.Message
}
}
}
Invoke-Command -ComputerName $ComputerName -Argumentlist $Username -ScriptBlock $ScriptBlock
然后我可以根据需要运行脚本:
.\Logoff-User.ps1 -Computername some_server -Username some_user
感谢 Theo 和其他所有人的帮助!
推荐阅读
- setup.py - 是否可以在 wheel/bdist/sdist 中包含 Python 包之外的文件?
- amazon-web-services - gulp-awspublish 使用 AWS 配置文件而不是 AWS_ACCESS_KEY 和秘密
- html - 将整个页面缩小为一个 div
- c# - 如何检查是否在 KeyUp 事件的文本框中输入了数字或字母
- flutter - 设备锁定时颤动动画侦听器不起作用
- eclipse - 限制 Eclipse RCP 项目中打开的选项卡
- r - 根据日期/时间范围和匹配 id 过滤数据
- java - 如何解决读取 JSON 文件以获取名字和姓氏的失败执行?
- oracle - 使用 Cursor 的 SQL 问题 - 进行第一次交易的案例研究
- javascript - 是否可以限制本地开发服务器的上传速度?