使用VBScript从网络文件夹移动文件 [英] Moving Files from Network Folder Using VBScript

查看:127
本文介绍了使用VBScript从网络文件夹移动文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的脚本,可以从我们的一台服务器映射一个共享文件夹.然后将所有文件从其中的一个文件夹移动到本地计算机.我在Windows Scheduler中创建了一个条目,以每10分钟运行一次此脚本.登录计算机后,脚本可以正常工作.

I have a simple script that maps a shared folder from one of our servers. And then move all the files from one of the folders in it to the local machine. I created an entry in windows scheduler to run this script every 10 minutes. The script works fine when I am logged in the machine.

我的问题是,当我没有登录计算机时,脚本不会移动文件.

The problem that I have is that, the script doesnt move the files when I am not logged in the machine.

我做了很多搜索,但是还没有找到任何解决方案.感谢您的提前帮助.

I did a lot of searching but have not found any solution to this yet. Thanks for your help in advance.

下面是我的脚本.

Set objNetwork = CreateObject("WScript.Network")
sUserName = objNetwork.UserName
Dim aNetworkDrives(4, 2)
'
aNetworkDrives(0, 0) = "Z:"
aNetworkDrives(0, 1) = "<a href="file://pronto.grahamgroup.local/gdb">\\pronto.grahamgroup.local\gdb</a>"
'
sPersistent = "FALSE"
sUsername = "MyUserNameHere"
sPassword = "MyPasswordHere"

'
'Map network drive(s)
'
Set oCheckDrive = objNetwork.EnumNetworkDrives()

On Error Resume Next

For iNetDriveCounter = 0 To Ubound(aNetworkDrives, 1) - 1 Step 1

bAlreadyConnected = False

For iCheckCounter = 0 To oCheckDrive.Count - 1 Step 1

IF oCheckDrive.Item(iCheckCounter) = aNetworkDrives(iNetDriveCounter, 0) THEN 

bAlreadyConnected = True

END IF

Next

IF bAlreadyConnected = False THEN

objNetwork.MapNetworkDrive aNetworkDrives(iNetDriveCounter, 0),
    aNetworkDrives(iNetDriveCounter, 1), sPersistent, sUsername, sPassword

END IF

Next

'

'Move files

'

sSource= "Z:\francistestfolder" 

sDestination= "C:\Documents and Settings\francisp\Desktop\test map\b\" 

getFolder sSource, sDestination

Function getFolder(ByVal sSource, ByVal sDestination)

    Dim fso, file, files

Set fso = CreateObject("Scripting.FileSystemObject") 

    If fso.FolderExists(sSource) Then

        For Each file In fso.GetFolder(sSource).Files

            'WScript.Echo file

sDestinationFileName = sDestination & file.Name

            If fso.FileExists(sDestinationFileName) Then

                sDestinationFileName = RenameFile(sDestinationFileName)

            End If

            file.Move(sDestinationFileName)

        Next

Else 

    Exit Function

End If 

End Function

Function RenameFile(ByVal sFileName)

RenameFile = sFileName & Year(Now) & Month(Now) & Day(Now) & Hour(Now) & 
    Minute(Now) & Second(Now)

End Function

推荐答案

找到了一些不同的脚本进行复制.

检查是否可以帮助您
http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/filesfolders/files/

Found a little different script for copying.

Check if this can help you
http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/filesfolders/files/


这听起来像您需要创建Windows服务.即使未登录,Windows服务也将运行.当然,您必须具有Admin特权,并且VBScript必须位于C#或VB中.

以下代码(在C#中)可用于创建Windows服务,该服务每10秒移动一次文件,如果目标文件夹中已经存在要移动的文件,则重命名文件.
This sounds like you need to create a Windows Service. A windows service will run even when you are not logged in. Of course to do that, you would have to have Admin privileges and the VBScript would have to be in C# or VB.

The following code (in C#) can be used to create a windows service to move files every 10 seconds and rename files if the file being moved already exists in the destination folder.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;
namespace Cron
{
    partial class Service2 : ServiceBase
    {
        private Timer ti = new Timer();
        private string fileTime;
        private string[] theCommands = new string[2];
        private EventLog eventLog1 = new EventLog();
        private FileStream fs;

        public Service2()
        {
            InitializeComponent();
            //This is a timer where code can run once the timer is up.
            ti.Elapsed += new ElapsedEventHandler(ti_Elapsed);
            //This sets the 10 second interval.  Every 1000 is one second.
            ti.Interval = 10000;
            ti.Enabled = true;
            //This sets up the Event log which is viewable in the 
            if (!System.Diagnostics.EventLog.SourceExists("CronMessage"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                   "CronMessage", "CronLog");
            }
            eventLog1.Source = "CronMessage";
            eventLog1.Log = "CronLog";
        }
        void ti_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                MoveFiles(theCommands[0], theCommands[1]);
            }
            catch (Exception ex)
            {
                eventLog1.WriteEntry(ex.Message, EventLogEntryType.Error);
            }
        }
        public void MoveFiles(string sourceFolder, string destFolder)
        {
            try
            {
                DateTime dt = DateTime.Now;
                string year = dt.Year.ToString("0000");
                string month = String.Format("{0:MMM}", dt);
                string day = dt.Day.ToString("00");
                string hour = dt.Hour.ToString("00");
                string min = dt.Minute.ToString("00");
                string sec = dt.Second.ToString("00");
                string time = year + month + day + "_" + hour + min + sec;
                
                if (Directory.Exists(destFolder))
                {
                    string[] files = Directory.GetFiles(sourceFolder);
                    foreach (string file in files)
                    {
                        string name = Path.GetFileName(file);
                        string dest = Path.Combine(destFolder, name);
                        if (File.Exists(dest))
                        {
                            name = Path.GetFileNameWithoutExtension(file) + time + Path.GetExtension(file);
                        }
                        dest = Path.Combine(destFolder, name);
                        File.Move(file, dest);
                    }
                    //This checks for sub-folders and moves those files also.
                    //If this is not desired, this can be commented out.
                    string[] folders = Directory.GetDirectories(sourceFolder);
                    foreach (string folder in folders)
                    {
                        string name = Path.GetFileName(folder);
                        string dest = Path.Combine(destFolder, name);
                        MoveFiles(folder, dest);
                    }
                }
                else
                {
                    throw new Exception("Folder does not exist!\nPlease check the file: " + fs.Name);
                }
            }
            catch (Exception ex)
            {
                eventLog1.WriteEntry(ex.Message, EventLogEntryType.Error);
            }
        }
        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            eventLog1.WriteEntry("Cron Backup service started.");
            //The text file contains the source and destination
            //folders is opened here.
            fs = File.OpenRead("C:\\Path\\to\\text\\file");
            StreamReader sr = new StreamReader(fs);
            sr.ReadLine();//This ignores the [Source Folder] line.
            theCommands[0] = sr.ReadLine();
            sr.ReadLine();//This ignores the blank line.
            sr.ReadLine();//This ignores the [Destination Folder] line.
            theCommands[1] = sr.ReadLine();
            fs.Close();
        }
        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            eventLog1.WriteEntry("Cron Backup service stopped.");
        }
    }
}



该文本文件可以包含UNC路径(即\\ servername \ somefolder),并且只要本地系统帐户有权访问该文件夹就可以使用.
文本文件示例:



The text file can contain a UNC Path (i.e. \\servername\somefolder) and should work as long as the Local System account has access to that folder.

Example of Text file:

[Source Folder]<br />
\\ServerName\some_Folder<br />
<br />
[Destination Folder]<br />
C:\Some_Folder<br />



如果人们对此有足够的兴趣,我可以详细说明.



If people have enough interest in this, I can expound on the subject.


这篇关于使用VBScript从网络文件夹移动文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆