我有以下PowerShell脚本,可以将特定目录中的所有配置文件复制到我的本地系统。这个脚本在我的许多服务器上都能正常工作,但在4台服务器上失败了:
$source = @()
switch ([System.Net.Dns]::GetHostByName(($env:computerName)).HostName)
# populate an array with a list of paths that contain config files to be copied
{
"SERVER1.DOMAIN" {
$source = @("C:\Program Files\MXC\", "C:\inetpub\wwwroot\")
$target = "\\tsclient\C\Backups\Configs\SERVER1\"
}
"SERVER2.DOMAIN" {
$source = @("C:\Program Files\MXC\")
$target = "\\tsclient\C\Backups\Configs\SERVER2\"
}
"SERVER3.DOMAIN" {
$source = @("C:\inetpub\wwwroot\ccb\001\", "C:\inetpub\wwwroot\eab\020\")
$target = "\\tsclient\C\Backups\Configs\SERVER3\"
}
"SERVER4.DOMAIN" {
$source = @("C:\inetpub\wwwroot\arv\drv\", "C:\inetpub\wwwroot\arv\imp\")
$target = "\\tsclient\C\Backups\Configs\SERVER4\"
}
function CopyConfigs ($configsList) {
try {
foreach ($file in $configsList) {
# get the folder the config file lives in so it can be created in the target dir
$folder = $file.DirectoryName | Split-Path -Leaf
$dest = $target + $folder + "\"
# if the $dest dir does not exist, create it.
if (-not (Test-Path -Path $dest -PathType Container -ErrorAction SilentlyContinue)) {
New-Item -ItemType Directory -Force -Path $dest
}
# copy the config file to the target directory
Copy-Item $file -Destination $dest -Force
}
Write-Host " End copying config files ====="
} catch {
Write-Host "** ERROR: An error occurred while trying to copy the $file to $dest"
return $Error[0].Exception
exit 1
}
}
try {
# get the locations and names of the config files to copy
foreach ($dir in $source) {
$configsList += get-childitem -Recurse -Path $dir *.config -Exclude *.dll.config,*.vshost*,*app.config,*packages.config,*-*,*company.config*
}
CopyConfigs $configsList
} catch {
Write-Host "** ERROR: An error occurred while trying to get a list of config files to copy."
Write-Host $Error[0].Exception
return 1
}
当它失败时,错误是:
方法调用失败,因为[System.IO.FileInfo]不包含名为'op_Addition'的方法。 at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception) at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
我确认了所有系统都安装了PowerShell 4.0,并且所有路径都有效。这个脚本在Windows Server 2008 R2和Windows Server 2012服务器上既成功又失败。
我研究了“op_Addition”错误,但我没有看到任何关于它有时工作有时不工作的信息。通常,此错误与尝试对不是数组的内容进行操作有关,但我认为我已经在我的脚本中考虑到了这一点。而且,有时它确实可以工作。
我真的不确定问题出在哪里。非常感谢您能提供的任何帮助。
$configsList
初始化为空数组($configsList = @()
),否则你的第二次迭代将尝试将一个FileInfo
对象附加到一个数组上,而不是附加到数组中,这会失败,因为这些对象不实现加法运算符。 - Ansgar Wiechers