使用powershell检查远程系统中是否存在文件/文件夹
我已经搜索了这个并找到了很多答案。但是,他们似乎都没有工作。使用powershell检查远程系统中是否存在文件/文件夹
我正在使用一个脚本,将用于从本地机器复制一些文件到远程服务器。在复制文件之前,我需要检查文件/文件夹是否已经存在。如果该文件夹不存在,则创建一个新文件夹,然后复制这些文件。如果该文件已经存在于指定位置,则只需覆盖该文件。
我得到了如何做到这一点的逻辑。但是,出于某种原因,Test-Path似乎不起作用。
$server = #list of servers
$username = #username
$password = #password
$files = #list of files path to be copied
foreach($server in $servers) {
$pw = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ($username, $pw)
$s = New-PSSession -computerName $server -credential $cred
foreach($item in $files){
$regex = $item | Select-String -Pattern '(^.*)\\(.*)$'
$destinationPath = $regex.matches.groups[1]
$filename = $regex.matches.groups[2]
#check if the file exists on local system
if(Test-Path $item){
#check if the path/file already exists on remote machine
#First convert the path to UNC format before checking it
$regex = $item | Select-String -Pattern '(^.*)\\(.*)$'
$filename = $regex.matches.groups[2]
$fullPath = $regex.matches.groups[1]
$fullPath = $fullPath -replace '(.):', '$1$'
$unc = '\\' + $server + '\' + $fullPath
Write-Host $unc
Test-Path $unC#This always returns false even if file/path exists
if(#path exists){
Write-Host "Copying $filename to server $server"
Copy-Item -ToSession $s -Path $item -Destination $destinationPath
}
else{
#create the directory and then copy the files
}
}
else{
Write-Host "$filename does not exists at the local machine. Skipping this file"
}
}
Remove-PSSession -Session $s
}
检查远程计算机上文件/路径是否存在的条件总是失败。不知道为什么。
我在powershell上手动尝试了以下命令,该命令在远程计算机上返回true,在本地计算机上返回false。
在本地机器上:
Test-Path '\\10.207.xxx.XXX\C$\TEST'
False
在远程机器:
Test-Path '\\10.207.xxx.xxx\C$\TEST'
True
Test-Path '\\localhost\C$\TEST'
True
所以,很显然,此命令就会失败,即使我尝试手动或通过脚本。但是当我尝试从远程系统或服务器上执行命令时,命令就会通过。
但我需要检查该文件是否存在于本地系统的远程机器上。
我错过了什么吗?有人能帮我理解这里发生了什么吗?
谢谢!
首先,你没有使用任何PSSession。他们看起来多余。
如果您的本地路径与目的地相同,并且您使用的是WMF/Powershell 4或更新版本;我建议您停止使用正则表达式和UNC路径,并执行以下操作,这会简化并删除大部分代码:
$existsOnRemote = Invoke-Command -Session $s {param($fullpath) Test-Path $fullPath } -argumentList $item.Fullname;
if(-not $existsOnRemote){
Copy-Item -Path $item.FullName -ToSession $s -Destination $item.Fullname;
}
谢谢老兄。有效! – jayaganthan
完成:) @CmdrTchort – jayaganthan
为什么不使用Robocopy处理副本? – Snak3d0c
我认为我们看到了这个问题,你能告诉我们'$ Files'有几行吗? – FoxDeploy