今天豆子需要远程注销一个终端服务器的用户,操作很简单,首先quser获取远程用户的sessionID,然后logoff命令注销即可
quser /server:XXXX logoff sessionID /server:XXX
和早期的cmd和Linux的bash命令一样,quser的结果都是字符串。字符串的处理对于脚本来说比较麻烦,如果能够转换成标准的object对象就好了。
仔细观察一下quser的结果,可以看见他的输出结果很整齐,我如果能够把他中间的空格用逗号替换掉,那就是标准的csv格式,那就很容易转换为对象了。唯一的问题是有的列,比如sessionname为空,那我就需要数数到底多少个空格需要替换了
PS C:\users\yli\Documents> $a=quser /server:sydbcc02 PS C:\users\yli\Documents> $a USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME smiths rdp-tcp#5 16 Active 24692+13:29 3/14/2017 9:06 AM llederbauer rdp-tcp#4 22 Active 1:18 3/14/2017 9:18 AM jedwards 23 Disc 1:39 3/14/2017 7:54 AM tpicken rdp-tcp#2 24 Active . 3/14/2017 8:22 AM okaragiaouris rdp-tcp#9 27 Active 18 3/14/2017 8:55 AM bhue rdp-tcp#7 28 Active 12 3/14/2017 9:20 AM mcherginets 29 Disc 1:37 3/14/2017 8:58 AM abishop 30 Disc 2:48 3/14/2017 9:22 AM fburns 31 Disc 2:28 3/14/2017 9:37 AM ygordony 32 Disc 2:07 3/14/2017 10:04 AM tmoloney rdp-tcp#0 33 Active 1:07 3/14/2017 9:30 AM smaroo rdp-tcp#1 34 Active 1:45 3/14/2017 10:19 AM jwoodford 35 Disc 22 3/14/2017 10:42 AM mozard rdp-tcp#8 36 Active 56 3/14/2017 11:08 AM gmarsh rdp-tcp#6 37 Active 41 3/14/2017 10:56 AM mking 38 Disc 20 3/14/2017 11:11 AM mcolgan rdp-tcp#11 39 Active 59 3/14/2017 11:16 AM jbelgiovane rdp-tcp#12 41 Active 39 3/14/2017 11:33 AM ndrabsch 42 Disc 3 3/14/2017 11:57 AM
直接看不太容易区分,转换成ASCII看看,可以看见32(代表空格)一共有16个
$a=quser /server:sydbcc02 [int[]][char[]]$a[2] 32 108 108 101 100 101 114 98 97 117 101 114 32 32 32 32 32 32 32 32 32 32 32 114 100 112
okay,那我指定2到17之间的空格都替换为逗号,就行了,最后代码如下
$quser = (quser /server:sydbcc02) -replace ‘\s{2,17}‘, ‘,‘ | ConvertFrom-Csv $quser | ft USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME -------- ----------- -- ----- --------- ---------- smiths 16 Disc 3 3/14/2017 9:06 AM llederbauer rdp-tcp#4 22 Active 1:26 3/14/2017 9:18 AM jedwards 23 Disc 1:47 3/14/2017 7:54 AM tpicken rdp-tcp#2 24 Active 7 3/14/2017 8:22 AM okaragiaouris rdp-tcp#9 27 Active . 3/14/2017 8:55 AM bhue rdp-tcp#7 28 Active 20 3/14/2017 9:20 AM mcherginets 29 Disc 1:44 3/14/2017 8:58 AM abishop 30 Disc 2:56 3/14/2017 9:22 AM fburns 31 Disc 2:36 3/14/2017 9:37 AM ygordony 32 Disc 2:15 3/14/2017 10:04 AM tmoloney rdp-tcp#0 33 Active 1:15 3/14/2017 9:30 AM smaroo rdp-tcp#1 34 Active 1:52 3/14/2017 10:19 AM jwoodford 35 Disc 30 3/14/2017 10:42 AM mozard rdp-tcp#8 36 Active . 3/14/2017 11:08 AM gmarsh rdp-tcp#6 37 Active 48 3/14/2017 10:56 AM mking 38 Disc 27 mcolgan 39 Disc . 3/14/2017 11:16 AM jbelgiovane rdp-tcp#12 41 Active 47 3/14/2017 11:33 AM ndrabsch rdp-tcp#3 42 Active . 3/14/2017 11:57 AM alawton 43 Disc 11 3/14/2017 12:02 PM
这样子就可以很容易的进一步处理了,同样的思路也可以用在其他的cmd命令上。
时间: 2024-10-05 22:43:20