首页 > 解决方案 > 在脚本块内使用脚本中的变量

问题描述

我正在尝试编写一个将注销当前登录用户的 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]) 有效,但会断开随机用户的连接。

我显然做错了什么,但我不明白为什么。脚本的行为可能不像我认为的那样。

谢谢!

标签: powershellinvoke-command

解决方案


感谢Theo,我想通了。我在脚本中使用的$Username变量未正确传递给脚本块。我必须在脚本块内重新定义一个参数,然后使用-ArgumentfromInvoke-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 和其他所有人的帮助!


推荐阅读