hta используя vbscript - пути и другой текст с пробелами, представленными в виде переменных, в другой строке кода - PullRequest
0 голосов
/ 27 марта 2012

Моя регистрация здесь является ярким свидетельством прекрасных ответов, которые я нашел здесь раньше.Я надеюсь, что кто-то может помочь мне с тем, что, как мне кажется, должно быть простой проблемой, если нет, я боюсь быстрого увеличения облысения.

Я создал файл HTA для выполнения операций с файлами, переименования, копирования, добавленияна дату и т. д.

Моя проблема в том, что у меня есть несколько переменных, которые установлены равными путям к файлам, которые содержат пробелы.другие переменные установлены для пользовательского ввода, который будет включать пробелы.Эти переменные затем используются в других строках кода.Но эти другие строки обрываются, когда они освобождают место в «расширенном» переменной.

Например, вот одна строка, в частности, приводящая меня к стене.

Sub makemp3
If mp3radio(0).Checked Then
    Set objShell = CreateObject("Wscript.Shell")
    objShell.Run "cmd.exe /c " &lameexe& " " &defaultpathfile& " " &sermonmp3folder& "\" &newfile& ".mp3"
Else
End If
End Sub

В приведенном вышеВ этом случае переменные устанавливаются в начале блока скрипта на ...

lameexe="D:\LAME\lame3.99.5-libsndfile\lame.exe"
defaultpathfile = sermonflacfolder&"\"&defaultflac
sermonmp3folder = "D:\SermonMP3"
newfile = datebox.value&"_"& titlebox.value

База данных заполняется подсчетом ...

'pouplate input boxes with variables as default text
'==============================================
sub Window_onload
  Set WshShell = CreateObject("WScript.Shell")
  Set ObjEnv = WshShell.Environment("Process")
  datebox.value = calcdate
end sub

, в свою очередьсозданный другим подпрограммой ...

'setup and perform date calculations
'======================================
days=DatePart("d", now)
monthdig=DatePart("m", now)
years=DatePart("yyyy", now)
amps=Hour(now)

If monthdig <10 Then months="0"&monthdig Else months=monthdig

If amps <15 Then apm="am" Else apm="pm"

calcdate = years&"_"&months&"_"&days&"_"&apm

titlebox в настоящее время является просто пользовательским вводом ... ожидаемый ввод будет похож на

What are we here for

или

Rev Phillip Smith

Во всех чтениях, которые я читал в Интернете, есть кое-что, чего я просто не понимаю, об экранировании кавычек, двойных кавычек и chr (34).

эта страница выглядит обнадеживающей, но я не смог сделатьон работает с переменными в моем скрипте.

http://groups.google.com/group/microsoft.public.scripting.vbscript/browse_thread/thread/2ca422f55628ea5e

Кроме того, эта страница была самой словесной по теме, но все же не показала использование переменных, которые сами по себе не имеютпробелы, но строка внутри них делает.

groups.google.com / group / microsoft.public.scripting.vbscript / browse_thread / thread / 2ca422f55628ea5e

У меня нет сил ... Пожалуйста, помогите.Спасибо, Дэвид

<script language="VBScript">



'
'
'deleteoldreapertemp subroutine adapted from:
'http://groups.google.com/group/microsoft.public.scripting.wsh/msg/14df6623fc552446
'
'
'explaination of variables...
'
'windowwidth... the desired width of the script window
'windowlength... the desired length of the script window
'sermonflacfolder... the desired location reaper renders the sermon file to
'defaultflac... this is the name used when the sermon file is rendered
'calcdate... uses date variables to create the default flac file name
'defaultpathfile... a shortcut to use intead of sermonflacfolder&"\"&defaultflac
'tempdir... where reaper stores its temp files
'killdate... files older than this value will be deleted from reaper temp directory

'Manually set variables
'=================================
windowwidth = 400
windowlength = 500
sermonflacfolder= "D:\SermonFLAC"
defaultflac="test.flac"
defaultpathfile = sermonflacfolder&"\"&defaultflac
tempdir = "D:\reaper temp dir"
sermonmp3folder = "D:\SermonMP3"
lameexe="D:\LAME\lame3.99.5-libsndfile\lame.exe"
killdaysold = 14

'setup and perform date calculations
'======================================
days=DatePart("d", now)
monthdig=DatePart("m", now)
years=DatePart("yyyy", now)
amps=Hour(now)

If monthdig <10 Then months="0"&monthdig Else months=monthdig

If amps <15 Then apm="am" Else apm="pm"

calcdate = years&"_"&months&"_"&days&"_"&apm

killdate = date() &" - "& killdaysold


'resize script window before it is drawn... avoids flicker
'==========================================
Sub resizewindow
    window.resizeTo windowwidth,windowlength
end Sub
resizewindow()



'position script window at center of screen
'============================================
sub centerwindow
    screenWidth = Document.ParentWindow.Screen.AvailWidth
    screenHeight = Document.ParentWindow.Screen.AvailHeight
    posLeft = (screenWidth - windowwidth) / 2
    posTop = (screenHeight - windowlength) / 2    
    'move to centerscreen
    window.moveTo posLeft, posTop
  end sub
centerwindow()



'pouplate input boxes with variables as default text
'==============================================
sub Window_onload
  Set WshShell = CreateObject("WScript.Shell")
  Set ObjEnv = WshShell.Environment("Process")
  datebox.value = calcdate
end sub





</script>


















<head>
<title>HTA Test</title>
<HTA:APPLICATION 
     APPLICATIONNAME="RENAMER"
     SCROLL="NO">
</head>






<body>
<body bgcolor=c0c0c0>

<!text boxes setup here>
<!=====================================================================>
<p>

Accept calculated date and service (am or pm)<br>
or input correct date and service<br>
(yyyy_mm_dd_am)<br>

<input type="text" name="datebox" onclick="datebox.value=''">




<p>
<br>
Input sermon title <br>
<input type="text" name="titlebox" onfocus="titlebox.value=''">
<input type="button" name="examplesbutton" value="Examples" onClick="examplesclick" style="float: right;">
<br>
<br>
Create archive MP3?
<br>
Yes<input type="radio" name="mp3Radio" value="1" checked="true">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
No<input type="radio" name="mp3Radio" value="2">
<p>
Shutdown computer when script finishes?
<br>
Yes<input type="radio" name="shutdownRadio" value="1" checked="true">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
No<input type="radio" name="shutdownRadio" value="2" >
<br>
<br>
<br>
<input type="button" name="settingsbutton" value="Settings" onClick="settingsclick" style="float: left;">
<input type="button" name="runbutton" value="Run Script" onClick="MASTERSUB" style="float: right;">
<p> 



</body>























<script language="VBScript">



'CHECKING "DOES DEFAULT SERMON FILE EXIST?"
'=========================================
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(defaultpathfile)) Then
Else 
Msgbox "Default sermon file not found at:" & vbnewline & sermonflacfolder & "\" & defaultflac & vbnewline & vbnewline & "Check settings in Reaper (File\Render menu)" & vbnewline & vbnewline &  "Click Ok to exit script"
exitscript()
End If








Sub MASTERSUB
    lastchance
    deleteoldreapertemp
    rename
    makemp3
    checkfornewflac
    checkfornewmp3
    deletedefaultflac
    shutdownsub
End Sub





'MASTERSUB runs all the contained sub subs
'=====================================================
'=====================================================
'=====================================================
dim shutdownverify
dim newfile
dim newflacfound
dim newmp3found



Sub Delay ( seconds )
    Dim wshShell
    Set wshShell = CreateObject( "WScript.Shell" )
    wshShell.Run "ping -n " & ( seconds + 1 ) & " 127.0.0.1", 0, True
    Set wshShell = Nothing
End Sub




'last chance to abort shutdown
'=====================================================
Sub lastchance
    If shutdownradio(0).Checked Then
        lastchanceanswer = _
            Msgbox("Computer will shutdown when script finishes", _
             vbYesNo, "Last chance to abort shutdown")
            If lastchanceanswer = vbYes Then
                shutdownverify = "yes"
            Else
                shutdownverify = "no"
            End If
    Else
    End If
End Sub





'attempt to rename defaultflac
'=======================================================
Sub rename
newfile = datebox.value&"_"& titlebox.value
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    objFSO.CopyFile defaultpathfile , sermonflacfolder&"\"&newfile&".flac"
End Sub




'encode an mp3 version of the defaultflac file (only if the "yes" mp3 radio button is checked)
'===============================================
Sub makemp3
    If mp3radio(0).Checked Then
        Set objShell = CreateObject("Wscript.Shell")
        objShell.Run "cmd.exe /c " &lameexe& " " &defaultpathfile& " " &sermonmp3folder& "\" &newfile& ".mp3"
    Else
    End If
End Sub


'check if new flac is was created successfully
'===============================================
Sub checkfornewflac
Delay 10
Dim count
count = 1

    Do 
        If (fso.FileExists(sermonflacfolder&"\"&datebox.value&"_"&titlebox.value&".flac")) Then
            newflacfound = "yes"
            'msgbox "new flac file found flag set to "&newflacfound
            Exit Sub            
        Else
            count=count+1
                If count >4 Then
                    newflacfound = "no"
                    'msgbox "new flac not found, flag set to "&newflacfound
                    Exit Sub
                Else
                End If
            Delay 10
        End If
    Loop 
End Sub





'check if mp3 was created sucessfully
'===============================================
Sub checkfornewmp3
Dim count
count = 1
If mp3radio(0).Checked Then
    Do 
        If (fso.FileExists(sermonmp3folder&"\"  & newfile & ".mp3")) Then
            newmp3found = "yes"
            'msgbox "new mp3 file found flag set to "&newmp3found
            Exit Sub            
        Else
            count=count+1
                If count >4 Then
                    newmp3found = "no"
                    'msgbox "new mp3 not found, flag set to "&newmp3found
                    Exit Sub
                Else
                End If
            Delay 10
        End If
    Loop 
End If
End Sub






'Delete default file
'=============================================
Sub deletedefaultflac
Delay 90
    If newflacfound = "yes" Then
        If newmp3found = "yes" Then
            set objFSO = createobject("Scripting.FileSystemObject")
            objFSO.DeleteFile defaultpathfile
        Else
            set objFSO = createobject("Scripting.FileSystemObject")
            objFSO.MoveFile defaultpathfile , sermonflacfolder&"\"& "aaERROR" &newfile&".flac"
        End If
    Else
        set objFSO = createobject("Scripting.FileSystemObject")
        objFSO.MoveFile defaultpathfile , sermonflacfolder&"\"& "00000_ERROR_" &newfile&".flac"
    End If
End Sub









'Delete old reaper temp files
'===========================================
Sub deleteoldreapertemp
'msgbox "starting 1sub"
    arFiles = Array()
    set fso = createobject("scripting.filesystemobject")

selectfiles path, killdate, arFiles, true

    nDeleted = 0
        for n = 0 to ubound(arFiles)
  '=================================================
  ' Files deleted via FSO methods do *NOT* go to the recycle bin!!!
  '=================================================
  on error resume next 'in case of 'in use' files...
  arFiles(n).delete true
  if err.number <> 0 then
    wscript.echo "Unable to delete: " & arFiles(n).path
  else
    nDeleted = nDeleted + 1
  end if
  on error goto 0
next

'msgbox nDeleted & " of " & ubound(arFiles)+1 _
'  & " eligible files were deleted"
'msgbox "end 1 sub"
End Sub




sub selectfiles(sPath,vKillDate,arFilesToKill,bIncludeSubFolders)
  set folder = fso.getfolder(tempdir)
  set files = folder.files

'msgbox "startng 2 sub"


  on error resume next

  for each file in files
    ' uses error trapping around access to the
    ' Date property just to be safe
    '
    dtlastmodified = null
    on error resume Next
    dtlastmodified = file.datelastmodified
    on error goto 0
        if not isnull(dtlastmodified) Then
            if dtlastmodified < vKillDate then
                count = ubound(arFilesToKill) + 1
                redim preserve arFilesToKill(count)
                set arFilesToKill(count) = file
            end if
        end if
next

  if bIncludeSubFolders then
    for each fldr in folder.subfolders
      SelectFiles fldr.path,vKillDate,arFilesToKill,true
    next
  end if
end sub 
































'shutdown computer (only if the "yes" shutdown radio button is checked)
'=======================================================================
Sub shutdownsub
    If shutdownverify= "yes" Then
        Set objShell = CreateObject("Wscript.Shell")
        'msgbox "shutdown ran!"
        objShell.Run "shutdown.exe -s -t 5"
    Else
        exitscript
    End If
End Sub



'=====================================================
'=====================================================
'=====================================================







'clicking the "settings" button runs this routine
'===================================================
Sub settingsclick
    Msgbox "Default sermon filename is set to:     " & defaultflac & vbnewline & "Storage area for sermon flacs is set to:     " & sermonflacfolder & vbnewline & "Storage location for sermon mp3's set to:   " & sermonmp3folder & vbnewline & "Path to Lame.exe (with flac support) set to:   " & lameexe & vbnewline

End Sub


'clicking the "Examples" button runs this routine
'===================================
Sub examplesclick
    Msgbox "Capitalize the first letter of the sermon title" & vbNewLine & "Capitalize the names of God" & vbNewLine & "For guest speaker, use their name as the title" & vbNewLine & "Here are some examples:"& vbNewLine & vbNewLine &"What hath God wrought"& vbNewLine & "The ABCs of life" & vbNewLine & "Dr Jimmy Stewart"

End Sub


'if no defaultflac file found, exit script
'=========================================
Sub exitscript
    window.close
End Sub






</script>

1 Ответ

0 голосов
/ 27 марта 2012

Пути, содержащие пробелы в командной строке, должны быть заключены в двойные кавычки.В VBScript вы можете удваивать кавычки, и они будут разбираться в вашей строке, но это очень сложно для чтения.Я предлагаю добавить внутреннюю константу vbQuote или использовать Chr(34), которые оба возвращают литерал ".

objShell.Run "cmd.exe /c " & lameexe & " " & Chr(34) & defaultpathfile & Chr(34) & " " & Chr(34) & sermonmp3folder& "\" &newfile& ".mp3" & Chr(34)

Важнейшими частями являются:

Chr(34) & defaultpathfile & Chr(34)

и

Chr(34) & sermonmp3folder& "\" &newfile& ".mp3" & Chr(34)

Обратите внимание, как я окружаю пути к файлам символами двойной кавычки.Это вернет строки, содержащие двойные кавычки.

Ваше чтение как бы направило вас в неправильном направлении.Не думайте об этом как о кавычках.Вы фактически вставляете их в свою строку.

...