Export Hyper-V configuration

Code Details

option explicit 
 
dim objWMIService
dim managementService
dim fileSystem
 
const JobStarting = 3
const JobRunning = 4
const JobCompleted = 7
const wmiStarted = 4096
const wmiSuccessful = 0
 
Main()
 
'-----------------------------------------------------------------
' Main
'-----------------------------------------------------------------
Sub Main()
 
    dim computer, objArgs, vmName, vm, exportDirectory
 
    set fileSystem = Wscript.CreateObject("Scripting.FileSystemObject")
    computer = "."
    set objWMIService = GetObject("winmgmts:\\" + computer + "\root\virtualization")
    set managementService = objWMIService.ExecQuery("select * from Msvm_VirtualSystemManagementService").ItemIndex(0)
 
    set objArgs = WScript.Arguments
    if WScript.Arguments.Count = 2 then
        vmName = objArgs.Unnamed.Item(0)
        exportDirectory = objArgs.Unnamed.Item(1)
    else
        WScript.Echo "usage: cscript ExportVirtualSystemEx.vbs vmName exportDirectoryName"
        WScript.Quit(1)
    end if
 
    set vm = GetComputerSystem(vmName)
 
    if ExportVirtualSystemEx(vm, exportDirectory) then
        WriteLog "Done"
        WScript.Quit(0)
    else
        WriteLog "ExportVirtualSystemEx Failed."
        WScript.Quit(1)
    end if
End Sub
 
'-----------------------------------------------------------------
' Retrieve Msvm_VirtualComputerSystem from base on its ElementName
'-----------------------------------------------------------------
Function GetComputerSystem(vmElementName)
    On Error Resume Next
    dim query
    query = Format1("select * from Msvm_ComputerSystem where ElementName = '{0}'", vmElementName)
    set GetComputerSystem = objWMIService.ExecQuery(query).ItemIndex(0)
    if (Err.Number > 0) then
        WriteLog Format1("Err.Number: {0}", Err.Number)
        WriteLog Format1("Err.Description:{0}",Err.Description)
        WScript.Quit(1)
    end if
End Function
 
'-----------------------------------------------------------------
' Export a virtual system
'-----------------------------------------------------------------
Function ExportVirtualSystemEx(computerSystem, exportDirectory)
 
    dim objInParam, objOutParams
    dim query
    dim computer
    dim exportSettingData
 
    ExportVirtualSystemEx = false
 
    if Not fileSystem.FolderExists(exportDirectory) then
        fileSystem.CreateFolder(exportDirectory)
    end if
 
    set objInParam = managementService.Methods_("ExportVirtualSystemEx").InParameters.SpawnInstance_()
    objInParam.ComputerSystem = computerSystem.Path_.Path
 
    query = Format1("ASSOCIATORS OF {{0}} WHERE resultClass = Msvm_VirtualSystemExportSettingData", computerSystem.Path_.Path)
    set exportSettingData = objWMIService.ExecQuery(query).ItemIndex(0)
 
    'Dont copy the VHDs and AVHDs, but copy the Saved state information and Snapshot configurations if present
    exportSettingData.CopyVmStorage = false
    exportSettingData.CopyVmRuntimeInformation = true
    exportSettingData.CreateVmExportSubdirectory = true
    exportSettingData.CopySnapshotConfiguration = 0
 
    objInParam.ExportSettingData = exportSettingData.GetText_(1)
 
    objInParam.ExportDirectory = exportDirectory
 
    set objOutParams = managementService.ExecMethod_("ExportVirtualSystemEx", objInParam)
 
    if objOutParams.ReturnValue = wmiStarted then
        if (WMIJobCompleted(objOutParams)) then
            ExportVirtualSystemEx = true
        end if
    elseif (objOutParams.ReturnValue = wmiSuccessful) then
        ExportVirtualSystemEx = true
    else
        WriteLog Format1("ExportVirtualSystemEx failed with ReturnValue {0}", objOutParams.ReturnValue)
    end if
 
End Function
 
'-----------------------------------------------------------------
' Handle wmi Job object
'-----------------------------------------------------------------
Function WMIJobCompleted(outParam)
 
    dim WMIJob, jobState
 
    set WMIJob = objWMIService.Get(outParam.Job)
 
    WMIJobCompleted = true
 
    jobState = WMIJob.JobState
 
    while jobState = JobRunning or jobState = JobStarting
        WriteLog Format1("In progress... {0}% completed.",WMIJob.PercentComplete)
        WScript.Sleep(1000)
        set WMIJob = objWMIService.Get(outParam.Job)
        jobState = WMIJob.JobState
    wend
 
    if (jobState <> JobCompleted) then
        WriteLog Format1("ErrorCode:{0}", WMIJob.ErrorCode)
        WriteLog Format1("ErrorDescription:{0}", WMIJob.ErrorDescription)
        WMIJobCompleted = false
    end if
 
End Function
 
'-----------------------------------------------------------------
' Create the console log files.
'-----------------------------------------------------------------
Sub WriteLog(line)
    dim fileStream
    set fileStream = fileSystem.OpenTextFile(".\ExportVirtualSystemExLog.log", 8, true)
    WScript.Echo line
    fileStream.WriteLine line
    fileStream.Close
 
End Sub
 
'------------------------------------------------------------------------------
' The string formating functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format2(myString, arg0, arg1)
    Format2 = Format1(myString, arg0)
    Format2 = Replace(Format2, "{1}", arg1)
End Function
 
'------------------------------------------------------------------------------
' The string formating functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format1(myString, arg0)
    Format1 = Replace(myString, "{0}", arg0)
End Function
Posted in Information Technology | Tagged , , | Comments Off on Export Hyper-V configuration

Import Hyper-V Configuration

Code Description

option explicit 
 
dim objWMIService
dim managementService
dim switchService
dim fileSystem
 
const JobStarting = 3
const JobRunning = 4
const JobCompleted = 7
const wmiStarted = 4096
const wmiSuccessful = 0
 
Main()
 
'-----------------------------------------------------------------
' Main
'-----------------------------------------------------------------
Sub Main()
    dim computer, objArgs, importDirectory, generateNewID
 
    set fileSystem = Wscript.CreateObject("Scripting.FileSystemObject")
    computer = "."
    set objWMIService = GetObject("winmgmts:\\" & computer & "\root\virtualization")
    set managementService = objWMIService.ExecQuery("select * from Msvm_VirtualSystemManagementService").ItemIndex(0)
    set switchService = objWMIService.ExecQuery("select * from Msvm_VirtualSwitchManagementService").ItemIndex(0)
 
    set objArgs = WScript.Arguments
    if WScript.Arguments.Count = 1 then
        importDirectory = objArgs.Unnamed.Item(0)
    else
        WScript.Echo "usage: cscript ImportVirtualSystemEx-ConfigOnly.vbs importDirectoryName"
        WScript.Quit(1)
    end if
 
    if ImportVirtualSystemEx(importDirectory) then
        WriteLog "Done"
        WScript.Quit(0)
    else
        WriteLog "ImportVirtualSystemEx Failed."
        WScript.Quit(1)
    end if
End Sub
 
'-----------------------------------------------------------------
' GetVirtualSystemImportSettingData from a directory
'-----------------------------------------------------------------
Function GetVirtualSystemImportSettingData(importDirectory)
 
    dim objInParam, objOutParams    
 
    set objInParam = managementService.Methods_("GetVirtualSystemImportSettingData").InParameters.SpawnInstance_()
    objInParam.ImportDirectory = importDirectory
 
    set objOutParams = managementService.ExecMethod_("GetVirtualSystemImportSettingData", objInParam)
 
    if objOutParams.ReturnValue = wmiStarted then
        if (WMIJobCompleted(objOutParams)) then
            set GetVirtualSystemImportSettingData = objOutParams.ImportSettingData
        end if
    elseif objOutParams.ReturnValue = wmiSuccessful then
        set GetVirtualSystemImportSettingData = objOutParams.ImportSettingData
    else
        WriteLog Format1("GetVirtualSystemImportSettingData failed with ReturnValue {0}", objOutParams.ReturnValue)
    end if
 
End Function
'-----------------------------------------------------------------
' ImportVirtualSystem from a directory
'-----------------------------------------------------------------
Function ImportVirtualSystemEx(importDirectory)
 
    dim objInParam, objOutParams
    dim newDataRoot
    dim importSettingData
    dim newSourceResourcePaths, newTargetNetworkConnections, newSwitch    
 
    'Resources in newSourceResourcePaths below should be existing. Fill this with the resources corresponding to those in CurrentResourcePaths
    newSourceResourcePaths = Array(1)
    newSourceResourcePaths(0) = importDirectory & "\VM.vhd"
 
    ImportVirtualSystemEx = false
    set objInParam = managementService.Methods_("ImportVirtualSystemEx").InParameters.SpawnInstance_()
    objInParam.ImportDirectory = importDirectory
 
    set importSettingData = GetVirtualSystemImportSettingData(importDirectory)
    importSettingData.GenerateNewId = true
    importSettingData.CreateCopy = false
    importSettingData.Name = "NewSampleVM-ConfigOnlyImport"
    importSettingData.SourceResourcePaths = newSourceResourcePaths
    importSettingData.Put_
 
    objInParam.ImportSettingData = importSettingData.GetText_(1)
 
    set objOutParams = managementService.ExecMethod_("ImportVirtualSystemEx", objInParam)
 
    if objOutParams.ReturnValue = wmiStarted then
        if (WMIJobCompleted(objOutParams)) then
            ImportVirtualSystemEx = true
        end if
    elseif objOutParams.ReturnValue = wmiSuccessful then
        ImportVirtualSystemEx = true
    else
        WriteLog Format1("ImportVirtualSystemEx failed with ReturnValue {0}", objOutParams.ReturnValue)
    end if
 
End Function
 
'-----------------------------------------------------------------
' Handle wmi Job object
'-----------------------------------------------------------------
Function WMIJobCompleted(outParam)
 
    dim WMIJob, jobState
 
    set WMIJob = objWMIService.Get(outParam.Job)
 
    WMIJobCompleted = true
 
    jobState = WMIJob.JobState
 
    while jobState = JobRunning or jobState = JobStarting
        WriteLog Format1("In progress... {0}% completed.",WMIJob.PercentComplete)
        WScript.Sleep(1000)
        set WMIJob = objWMIService.Get(outParam.Job)
        jobState = WMIJob.JobState
    wend
 
    if (jobState <> JobCompleted) then
        WriteLog Format1("ErrorCode:{0}", WMIJob.ErrorCode)
        WriteLog Format1("ErrorDescription:{0}", WMIJob.ErrorDescription)
        WMIJobCompleted = false
    end if
 
End Function
 
'-----------------------------------------------------------------
' Create the console log files.
'-----------------------------------------------------------------
Sub WriteLog(line)
    dim fileStream
    set fileStream = fileSystem.OpenTextFile(".\ImportVirtualSystemEx-ConfigOnly.log", 8, true)
    WScript.Echo line
    fileStream.WriteLine line
    fileStream.Close
 
End Sub
 
'------------------------------------------------------------------------------
' The string formating functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format1(myString, arg0)
    Format1 = Replace(myString, "{0}", arg0)
End Function
  • Keywords:
Posted in Information Technology | Tagged , , | Comments Off on Import Hyper-V Configuration

USB bootable with Diskpart

DISKPART> list disk
Disk ### Status Size Free Dyn Gpt
——– ———- ——- ——- — —
Disk 0 Online 279 GB 88 GB
Disk 1 Online 190 GB 5780 KB
Disk 2 Online 233 GB 673 KB *
Disk 3 No Media 0 B 0 B
Disk 4 No Media 0 B 0 B
Disk 5 Online 3914 MB 0 B

Once the disk is known, select the disk and run the rest of the displayed commands (change “disk 5” to the number of your disk):

DISKPART> select disk 5
Disk 5 is now the selected disk.
DISKPART> clean
DiskPart succeeded in cleaning the disk.
DISKPART> create partition primary
DiskPart succeeded in creating the specified partition.
DISKPART> select partition 1
Partition 1 is now the selected partition.
DISKPART> active
DiskPart marked the current partition as active.
DISKPART> format fs=fat32 quick
or
DISKPART> format fs=NTFS quick
100 percent completed
DiskPart successfully formatted the volume.
DISKPART> assign
DiskPart successfully assigned the drive letter or mount point.
DISKPART> exit
Leaving DiskPart…

Posted in Information Technology | Tagged , | Comments Off on USB bootable with Diskpart

MomADAdmin error in Child Domain

MomADAdmin is not extending Active Directory on Child domains. The problem occurs in a environment where SCOM is installed in one domain monitoring other domain. Within SCOM the following error is shown: MomADAdmin not run

To successful run momadadmin you need to add to both parameters MomAdminSecurityGroup and RMS-Server the domain prefix.

MomADAdmin.exe ManagementGroupName Domain\MomadminSecurityGroup Domain\RMSServer TargetDomain

 

Posted in Information Technology | Tagged , , | Comments Off on MomADAdmin error in Child Domain

Scheduled task error – Could not run

Problem:

A scheduled task running on windows 2003 shows status “could not run” . The task is starting a batch (cmd) running some simple dos shell commands. So nothing special.

Solution:

Rights for user BATCH on %windir%\system32\cmd.exe missing

Add rights for user BATCH on cmd.exe read/execute and read

Posted in Information Technology | Tagged | Comments Off on Scheduled task error – Could not run

Scheduled task last result 0x2

Problem | A scheduled task running a command shell is returning “last result 0x2” but everything is fine.

Reason | The last command within the batch is returning an errorlevel <>; 0. This could be robocopy ending with skipped files.

Solution | Run error level checks within your batch and if all is ok set errorlevel to 0

set errorlevel=0
Posted in Information Technology, Uncategorized | Tagged | Comments Off on Scheduled task last result 0x2

DNSMadeEasy DDNS update script

Controlled update of DDNS

  • Author: Martin Oehy
  • Date: 2010 04 11
  • Desription: this Script replaces the executable provided by DNSMade Easy. So you can track changes of your DHCP provider.
  • Parameter: Change your ID’s, Name , Password and Log Location and run it
'Author: Martin Oehy
'Zweck:  Kontrolliertes Update des DDNS bei DNSMadeEasy
'Info: IE6: Advanced: allow paste operations via script -&gt; muss im IE disabled
'      IE7: Security: Scripting: allow programmatic Clipbord access 
 
Option Explicit
Dim g_oFso
Dim g_oShell
Set g_oFso 			= WScript.CreateObject("Scripting.FileSystemObject")
Set g_oShell			= WScript.CreateObject("Wscript.Shell")
Const vbAnf = """"
 
Dim strOldIP, strNewIP, strIP
Dim strLogFile
Dim StrInputFile
Dim StrError
Dim arrAccounts, strAccounts,  strAccount, strDDNSUSername, strDDNSPw
dim strLogFolder, strChangeFile , strIncludeFile
dim objIE
 
strLogFolder	= "C:\AppData\Scripts\"
if not g_oFso.folderexists(strLogFolder) Then
	strLogFolder = g_oShell.ExpandEnvironmentStrings("%temp%") & "\"
End If
strLogFile 	= strLogFolder & "DNSUpdate.log"
strChangeFile 	= strLogFolder & "DNSUpdateChange.log"
strIncludeFile 	= strLogFolder & "DNSUpdate.inc"
 
strOldIP	= ""
strAccounts 	= "1111111;2222222" 	' The numbers of your Accounts by DNSMadeEasy separated by ;
strDDNSUSername	= "aaaaa"		' Logon Name at DDNS
strDDNSPw	= "Password"		' Passwort by DDNS
 
if g_oFso.fileexists(strIncludeFile) then	' Letzte IP einlesen
	include strIncludeFile
end if
 
Set objIE = CreateObject("InternetExplorer.Application")
objIE.ToolBar        = False
objIE.Resizable      = False
objIE.StatusBar      = False
objIE.Width          = 300
objIE.Height         = 180
 
objIE.Navigate("www.dnsmadeeasy.com/myip.jsp")	' Get IP
Do
Loop Until Not objIE.busy
'objIE.Visible = True
 
objIE.Document.execcommand "SelectAll"
objIE.Document.execcommand "Copy"
 
strIP = objIE.document.parentwindow.clipboardData.GetData("text")
objIE.Quit
set ObjIE = Nothing
strNewIP = ltrim(rTrim(strIP))
fuQuicklog01 strIncludeFile,"C","strOldIP=" & vbanf & strNewIP & vbAnf
'msgbox "Old:" &strOldIP & vbCRLF & "New:" &strNewIP
If strNewIP <> strOldIP Then	' test ob die IP geändert hat
	FuQuicklog01 strLogFile ,"A",now() & vbTab &  "Warning: IP Change to " & strNewIP
	FuQuicklog01 strChangeFile ,"A",now() & vbTab &  "Warning: IP  Change to " & strNewIP
	arrAccounts = split(strAccounts,";")
	For Each strAccount in arrAccounts	' einen Account nach dem anderen Aktualisieren
		Set objIE = CreateObject("InternetExplorer.Application")
		objIE.Navigate("www.dnsmadeeasy.com/servlet/updateip?username=" & strDDNSUSername & "&password=" & strDDNSPw & "&id=" & strAccount & "&ip=" & strNewIP)
		do
		Loop Until Not objIE.busy
		'objIE.Visible = True
		objIE.Document.execcommand "SelectAll"
		objIE.Document.execcommand "Copy"
		strError 	= objIE.document.parentwindow.clipboardData.GetData("text")
		'msgbox "Wait"
		objIE.Quit
		Set objIE = Nothing
		FuQuicklog01 strLogFile,"A",now() & vbTab &  strAccount &"  ReturnCode :" & strError
	Next
Else
	FuQuicklog01 strLogFile,"A",now() & vbTab &  "Info:   IP Not Changed " & strNewIP
 
End If 
 
Public Function fuQuickLog01( ByVal strFileFQN, ByVal strMode, ByVal strTextline )
	'********************************************************************************
	' Author: 2008-07-22 Martin Oehy
	' Beschreibung: Erstellt oder erweitert ein Logfile mit einer Zeile
	'
	' Parameter:
	'	strFileFQN 	: z.B c:\temp\logfile.txt
	'	strMode	: C für Create oder A für Append
	'	strTextLine: Text der gelogt werden soll
	' Return: -1 für Fehler
	'
	'********************************************************************************
	'On Error Resume next
	Dim foFSO
	Dim foLogfile
	Const Forappending = 8
	Set foFSO=CreateObject("Scripting.FileSystemObject")
	If UCase(strMode) = "C" Or Not foFSO.FileExists(strFileFQN) Then ' new or not existing
		Err.Clear
		set foLogfile = foFSO.CreateTextFile(strFileFQN,True)
		If Err.Number > 0 Then
			fuQuickLog01	= "1 " & Err.Description
			Exit Function
		End If
	Else
		Err.Clear
		Set foLogFile = foFSO.OpenTextFile(strFileFQN, ForAppending)
		If Err.Number > 0 Then
			fuQuickLog01	= "1 " & Err.Description
			Exit Function
		End If
	End If
	foLogFile.WriteLine strTextLine
	foLogFile.Close
	Set foLogFile 	= Nothing
	Set foFSO 		= Nothing
	fuQuickLog01 		= 0
End Function
 
Public Function Include(sInstFile)
	' Author OM 2008-09-02 OM
	' Include a VB with Public arguments
	' Example Include File:
	'		Public strText
	'		strText = "This is a Message"
	'
	' For non public rewrite the SUB as Sub
 
	On Error Resume Next
	Dim foFSO, f, s
	Set foFSO = CreateObject("Scripting.FileSystemObject")
	If foFSO.FileExists(sInstFile) Then
		Set f = foFSO.OpenTextFile(sInstFile)
		s = f.ReadAll
		f.Close
		ExecuteGlobal s
	End If
	Set foFSO = Nothing
	Set f = Nothing
End Function
  • Keywords: VBScript DDNS DNSMadeEasy
Posted in Information Technology | Tagged , , | Comments Off on DNSMadeEasy DDNS update script