2014-09-05 58 views
-1

好吧,就像许多其他人一样,我是VB脚本的noob。我想要做的是创建一个VB脚本,它将操纵从Fulton A1032-CCC Adamsville到A1032-CCC的文件名。我浏览过很多网站试图找到答案,但只有在中途工作时才提出来。VB脚本,将操纵文件名

strComputer = "." 

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 

Set colFiles = objWMIService.ExecQuery _ 
("ASSOCIATORS OF {Win32_Directory.Name='H:\Darrell 2014 folder\Distview Wiki Revamp\To'} Where " _ 
    & "ResultClass = CIM_DataFile") 

For Each objFile In colFiles 
    strPath = objFile.Drive & objFile.Path 
    strExtension = objFile.Extension 
    strFileName = objFile.FileName 

    If Left(strFileName, 7) = "Fulton " Then 
     intLength = Len(strFileName) 
     strFileName = Right(strFileName, intLength - 7) 
    End If 

    If Right(strFileName, 10) = " Adamsville" Then 
     intLength = Len(strFileName) 
     strFileName = Left(strFileName, intLength - 10) 
    End If 

    strNewName = strPath & strFileName & "." & strExtension 
    errResult = objFile.Rename(strNewName) 
Next 

请帮助

+1

VBScript!= VB.Net!= VB6。 IOW,它们不是同义词 - 它们是三种不同的语言。请仅使用** **相关标签(本例中为'vbscript')。谢谢。 – 2014-09-05 15:54:25

回答

-2

学习计数:

>> WScript.Echo Len(" Adamsville") 
>> 
11 
>> 

或写一个函数:

>> Function endsWith(b, t) 
>> endsWith = Right(b, len(t)) = t 
>> End Function 
>> WScript.Echo CStr(endsWith("Fulton A1032-CCC Adamsville", " Adamsville")) 
>> 
True 

更新WRT downvotes:

随着downvotes表明,至少有两个人谁也不能指望两种:

Option Explicit 

Function qq(s) : qq = """" & s & """" : End Function 

Dim strFileName : strFileName = "Fulton A1032-CCC Adamsville" 
Dim intLength 
WScript.Echo 0, qq(strFileName) 

' assume the structure of the input data is: 
' <todelete+blank><tokeep><blank+todelete> 
WScript.Echo 1, qq(Split(strFileName)(1)) 

' the ot's code 'works' if you count correctly 
If Left(strFileName, 7) = "Fulton " Then 
    intLength = Len(strFileName) 
    strFileName = Right(strFileName, intLength - 7) 
End If 
If Right(strFileName, 11) = " Adamsville" Then 
    intLength = Len(strFileName) 
    strFileName = Left(strFileName, intLength - 11) 
End If 
WScript.Echo 2, qq(strFileName) 

输出:

cscript 25689666.vbs 
0 "Fulton A1032-CCC Adamsville" 
1 "A1032-CCC" 
2 "A1032-CCC" 
+0

你会如何处理文件名前后各种数量的字符。中间将是相同数量的字符。 – 2014-09-08 17:28:07

1

为什么不直接用替换功能呢?例如:

Dim fileName As String 

fileName = "Fulton A1032-CCC Adamsville" 

fileName = Replace(fileName, "Fulton ", "") 
fileName = Replace(fileName, " Adamsville", "") 

MsgBox fileName 

输出是A1032-CCC。如果搜索字符串中的任何一个或两个都不存在,这也适用。