【发布时间】:2020-06-19 02:41:11
【问题描述】:
我正在尝试编写简单的脚本来提高我的 powershell 能力,我想我经常做的事情是通过服务器管理器或远程 powershell 会话来停止我们的 RDS 服务器以应用更新等。
我尝试根据我的输入编写一个脚本来执行此操作,但无论我做什么,变量的内容都不会传递到远程服务器。
脚本只是询问您希望更改哪个服务器,您希望将其更改为何种状态,将两者的值结合起来,然后将其传递到远程服务器。
唉……什么都没有。代码如下。任何指针将不胜感激。
$SessionHosts = "Server_1", "Server_2", "Server_3", "Server_4"
$OpeningSalvo = Read-Host -Prompt "[Q]uery Servers or [C]hange State?"
If ($OpeningSalvo -match "q")
{
Invoke-Command $SessionHosts {chglogon.exe /query}
}
Elseif ($OpeningSalvo -match "c")
{
$Server = Read-Host -Prompt "Server Name?"
$State = Read-Host -Prompt "Enable, Drain, Drainuntilrestart or Disable"
$Run = "chglogon.exe /" + "$State"
#Invoke-Command -ComputerName $Server -ScriptBlock {Write-Host $Fun $using:Run echo $Fun}
#$ScriptBlockContent1 = {param ($Run) Write-Host $Run}
#Invoke-Command $Server $ScriptBlockContent1 -ArgumentList $Run
$ScriptBlockContent1 = {param ($Run) Write-Output $Run}
Invoke-Command $Server $ScriptBlockContent1 -ArgumentList $Run
$ScriptBlockContent2 = {Write-Host $Run}
Invoke-Command $Server $ScriptBlockContent2
}
Else
{
Write-Host "End"
}
我已经设法使用以下 powershell 脚本来完成这项工作,但是,它有点笨拙!
$SessionHosts = "Server_1", "Server_2", "Server_3", "Server_4"
$OpeningSalvo = Read-Host -Prompt "[C]hange State, [Q]uery Servers or [E]xit?"
If ($OpeningSalvo -match "q")
{
Invoke-Command $SessionHosts {chglogon.exe /query}
}
Elseif ($OpeningSalvo -match "c")
{
$Server = Read-Host -Prompt "Server Name?"
$State = Read-Host -Prompt "[1] Enable, [2] Drain, [3] Drain until restart, [4] Disable all connections"
If ($State -match "1")
{Invoke-Command $Server {chglogon.exe /enable}}
Elseif ($State -match "2")
{Invoke-Command $Server {chglogon.exe /drain}}
Elseif ($State -match "3")
{Invoke-Command $Server {chglogon.exe /drainuntilrestart}}
Elseif ($State -match "4")
{Invoke-Command $Server {chglogon.exe /disable}}
}
Else
{
Write-Host "End"
}
顺便说一句,第一个实例中 chggon.exe /query 的输出有点冗长。
有什么建议可以将其通过管道传输到内存中,然后将服务器名称和状态提取出来?我确信我可以很好地格式化它。
事实上,任何建议都将不胜感激!这个脚本变得越复杂和有用,我就会学到越多!可能会有错误,但这是我的第一个脚本! :)
"会话登录当前已启用 + CategoryInfo:未指定:(会话登录当前启用:字符串)[],RemoteException + FullyQualifiedErrorId : NativeCommandError + PSComputerName : Server2"
【问题讨论】:
标签: powershell variables remote-desktop