我正在尝试使用VB.Net和PowerShell来更新AD照片(thumbnailphotos属性)。所以我直接用PowerShell对所有用户进行了一次性更新。 thumbnailphoto属性已经有效了。我想做的是做一个夜间工作,获取在过去24小时内被修改或是新的图片文件。我的代码的大部分内容(获取最后24小时编辑的文件并通过查询内部数据库解析用户登录)正在运行。不起作用的部分是应该更新照片的PowerShell部分。
Imports System.Collections.ObjectModel
Imports System.Management.Automation
Imports System.Management.Automation.Runspaces
Imports System.IO
Imports System.Data.SqlClient
Imports System.Text
Module Module1
Sub Main()
'Read the number of files that are new in the past 24 hours
GetFiles()
Console.ReadLine()
End Sub
Private Sub GetFiles()
Dim directory = New DirectoryInfo("\\server\share")
Dim from_date As DateTime = DateTime.Now.AddDays(-7)
Dim to_date As DateTime = DateTime.Now
Dim files = directory.GetFiles().Where(Function(file) file.LastWriteTime >= from_date AndAlso file.LastWriteTime <= to_date)
'Test to see what file output we are getting
'===========================================
For Each file In files
'Console.WriteLine(file.ToString)
'Going to function to find user if file is not thumbs.db
If file.ToString <> "Thumbs.db" Then
FindUsername(file.ToString())
End If
Next
End Sub
Private Sub FindUsername(ByVal fileName As String)
'Calling function to find the user that has the picfile with this name
Dim userLogin As String = ""
Dim sqlConnection1 As New SqlConnection("Data Source=sqlserver;Initial Catalog=database;Integrated Security=False;User Id=user;Password=password;")
Dim cmd As New SqlCommand
Dim returnValue As Object
cmd.CommandText = "SELECT RTRIM(userLogin) AS [userLogin] FROM directory WHERE picfile='" + fileName + "'"
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1
sqlConnection1.Open()
returnValue = cmd.ExecuteScalar()
'Console.WriteLine(returnValue.ToString + " " + fileName.ToString)
sqlConnection1.Close()
If returnValue IsNot Nothing Then
'Run script with powershell
updatePhotoInAD(returnValue.ToString, fileName.ToString)
End If
End Sub
Private Sub updatePhotoInAD(userLogin As String, fileName As String)
'Prepare pipeline for execution
Dim fileNamewithPath As String = "\\server\share\" + fileName
Dim commandString As String = String.Format("Set-UserPhoto " + "{0}" + " - PictureData([System.IO.File]::ReadAllBytes(" + "{1})", userLogin, fileNamewithPath)
Using PowerShellInstance As PowerShell = PowerShell.Create()
' use "AddScript" to add the contents of a script file to the end of the execution pipeline.
' use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
PowerShellInstance.AddScript(commandString)
' invoke execution on the pipeline (ignore output)
PowerShellInstance.Invoke()
End Using
Console.WriteLine(userLogin + " " + fileName + " " + commandString)
End Sub
End Module