首页 文章

用于将文件移动到多个网络驱动器的PowerShell脚本

提问于
浏览
1

我无法让这个脚本在Windows Server 2012 R2任务计划程序中正确运行,当我从PowerShell ISE运行它时运行正常并将文件复制到所有3个服务器映射的网络驱动器,但是,从任务计划程序它只复制文件到最后映射的驱动器和bkup文件夹 . 我希望你们能帮助我获得正确的配置,这里是代码:

param (
$src = "C:\Users\user\Documents\SRC_FOLDER",
$bkup = "C:\Users\user\Documents\BKUP_FOLDER",
$SHARE1 = "\\SERVER1\SHARE\1",
$SHARE2 = "\\SERVER2\SHARE\2",
$SHARE3 = "\\SERVER3\SHARE\3"
)

$mappedUnits = $bkup, $SHARE1, $SHARE2, $SHARE3

foreach ($mappedUnit in $mappedUnits)
{
    Get-ChildItem $src | Copy-Item  -Destination $mappedUnit -Recurse -Force
}

#Get-ChildItem $src | Remove-Item

任务计划程序设置为以域管理员身份运行(也尝试使用本地管理员帐户),并且作为最高权限,它每10分钟运行一次,它会调用powershell(完整路径为.exe),参数: -ExecutionPolicy Unrestricted -File "MOVE-FILES.ps1" 并且选项 Start in 已设置到脚本的路径 .

我已经尝试了很多类型的配置,这是最新的配置,就像我之前提到的那样,它在手动执行时有效,但不能从任务调度程序执行 .

2 回答

  • 1

    我找到了解决问题的方法,我不得不调用New-PSDrive并为其分配凭据 . 我会为寻找类似内容的人发布答案:

    [string][ValidateNotNullOrEmpty()] $userPassword = "password"
    $username = "user"
    $password = ConvertTo-SecureString -String "password" -AsPlainText -Force
    $computers = gc "C:\path\to\file\machines.txt"
    $source = "C:\path\to\source"
    $destination = "path\to\destination\server"
    $bkup = "path\to\backup\folder"
    $creds = new-object -typename System.Management.Automation.PSCredential `
             -argumentlist $username, $password
    foreach ($computer in $computers)
    {
        if (test-Connection -Cn $computer -quiet)
        {
            New-PSDrive -Name Y -PSProvider filesystem -Root "\\$computer\$destination" -Credential $creds
            Copy-Item $source -Destination Y:\ -Recurse -ErrorAction SilentlyContinue -ErrorVariable A
            if($A) { write-Output "$computer - File copy Failed" | out-file "C:\File Transfer\BIOS_Copy.txt" -Append }
            Remove-PSDrive Y
        }
        else
        {
            Write-Output "$computer is offline" | Out-File "C:\File Transfer\BIOS_Copy_error.txt" -Append
        }
    }
    
    Get-ChildItem $source | Copy-Item -Destination $bkup -Force
    
    Get-ChildItem $source | Remove-Item -Force
    

    我很确定我可以在没有写入文件的情况下做错,但是我会留下它以防万一 .

    此外,缺点是密码是纯文本的,任何有权访问该脚本的人都能看到它 .

  • 0
    $SHARE1 = "\\SERVER1\SHARE\1",
    $SHARE2 = "\\SERVER2\SHARE\2",
    

    最后缺少双引号

相关问题