Return filename in VBS
Is it possible to return the name of a File / program by a VBS script? Type to drag and drop in script or open with... the script, it returns the name.
2 answers
Wscript.Arguments
recognizes the file in the sequence of parameters as if it were a normal executable and with GetFileName
you can take the name and GetAbsolutePathName
will take the full path.
An example script:
Dim Arg
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Verifica se selecionou arrastou ao menos um arquivo
If WScript.Arguments.Count > 0 Then
'Itera todos arquivos que soltou em uma ação
For Each Arg in Wscript.Arguments
'Remove possíveis espaços
Arg = Trim(Arg)
Set objFile = objFSO.GetFile(Arg)
'Exibe um dialogo somente para testes
MsgBox("Nome: " & objFSO.GetFileName(objFile) & " - caminho: " & objFSO.GetAbsolutePathName(objFile))
Next
End If
Working example of the script:
If you want to limit to only one file, then change the line:
If WScript.Arguments.Count > 0 Then
For
If WScript.Arguments.Count = 1 Then
Should look like this:
Dim Arg
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Verifica se selecionou arrastou um arquivo
If WScript.Arguments.Count = 1 Then
'Itera todos arquivos que soltou em uma ação
For Each Arg in Wscript.Arguments
'Remove possíveis espaços
Arg = Trim(Arg)
Set objFile = objFSO.GetFile(Arg)
'Exibe um dialogo somente para testes
MsgBox("Nome: " & objFSO.GetFileName(objFile) & " - caminho: " & objFSO.GetAbsolutePathName(objFile))
Next
End If
To check if it is a file and not a folder, use FileExists
/FolderExists
An example that checks if it is file and how many you selected:
Dim Arg
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Verifica se selecionou arrastou ao menos um arquivo
If WScript.Arguments.Count = 1 Then
'Itera todos arquivos que soltou em uma ação
For Each Arg in Wscript.Arguments
'Remove possíveis espaços
Arg = Trim(Arg)
If objFSO.FileExists(Arg) Then
Set objFile = objFSO.GetFile(Arg)
'Exibe um dialogo somente para testes
MsgBox("Nome: " & objFSO.GetFileName(objFile) & " - caminho: " & objFSO.GetAbsolutePathName(objFile))
Else
MsgBox("Este arquivo não existe ou é uma pasta")
End If
Next
ElseIf WScript.Arguments.Count > 1 Then
MsgBox("Você mais de um arquivo")
Else
MsgBox("Você não selecionou nenhum arquivo")
End If
Note: save the file .vbs as ANSI (windows-1252 or iso-8859-1 or compatible), UTF-8 or other unicode type may not be displayed in
MsgBox
(unless you make adjustments to the script)
Yes, it is possible. See the FileSystemObject :
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("C:\Scripts\Test.txt")
Wscript.Echo "File name: " & objFSO.GetFileName(objFile)