【问题标题】:PowerShell script to move files to multiple network drives用于将文件移动到多个网络驱动器的 PowerShell 脚本
【发布时间】:2018-02-23 21:32:06
【问题描述】:

我无法让此脚本在 Windows Servers 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 个网络驱动器(一个可以工作,一个不工作),只留下 SERVER1,它不是通过任务计划程序复制文件,而是手动复制文件。我已经进入 SERVER3 并查看了共享的权限,但它们与 SERVER1 相似。

标签: powershell scheduled-tasks


【解决方案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

我很确定我可以在没有写入文件的情况下解决错误,但我会留下它以防万一。

另外,缺点是密码是纯文本的,任何有权访问脚本的人都可以看到它。

【讨论】:

    【解决方案2】:
    $SHARE1 = "\\SERVER1\SHARE\1",
    $SHARE2 = "\\SERVER2\SHARE\2",
    

    末尾缺少双引号

    【讨论】:

    • 抱歉,这是我的错字。
    猜你喜欢
    • 2018-04-17
    • 2011-06-08
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多