根据文件名移动文件

时间:2015-07-20 14:43:31

标签: powershell batch-file vbscript

我有一台联网的PDF打印机。它具有自动保存功能,但不允许我保存在用户指定的文件夹中(例如\\server\users\<username>\pdfs\)。

它允许在保存后运行程序。所以,我需要的是在保存后运行的脚本,并根据文件名将文件移动到该特定用户的保存目录。

目前,自动保存是使用username<date/time>.pdf生成的,因此我需要一个脚本:

  1. 扫描将自动保存的文件夹
  2. 从文件名中提取用户名并将文件移至\\servername\users\<username>\pdfs\
  3. 我的Googlefu工作效果不佳,我的脚本编写能力非常有限。任何帮助表示赞赏。

    目前我正在与之合作:

    $autoSaveDir = "c:\autosave"
    $userDir = "c:\userdir\%username%\pdfs"
    $regexFirstNumber = "^[^\d]*(\d+)"
    
    #iterate through the auto save directory
    Get-ChildItem -Path $autoSaveDir -File | ForEach-Object {
      #find the username portion of the file by splitting on the first number in the filename
      $dateInFileName = [regex]::split($_.Name,'^[^\d]*(\d+)')
    
      $fileNameParts = $_.Name -split $dateInFileName[1]
      $userName = $fileNameParts[0]
    
      $newFile = $userDir -replace "%username%", $username
      $newFile = $newFile + "\" + $_.Name
    
      #copy the file over - doesn't check to make sure the folders are there first though
      Copy-Item $_.FullName $newFile
    }
    

2 个答案:

答案 0 :(得分:0)

这个VBScript应该做你需要的:

With CreateObject("Scripting.FileSystemObject")
    For Each File In .GetFolder("c:\autosave").Files
        If StrComp(.GetExtensionName(File.Name), "pdf", vbTextCompare) = 0 Then

            strUser     = .GetBaseName(File.Path)
            strUserRoot = .BuildPath("c:\userdir", strUser)
            strUserPdf  = .BuildPath(strUserRoot, "pdfs")

            If Not .FolderExists(strUserRoot) Then .CreateFolder strUserRoot
            If Not .FolderExists(strUserPdf)  Then .CreateFolder strUserPdf

            File.Move strUserPdf & "\"

        End If
    Next
End With

修改

如果文件以yyyymmddhhnnssUsername.pdf格式命名,则只需删除前14个字符以确定用户名:

strUser = Mid(.GetBaseName(File.Path), 15)

移动文件时,它仍将包含时间戳。

答案 1 :(得分:0)

这是我的回答感谢邦德!

With CreateObject("Scripting.FileSystemObject")
For Each File In .GetFolder("c:\pdfcreator").Files
    If StrComp(.GetExtensionName(File.Name), "pdf", vbTextCompare) = 0 Then

        strUser = Mid(.GetBaseName(File.Path), 15)
        strUserRoot = .BuildPath("C:\Network Storage\Userstorage", strUser)
        strUserPdf  = .BuildPath(strUserRoot, "pdfs")

        If Not .FolderExists(strUserRoot) Then .CreateFolder strUserRoot
        If Not .FolderExists(strUserPdf)  Then .CreateFolder strUserPdf

        File.Move strUserPdf & "\"

    End If
Next
End With