GRAPHICAL USER INTERFACE | WORKSHEET
Option Explicit
Private Sub buttonReplaceStringInFileName_Click()
Dim workSheetDashBoard As Worksheet
Dim dataPacket As DataPacketInterfaceToFunction
Dim interfaceField As OLEObject
Set workSheetDashBoard = Me
Set interfaceField = workSheetDashBoard.OLEObjects("ButtonSearchScope1")
If interfaceField.Object.Value = True Then
dataPacket.SearchScope = SingleDirectory
End If
Set interfaceField = workSheetDashBoard.OLEObjects("ButtonSearchScope2")
If interfaceField.Object.Value = True Then
dataPacket.SearchScope = DirectoryAndSubDirectories
End If
Set interfaceField = workSheetDashBoard.OLEObjects("UserInputFilePath")
dataPacket.FilePath = interfaceField.Object.Value
Set interfaceField = workSheetDashBoard.OLEObjects("UserInputStringOld")
dataPacket.StringOld = interfaceField.Object.Value
Set interfaceField = workSheetDashBoard.OLEObjects("UserInputStringNew")
dataPacket.StringNew = interfaceField.Object.Value
PowerShellCommands.findAndReplaceStringInFileName dataPacket
End Sub
MODULE | POWERSHELL COMMANDS
Option Explicit
Public Type DataPacketInterfaceToFunction
SearchScope As SearchScope
FilePath As String
StringOld As String
StringNew As String
End Type
Enum SearchScope
SingleDirectory = 1
DirectoryAndSubDirectories = 2
End Enum
Public Sub findAndReplaceStringInFileName(ByRef dataPacket As DataPacketInterfaceToFunction)
Dim shell As WshShell
Dim shellExec As WshExec
Dim strCommand As String
If dataPacket.SearchScope = SingleDirectory Then
strCommand = "Powershell $FilesInPathway = get-childitem -path " & "'" & dataPacket.FilePath & _
"'" & " -attributes !directory; foreach ($file in $FilesInPathway)" & _
"{$tempName = $file.name; $tempName = $tempName.replace('" & _
dataPacket.StringOld & "','" & dataPacket.StringNew & _
"'); Rename-Item $file.fullname $tempName}"
End If
If dataPacket.SearchScope = DirectoryAndSubDirectories Then
strCommand = "Powershell $FilesInPathway = get-childitem -path " & "'" & dataPacket.FilePath & _
"'" & " -recurse -attributes !directory; foreach ($file in $FilesInPathway)" & _
"{$tempName = $file.name; $tempName = $tempName.replace('" & _
dataPacket.StringOld & "','" & dataPacket.StringNew & "');" & _
"Rename-Item $file.fullname $tempName}"
End If
Set shell = CreateObject("WScript.Shell")
Set shellExec = shell.Exec(strCommand)
Do While shellExec.Status = 0
Application.Wait (Now() + TimeValue("0:00:01"))
Loop
End Sub