windows - 替换/更新文件共享上的特定文件

标签 windows file powershell scripting powershell-2.0

我正在尝试搜索多个目录并替换 newfile.swf 的所有实例。

$Logfile = "C:\FOLDER\filecopy.log" 
$ServerDir = "\\SERVER\TESTING\DIRECTORY"
$SourceFile = "C:\FOLDER\newfile.swf"
$OldFiles = Get-ChildItem -path $ServerDir -Recurse -Include newfile.swf |
            Sort-Object Name | Format-Table Fullname -Auto

foreach ($O in $OldFiles) {
    if (Test-Path $O) {
        Copy-Item $SourceFile $O -force
    } else {
        Add-Content $logfile "File Copy Failed"
        Add-Content $logfile $error[$error.count-1]
        Add-Content $logfile "==================="
    }
}

下面列出了错误。

File Copy Failed System.Management.Automation.ParseException:
Unexpected token 'C:\FOLDER\newfile.swf' in expression or statement.
at System.Management.Automation.Parser.PipelineRule()
at System.Management.Automation.Parser.StatementRule()
at System.Management.Automation.Parser.StatementListRule(Token start)
at System.Management.Automation.Parser.ScriptBlockRule(String name, Boolean requireBrace, Boolean isFilter, ParameterDeclarationNode parameterDeclaration, List`1 functionComments, List`1 parameterComments)
at System.Management.Automation.Parser.ParseScriptBlock(String input, Boolean interactiveInput)
at System.Management.Automation.AutomationEngine.ParseScriptBlock(String script, Boolean interactiveCommand)
at System.Management.Automation.ScriptCommandProcessor..ctor(String script, ExecutionContext context, Boolean isFilter, Boolean useLocalScope, Boolean interactiveCommand, CommandOrigin origin)
at System.Management.Automation.Runspaces.Command.CreateCommandProcessor(ExecutionContext executionContext, CommandFactory commandFactory, Boolean addToHistory)
at System.Management.Automation.Runspaces.LocalPipeline.CreatePipelineProcessor()
at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()
===================

最佳答案

Format-Table 不会生成文件对象列表,而这正是 Copy-Item 期望的输入。试试这个:

Get-ChildItem -Path $ServerDir -Recurse -Include newfile.swf | sort Name | % {
  if ( Test-Path -LiteralPath $_.FullName ) {
    Copy-Item $SourceFile $_.FullName -Force
  } else {
    Add-Content $logfile "File Copy Failed"
    Add-Content $logfile $error[$error.count-1]
    Add-Content $logfile "==================="
  }
}

关于windows - 替换/更新文件共享上的特定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15670384/

相关文章:

java - 如何在不下载文件的情况下搜索 amazon S3 存储桶中的文件内容

django - Flutter 向 Django API 发送一个以文件为正文的 POST 请求

arrays - 将对象数组转换为哈希表时出错

通过 SetPixel 设置的 C++ 像素在调整控制台大小时或将其移出屏幕时消失

c - 当exe文件没有资源部分时,向exe文件添加图标

java - 我可以在32位Windows操作系统上运行64位java程序吗

ruby - 如何防止 File.readlines 中的引号

csv - 替换 powershell 输出中的 NULL 值

windows - PowerShell 的互操作性

python - 在不出现 Windows 控制台的情况下运行 Python 脚本