Powershell Remote Copy失败,在本地工作

问题描述 投票:1回答:2

我们在不同位置的服务器A上有日志文件(没有UNC路径访问权限),我们希望将文件复制到服务器B.只要文件关闭,这就成功地与Copy-Item -FromSession(在服务器B上运行)一起使用。所以我们可以成功复制前一天的日志而不是今天的日志。

$cred = Get-OurUserCredentials
$sess = New-PSSession -ComputerName $ServerA -Credential $cred -Authentication Negotiate
$LogFile = "D:\log\tomcat\access.20180227.log" 
Copy-Item -FromSession $sess $LogFile "D:\logs\tomcat\" -Force

但是,如果我们在服务器A本地运行Copy-Item,我们可以在本地复制今天的活动日志。它只是服务器B上的Copy-Item -FromSession,它失败了:

Copy-Item:进程无法访问文件'D:\ log \ tomcat \ access.20180227.log',因为它正由另一个进程使用。在行:11 char:2

作为一种解决方法,我们可以在服务器A上创建一个本地任务来创建本地副本,但为什么这是必要的呢?

为什么Copy-Item在远程运行时表现不同,我们可以“修复”它的行为,因此它会像本地一样远程复制日志。

powershell powershell-remoting
2个回答
1
投票

OP中提出的答案版本,但不需要计划任务。

    $cred = Get-OurUserCredentials
    $sess = New-PSSession -ComputerName $ServerA -Credential $cred -Authentication Negotiate

    #ScriptBlock to copy file locally
    $SB =
    {
        #Create variables on the remote machine avoid havin gto pass to scriptblock
        $LogFile = "D:\log\tomcat\access.20180227.log" 
        $TempDes = "temporarylocationhere"

        Copy-Item -Path $LogFile -Destination $Des
    }

    #optional scriptblock to clean up
    $SB2 =
    {
        Remove-Item -Path $TempDes -force
    }

    #Run the copy file scriptblock
    Invoke-Command -Session $sess -ScriptBlock $SB

    #Copy file
    Copy-Item -FromSession $sess $TempDes "D:\logs\tomcat\" -Force                           #"

    #Run clean up scriptblock
    Invoke-Command -Session $sess -ScriptBlock $SB2

0
投票

您是否考虑过使用PSDrive映射远程位置,然后将文件复制到该驱动器或从该驱动器复制?

New-PSDrive cmdlet创建映射到数据存储中的位置或与之关联的临时和永久驱动器,例如网络驱动器,本地计算机上的目录或注册表项,以及持久性Windows映射的网络驱动器。与远程计算机上的文件系统位置相关联。

使用代码的示例:

# Change the ServerNameToCopyTo below    
New-PSDrive -Name "Remote" -PSProvider "FileSystem" -Root "\\ServerNameToCopyTo\log\tomcat\" 
$LogFile = "D:\log\tomcat\access.20180227.log"
Copy-Item $LogFile "Remote:\" -Force
© www.soinside.com 2019 - 2024. All rights reserved.