2016-12-08

Microsoft VDI 內類似 Dynamic DNS (DDNS)的功能 (Part 1)

Updated 2020.06.11:
    程式整個重寫 參考新的一篇

User 的需求真是千奇百怪
VDI Pooled VM 的情況下, User 每次登入不一定是哪一台 VM, 可能每次都不一樣
然而如果 User 有需要執行某種服務需要提供其他同仁連線, 就會因此造成麻煩

當然, 這種服務理當建立獨立運作的 Server, 不該用 VDI Pooled VM
但有時候就是會有這種需求
因應這種事情, 我寫了三個小 Script 來達成類似 Dynamic DNS (DDNS) 的效果

LogonScript.vbs: 在 User 登入時執行
LogoutScript.vbs: 在 User 登出時執行
DDNS.ps1: 在 FileServer 上以具有管理 DNS Record 權限的帳號每一分鐘執行一次

LogonScript.vbs
===== 程式開始 =====
on error resume next

RemotePath = "\\FileServer.Contoso.com\DNSCNameQueue$"

Set wshNetwork = CreateObject("WScript.Network")

Set fso = CreateObject("Scripting.FileSystemObject")

if (fso.FolderExists(RemotePath)) then
QueueFileName = RemotePath & "\" & wshNetwork.UserName & "@" & wshNetwork.ComputerName & "@" & "ADD"
WriteQueue = fso.OpenTextFile(QueueFileName, 2, true, -1)
WriteQueue.Close
end if
===== 程式結束 =====

LogoutScript.vbs
===== 程式開始 =====
on error resume next

RemotePath = "\\FileServer.Contoso.com\DNSCNameQueue$"

Set wshNetwork = CreateObject("WScript.Network")

Set fso = CreateObject("Scripting.FileSystemObject")

if (fso.FolderExists(RemotePath)) then
QueueFileName = RemotePath & "\" & wshNetwork.UserName & "@" & wshNetwork.ComputerName & "@" & "DEL"
WriteQueue = fso.OpenTextFile(QueueFileName, 2, true, -1)
WriteQueue.Close

end if
===== 程式結束 =====

DDNS.ps1
===== 程式開始 =====
$DomainName = "Contoso.com"
$DNSServerName = "DC"
$QueuePath = "D:\DNSCNameQueue"
$MinuteBefore = -20

Get-ChildItem $QueuePath | Where {$_.LastWriteTime -gt (Get-Date).Addminutes($MinuteBefore)} | select Name | foreach {

$Info = $_.Name.Split("@")
$UserName = $Info[0]
$ComputerName = $Info[1]
$ActionType =  $Info[2]
$ComputerNameArray = $ComputerName.Split("-")
$CollectionName = $ComputerNameArray[0]
$CName = "$UserName-$CollectionName"

if ($ActionType -eq "ADD") {
Add-DnsServerResourceRecordCName -ComputerName "$DNSServerName.$DomainName" -Name $CName -HostNameAlias "$ComputerName.$DomainName" -ZoneName $DomainName
} else {
Get-DnsServerResourceRecord -ComputerName "$DNSServerName.$DomainName" -ZoneName $DomainName -RRType "CName" | where {$_.HostName -eq $CName} | Remove-DnsServerResourceRecord -ComputerName "$DNSServerName.$DomainName" -ZoneName $DomainName -Force
};

Remove-Item ($QueuePath +"\" + $_.Name)
};


Get-ChildItem $QueuePath | Where {$_.LastWriteTime -lt (Get-Date).Addminutes($MinuteBefore)} | Remove-Item
===== 程式結束 =====

沒有留言:

張貼留言