powered by simpleCommunicator - 2.0.59     © 2025 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / HTML, JavaScript, VBScript, CSS [игнор отключен] [закрыт для гостей] / (VBS) Как преобразовать два DWORD значения из реестра в дату?
5 сообщений из 5, страница 1 из 1
(VBS) Как преобразовать два DWORD значения из реестра в дату?
    #34732869
pazdak
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Помогите пожалуйста справиться со следующей задачей:

В реестре по адресу:
"SOFTWARE\MICROSOFT\Windows NT\CurrentVersion\ProfileList\"
для определенного пользователя есть DWORD поля ProfileLoadTimeHigh и ProfileLoadTimeLow, которые в сумме дают дату последней загрузки профиля, вопрос как ею можно получить?

Буду благодарен за любую помощь.
pazdak
...
Рейтинг: 0 / 0
(VBS) Как преобразовать два DWORD значения из реестра в дату?
    #34733385
Фотография mahoune
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Что есть тут \\http://www.voodoovenue.com/nw_tips.htm#4

И в нете еще вот это нарыл:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
    '
    ' Get information about the User Profiles and mount all of the User's
    ' registry hives.
    ' Note: The registry hives mounted here are used in: GetEmail, GetInternet,
    ' GetMapped, GetShares, and GetStartup.  We do not update the "reference
    ' count" for the hive, so it's possible that some other program might
    ' umount the hive before we read from it.
    '
    Public Sub GetProfiles()
        If IsWin32 Then
            Dim DefaultUserProfile, keyname, ImagePath, ProfileName, UserID, LoadedHives() As String
            Dim key, subkey, testkey As RegistryKey
            Dim flags, num_users As Integer
            Dim ld As LongDate
            Dim RawSID() As Byte
            Dim admin, we_mounted_it As Boolean
            Dim dr As SOSOSDataSet.ProfilesRow

            ImagePath = ""
            keyname = ""
            Try
                ' the mounting of registry hives is a tightly held privilege
                ' that is not enabled by default (even for administrators)
                admin = Misc.IsAdmin()

                ' make a list of hives that are currently loaded
                LoadedHives = reg_hku.GetSubKeyNames

                ' get the listing of profiles from the registry
                key = reg_hklm.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList", False)
                If Not IsNothing(key) Then
                    ' loop thru each subkey
                    num_users = 0
                    For Each keyname In key.GetSubKeyNames
                        subkey = key.OpenSubKey(keyname, False)
                        flags = CInt(subkey.GetValue("Flags", -1))
                        RawSID = CType(subkey.GetValue("SID", Nothing), Byte())

                        ' for WinVista, the flags trick doesn't work to weed
                        ' out the non-numan keys
                        If OSVer >= 6.0 And IsNothing(RawSID) Then
                            flags = -1
                        End If

                        ' we only want "human" profiles (WinNT doesn't have
                        ' this flag, but it also doesn't list non-human keys)
                        If flags = 0 Or OSVer = 4.0 Then
                            num_users += 1
                            ImagePath = subkey.GetValue("ProfileImagePath", "").ToString
                            ' We have to substitute the values for our expanded
                            ' enivronmental variables with those of the remote
                            ' PC!
                            If RemotePC <> "" Then
                                ImagePath = ImagePath.Replace(Environment.ExpandEnvironmentVariables("%SystemDrive%"), SystemDrive)
                            End If
                            If Directory.Exists(Misc.ConvUNC(RemotePC, ImagePath)) Then
                                ld.date_hi = CInt(subkey.GetValue("ProfileLoadTimeHigh", 0))
                                ld.date_lo = CInt(subkey.GetValue("ProfileLoadTimeLow", 0))
                                ProfileName = Path.GetFileName(ImagePath)
                                If Not IsNothing(RawSID) Then
                                    UserID = Misc.SidToName(RemotePC, RawSID)
                                Else
                                    ' If we don't have an imbedded SID, then we
                                    ' use the key name instead
                                    UserID = Misc.SidToName(RemotePC, keyname)
                                End If

                                ' Let's mount the user's hive (if it isn't
                                ' already mounted)
                                we_mounted_it = False
                                If admin AndAlso Array.IndexOf(LoadedHives, keyname) < 0 Then
                                    ' Since we're doing this remotely, the path
                                    ' to the hive is relative to the remote PC
                                    If Misc.MountHive(RemotePC, keyname, ImagePath & "\NTUSER.DAT") = 0 Then
                                        we_mounted_it = True
                                        ' we tag the ones that we mounted with
                                        ' an asterisk
                                        ProfileList.Add(ImagePath, "*" & keyname)
                                    End If
                                End If

                                dr = ds.Profiles.NewProfilesRow
                                dr.ID_Profile = ID
                                dr.Profile = Left(ProfileName, ds.Profiles.ProfileColumn.MaxLength)
                                dr.Profile_Path = Left(ImagePath, ds.Profiles.Profile_PathColumn.MaxLength)
                                If UserID <> "" Then
                                    dr.Profile_Owner = Left(UserID, ds.Profiles.Profile_OwnerColumn.MaxLength)
                                End If

                                If OSVer = 4.0 Or admin = False Then
                                    ' This is a bit crude, but it's better than
                                    ' nothing
                                    dr.Profile_IsAdmin = False
                                    If Not IsNothing(ds.Admins.FindByID_AdminAdmin_UserID(ID, UserID)) Then
                                        dr.Profile_IsAdmin = True
                                    End If
                                Else
                                    dr.Profile_IsAdmin = Misc.IsRemoteAdmin(MachineName, reg_hku, UserID)
                                End If
                                If ld.Long64 > 0 Then
                                    ' Not supported in WinNT or WinVista
                                    dr.Profile_LastLoad = Date.FromFileTime(ld.Long64)
                                End If
                                ds.Profiles.AddProfilesRow(dr)

                                ' Let's do a "test run" to verify that the
                                ' hive got mounted and that current user has
                                ' permission to read it.  We do this here
                                ' rather than in each one of the "dependent"
                                ' methods.
                                Try
                                    testkey = reg_hku.OpenSubKey(keyname & "\Control Panel", False)
                                    If Not IsNothing(testkey) Then
                                        testkey.Close()
                                    End If
                                    If we_mounted_it = False Then
                                        ProfileList.Add(ImagePath, keyname)
                                    End If
                                Catch
                                    ' if this test fails, then this key
                                    ' won't appear in the ProfileList
                                End Try
                            End If
                        End If
                        subkey.Close()
                    Next

                    DefaultUserProfile = key.GetValue("DefaultUserProfile", "Default User").ToString
                    key.Close()

                    ' Update the PC table's NumUser field
                    If ds.PC.Count > 0 Then
                        ds.PC(0).PC_NumUsers = num_users
                    End If

                    ' manually create an entry for the Default User
                    If ds.Profiles.Count > 0 Then
                        Dim parts() As String

                        dr = ds.Profiles.NewProfilesRow
                        dr.ID_Profile = ID
                        dr.Profile = DefaultUserProfile

                        ' use an existing entry as a prototype
                        parts = ds.Profiles(0).Profile_Path.Split("\"c)
                        parts(parts.Length - 1) = DefaultUserProfile
                        ImagePath = Join(parts, "\")
                        dr.Profile_Path = Left(ImagePath, ds.Profiles.Profile_PathColumn.MaxLength)
                        dr.Profile_IsAdmin = False
                        ds.Profiles.AddProfilesRow(dr)

                        we_mounted_it = False
                        If admin AndAlso Array.IndexOf(LoadedHives, DefaultUserProfile) < 0 Then
                            ' Since we're doing this remotely, the path
                            ' to the hive is relative to the remote PC
                            If Misc.MountHive(RemotePC, DefaultUserProfile, ImagePath & "\NTUSER.DAT") = 0 Then
                                we_mounted_it = True
                                ' we tag the ones that we mounted with
                                ' an asterisk
                                ProfileList.Add(ImagePath, "*" & DefaultUserProfile)
                            End If
                        End If
                    End If
                End If
            Catch ex As Exception
                dr = ds.Profiles.NewProfilesRow
                dr.ID_Profile = ID
                dr.Profile = "Error"
                dr.Profile_IsAdmin = False
                dr.Profile_Path = Left("Error: " & ex.Message, ds.Profiles.Profile_PathColumn.MaxLength)
                ds.Profiles.AddProfilesRow(dr)
                Misc.ErrorLog(ex, MachineName, "Profiles", Misc.ErrLogLevel.Errors)
            End Try
        End If
    End Sub

    'BOOL LookupAccountSid(
    '  LPCTSTR lpSystemName,
    '  PSID lpSid,
    '  LPTSTR lpName,
    '  LPDWORD cchName,
    '  LPTSTR lpReferencedDomainName,
    '  LPDWORD cchReferencedDomainName,
    '  PSID_NAME_USE peUse
    ');
    Private Declare Auto Function LookupAccountSid Lib "advapi32.dll" ( _
        ByVal lpSystemName As String, _
        ByVal lpSid As IntPtr, _
        ByVal lpName As String, _
        ByRef cchName As Integer, _
        ByVal lpReferenceDomainName As String, _
        ByRef cchReferencedDomainName As Integer, _
        ByRef peUse As Integer _
    ) As Boolean

    '
    ' Take a "raw" SID (as a byte array) and determine the User ID (used in
    ' GetProfiles) (overloaded)
    '
    Public Shared Function SidToName(ByVal RemotePC As String, ByVal RawSid As Byte()) As String
        Dim Sid As IntPtr
        Dim gch As GCHandle
        Dim ans As String

        ' get a safe pointer to the SID array of bytes
        gch = GCHandle.Alloc(RawSid, GCHandleType.Pinned)
        Sid = Marshal.UnsafeAddrOfPinnedArrayElement(RawSid, 0)
        ans = SidToName(RemotePC, Sid)
        gch.Free()

        Return ans
    End Function

    '
    ' Take a String version of a SID and generate a User ID (used in
    ' GetProfiles) (overloaded)
    '
    Public Shared Function SidToName(ByVal RemotePC As String, ByVal sid_string As String) As String
        Dim sid As IntPtr

        sid = StringToSID(sid_string)
        If IsNothing(sid) Then
            Return sid_string
        End If

        Return SidToName(RemotePC, sid)
    End Function

    '
    ' Take an IntPtr SID and generate the User ID (overloaded)
    '
    Private Shared Function SidToName(ByVal RemotePC As String, ByVal sid As IntPtr) As String
        Dim UserName, name, domain_name As String
        Dim name_len, domain_len, peUse As Integer

        name_len = NAME_SIZE
        domain_len = NAME_SIZE
        name = Space(name_len)
        domain_name = Space(domain_len)

        ' look up the Account associated with that SID
        If LookupAccountSid(RemotePC, sid, name, name_len, domain_name, domain_len, peUse) = False Then
            ' if the lookup fails, return the SID as as string
            Return SIDtoString(sid)
        End If

        ' put the name parts together
        If domain_len > 0 Then
            UserName = Left(domain_name, domain_len) & "\" & Left(name, name_len)
        Else
            If RemotePC = "" Then
                RemotePC = Environment.MachineName
            End If
            UserName = RemotePC & "\" & Left(name, name_len)
        End If

        Return UserName
    End Function


Код: plaintext
.mahoune .  
...
Рейтинг: 0 / 0
(VBS) Как преобразовать два DWORD значения из реестра в дату?
    #34734847
pazdak
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
mahoune
Спасибо за ответ, но я это читал и не смог это перенести на VBScript, т.к. не знаю как завести объект:
Код: plaintext
Dim ld As LongDate
Еще небольшое дополнение:
результат преобразования хотелось бы получить в таком виде:
20070816131045.348351+000
это мне нужно для составления MIF файла, и даты в этом файле должны быть именно в таком формате.
Есть ли еще какие-нибудь идеи?
...
Рейтинг: 0 / 0
(VBS) Как преобразовать два DWORD значения из реестра в дату?
    #34748318
pazdak
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Нарыл такой вот скриптик:
http://www.voodoovenue.com/nw_tips.htm
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
Const HKEY_LOCAL_MACHINE = &H80000002 
strComputer = "." 
Set objRegistry=GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv") 
strKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" 
objRegistry.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubkeys 
  
For Each objSubkey In arrSubkeys 
    strValueName = "ProfileImagePath" 
    strSubPath = strKeyPath & "\" & objSubkey 
    objRegistry.GetExpandedStringValue HKEY_LOCAL_MACHINE,strSubPath,strValueName,strValue 
    strValueName = "ProfileLoadTimeHigh" 
    strSubPath = strKeyPath & "\" & objSubkey 
    objRegistry.GetDWordValue HKEY_LOCAL_MACHINE,strSubPath,strValueName, lngHighValue 
    strValueName = "ProfileLoadTimeLow" 
    strSubPath = strKeyPath & "\" & objSubkey 
    objRegistry.GetDWordValue HKEY_LOCAL_MACHINE,strSubPath,strValueName,lngLowValue 
        If lngLowValue <  0  Then 
                lngHighValue = lngHighValue +  1  
        End If 
        If lngHighValue =  0  And lngLowValue =  0  Then 
                diff =  0  
        End If 
        WScript.Echo strValue & " " & DateAdd("d", ((lngHighValue *  2  ^  32  + lngLowValue) /  600000000  - diff) /  1440 , # 1 / 1 / 1601 #)
Next 
Результат получается ввиде даты 01.01.2007, как можно получить такое же но только в требуемом виде: 20070816131045.348351+000
Требуется Ваша помощь...
...
Рейтинг: 0 / 0
(VBS) Как преобразовать два DWORD значения из реестра в дату?
    #34749797
pazdak
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Итак что получилось сделать:
требуемое значение даты получено, но работает этот скрипт только для Windows XP и выше, это связанно с объектом WbemScripting.SWbemDateTime, которого в ранних версиях к сожалению нет
Подскажите, если знаете:
Можно ли как-то реализовать функции WbemScripting.SWbemDateTime для Windows 2000???
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
Const HKEY_LOCAL_MACHINE = &H80000002 
Set pbjReg  = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv" ) 
strKeyPath  = "SOFTWARE\MICROSOFT\Windows NT\CurrentVersion\ProfileList" 
pbjReg.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys 

For Each subkey In arrSubKeys 
  ret = pbjReg.GetStringvalue(HKEY_LOCAL_MACHINE, strKeyPath & "\ProfileImagePath" , sValue) 
  If ret<> 0  Then 
    Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv" ) 
    strKeyPath = "SOFTWARE\MICROSOFT\Windows NT\CurrentVersion\ProfileList\" & subkey 
    strValueName = "ProfileImagePath" 
    Return = objReg.GetExpandedStringValue(HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue) 
    
    If (Return =  0 ) And (Err.Number =  0 ) Then 
       Set wmiCol = WMI.ExecQuery ("SELECT Domain, Name, SID FROM Win32_Account where SID="""&subkey&"""")
       sUserName   = "???"
       sUserDomain = "???"
       For each wmiItem in wmiCol
         if wmiItem.SID = subkey then 
           sUserName   = wmiItem.Name
           sUserDomain = wmiItem.Domain
         End if
       Next
       
       strValueName = "ProfileLoadTimeHigh"
       Return = objReg.GetDWORDValue(HKEY_LOCAL_MACHINE,strKeyPath,strValueName,lngHighValue)
       strValueName = "ProfileLoadTimeLow"
       Return = objReg.GetDWORDValue(HKEY_LOCAL_MACHINE,strKeyPath,strValueName,lngLowValue)
       if typename(lngHighValue) <> "Null" then
         WScript.Echo sUserDomain & "\" & sUserName 
         WScript.Echo DateAdd("d", ((lngHighValue *  2  ^  32  + lngLowValue) /  600000000 ) /  1440 , # 1 / 1 / 1601 #)
         NanoSecs = (lngHighValue *  2  ^  32  + lngLowValue)
         '' /* Returns UTC (Universal Coordinated Time, aka GMT) time */
         DT = # 1 / 1 / 1601 # + (NanoSecs /  600000000  /  1440 )
         WScript.Echo CDate(DT)
         '' /* Only Windows XP and above */
         Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
         dateTime.SetVarDate DT, False
         WScript.Echo dateTime.Value
         WScript.Echo ""
       end if
    End if
  End if
NEXT 
На выходе получаем следущую информацию:
авторDOMAIN\Administrator
05.07.2007
05.07.2007 10:23:01
20070705102301.000000+000
...
Рейтинг: 0 / 0
5 сообщений из 5, страница 1 из 1
Форумы / HTML, JavaScript, VBScript, CSS [игнор отключен] [закрыт для гостей] / (VBS) Как преобразовать два DWORD значения из реестра в дату?
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]