VBS 使用 LIKE 比较字符串 "Sub or Function not defined"

VBS using LIKE to compare strings "Sub or Function not defined"

我正在尝试制作一个脚本来将网络打印机连接到用户计算机。 该脚本使用需要打印机的计算机名称作为参数。

打印机名称与其打印服务器名称相似,例如。 server_USA 有像 printer_USA01、printer_USA02.

这样的打印机

但是它在到达第一个时抛出错误 "Sub or Function not defined" 就像...为什么?

Set shl = WScript.CreateObject("WScript.Shell")
strName = Wscript.Arguments.Item(0)

'input Printer name
strPrinter = InputBox("Please enter share name of printer to install:", _
    "Add network printer")

if strPrinter = "" then
    msgbox "Can't be empty."
    WScript.quit

elseif strPrinter Like "printer_USA*" then
    strServer = server_USA

elseif strPrinter Like "printer_SPAIN*" then
    strServer = server_SPAIN

else
    'Printer name NOT registered, input printserver manually:
    strServer = inputbox("Please enter the name of the printserver","printserver")

    if strServer = "" then
        msgbox "Can't be empty."
        WScript.quit
    End if

End if

'ADD
shl.run "RUNDLL32 PRINTUI.DLL,PrintUIEntry /ga /c\" & strName & " /n\" & strServer & "\" & strPrinter

VBScript 中没有 Like 运算符。你可以使用 Instr.

if strPrinter = "" then
    msgbox "Can't be empty."
    WScript.quit

elseif Instr( 1, strPrinter, "printer_USA", vbTextCompare ) > 0 then
    strServer = server_USA

vbTextCompare 常量(值=1)用于执行文本比较

您可以使用 StrComp 以这种方式获得相同的结果

    If StrComp(strPrinter,"printer_USA",vbTextCompare)=0 then  
    strServer = server_USA
    End IF

等于 0 表示 strPrinter[=14= 之间的差异为零] 忽略字母大小写,因为我们使用 vbTextCompare

您可以将vbTextCompare替换为1,您将得到相同的结果。

如果字母大小写很重要,您可以使用 vbBinaryCompare0.

一种使用 select 大小写的方法。这个版本的 instr() 区分大小写,但其他版本不区分大小写。 instr() returns找到的子串的位置,这里总是一个

select case 1
  case instr(strPrinter, "") + 1
    wscript.echo "empty"
  case instr(strPrinter, "printer_USA")
    wscript.echo "server_USA"
  case instr(strPrinter, "printer_SPAIN")
    wscript.echo "server_SPAIN"
  case instr(strPrinter, "printer_ITALY"), instr(strPrinter, "printer_RUSSIA")
    wscript.echo "other known ones"
  case else
    wscript.echo "not registered"
end select

我使用了以下替代方法(VBScript 正则表达式)... 使用与 LIKE 略有不同的语法但最简单的解决方案来成功匹配类似于 LIKE 运算符。

dim regExp
set regExp=CreateObject("VBScript.RegExp")
regExp.IgnoreCase = true
regExp.Global = true
regxp.Pattern = ".*Test Pattern.*" ' example only, basic pattern

if regExp.Test(MyString) then
    ' match successful
end if