我有这个脚本,它比较磁盘的两个区域中的文件,并将最新的文件复制到具有较旧修改日期的文件上。
$filestowatch=get-content C:\H\files-to-watch.txt
$adminFiles=dir C:\H\admin\admin -recurse | ? { $fn=$_.FullName; ($filestowatch | % {$fn.contains($_)}) -contains $True}
$userFiles=dir C:\H\user\user -recurse | ? { $fn=$_.FullName; ($filestowatch | % {$fn.contains($_)}) -contains $True}
foreach($userfile in $userFiles)
{
$exactadminfile= $adminfiles | ? {$_.Name -eq $userfile.Name} |Select -First 1
$filetext1=[System.IO.File]::ReadAllText($exactadminfile.FullName)
$filetext2=[System.IO.File]::ReadAllText($userfile.FullName)
$equal = $filetext1 -ceq $filetext2 # case sensitive comparison
if ($equal) {
Write-Host "Checking == : " $userfile.FullName
continue;
}
if($exactadminfile.LastWriteTime -gt $userfile.LastWriteTime)
{
Write-Host "Checking != : " $userfile.FullName " >> user"
Copy-Item -Path $exactadminfile.FullName -Destination $userfile.FullName -Force
}
else
{
Write-Host "Checking != : " $userfile.FullName " >> admin"
Copy-Item -Path $userfile.FullName -Destination $exactadminfile.FullName -Force
}
}
这是files-to-watch.txt的格式
content\less\_light.less
content\less\_mixins.less
content\less\_variables.less
content\font-awesome\variables.less
content\font-awesome\mixins.less
content\font-awesome\path.less
content\font-awesome\core.less
我想修改它,以便它避免这样做,如果文件不存在于两个区域并打印警告消息。有人能告诉我如何使用PowerShell检查文件是否存在?
只是提供the alternative到Test-Path
cmdlet(因为没有人提到它):
[System.IO.File]::Exists($path)
是(差不多)同样的事情
Test-Path $path -PathType Leaf
除了不支持通配符
使用Test-Path:
if (!(Test-Path $exactadminfile) -and !(Test-Path $userfile)) {
Write-Warning "$userFile absent from both locations"
}
将上面的代码放在你的ForEach
循环中可以做你想要的
您想使用Test-Path。
Test-Path <path to file> -PathType Leaf
查看文件是否存在的标准方法是使用Test-Path
cmdlet。
Test-Path -path $filename
您可以使用qazxsw poi cmdlet。做点什么......
Test-Path
if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
Write-Host "$file doesn't exist in both locations."
}
测试路径可能给出奇怪的答案。例如。 “Test-Path c:\ temp \ -PathType leaf”给出false,但“Test-Path c:\ temp * -PathType leaf”给出为true。伤心:(