0

目标:使用机器名称和当前登录用户的变量从网络上的多台机器复制到网络共享。

我所拥有的:带有计算机名列表的 txt 文件。

问题:我无法让 foreach 与我在用户名变量上使用的 .split("\")[1] 一起工作以删除域前缀,因此我可以使用 robocopy 路径中的输出

就像是

    robocopy "\\$computername\c$\documents and settings\$username\backup" "\\networkshare\backup\$username\backup"

给我错误 您不能在空值表达式上调用方法。在 C:\Scripts\Test\backup.ps1:13 char:2

这是我到目前为止所拥有的。有人可以帮忙吗?

function Get-LoggedIn {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$True)]
        [string[]]$computername
    )

    foreach ($pc in $computername){
        $logged_in = (gwmi win32_computersystem -COMPUTER $pc).username
        $name = $logged_in.split("\")[1]
        "{1}" -f $pc,$name
    }
}

$computers = Get-Content "C:\Scripts\testcomputers.txt"

foreach ($computer in $computers) {
    $users = Get-LoggedIn $computer
}       

$SourceFolder = "\\$computer\c$\users\$users\desktop"
$DestinationFolder = "\\networkshare\backups\$users\backup\desktop"
$Logfile = "\\networkshare\backups\$users\backup\backuplog.txt"

Robocopy $SourceFolder $DestinationFolder /E /R:1 /W:1 /LOG:$Logfile
4

1 回答 1

0

我在这里看到多个错误。您没有在 foreach 循环中运行复制命令。从 WMI 接收的用户名属性通常可以采用以下格式:

domain\computer\username (or computer\domain\username, unsure since I'm on non-domain workstation now)

无论如何,用户名始终是最后一部分,因此请改用索引[-1]来获取它。更新的脚本(带有缩进!):

function Get-LoggedIn {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$True)]
        [string[]]$computername
        )

    foreach ($pc in $computername){
        $logged_in = (gwmi win32_computersystem -COMPUTER $pc).username
        $name = $logged_in.split("\")[-1]
        "{1}" -f $pc,$name
    }
}

$computers = Get-Content "C:\Scripts\testcomputers.txt"

foreach ($computer in $computers) {
    $users = Get-LoggedIn $computer

    $SourceFolder = "\\$computer\c$\users\$users\desktop"
    $DestinationFolder = "\\networkshare\backups\$users\backup\desktop"
    $Logfile = "\\networkshare\backups\$users\backup\backuplog.txt"

    & Robocopy $SourceFolder $DestinationFolder /E /R:1 /W:1 /LOG:$Logfile

}  
于 2013-05-10T22:58:06.753 回答