首页 > 解决方案 > 将重定向从批处理重定向到 powershell

问题描述

我正在使用批处理文件来编写 Powershell 脚本。我知道当整个事情都可以用 Powershell 编写时,这不是首选方法,但我在这里。

在 Powershell 脚本中有一行应该将匹配的文本重定向到输出文件。但是,由于我正在从批处理文件“编写”Powershell 脚本,因此我试图将包含重定向的行重定向到脚本中。

以下是批处理文件中的示例代码:

Echo CLS >> Path\to\PowerShell\Script\example.ps1
Echo Echo "Please wait while we compare files" >> Path\to\PowerShell\Script\example.ps1
Echo Echo " " >> Path\to\PowerShell\Script\example.ps1
Echo $file1 = (Get-Content -Path Path\to\Footprint\File\footprint) >> Path\to\PowerShell\Script\example.ps1
Echo :sig ForEach ($Foot In $file1) >> Path\to\PowerShell\Script\example.ps1
Echo     { >> Path\to\PowerShell\Script\example.ps1
Echo         $Logfile = (Get-Content -Path Path\to\Log\File\Log.log) >> Path\to\PowerShell\Script\example.ps1
Echo         :log ForEach ($Line In $Logfile) >> Path\to\PowerShell\Script\example.ps1
Echo         { >> Path\to\PowerShell\Script\example.ps1
Echo          If (($Line -match $Foot)) >> Path\to\PowerShell\Script\example.ps1
Echo                 { >> Path\to\PowerShell\Script\example.ps1
Echo                     ECHO $Line >> Path\to\Output\File\Match.txt >> Path\to\PowerShell\Script\example.ps1
Echo                     ECHO "We have found a match!" >> Path\to\PowerShell\Script\example.ps1
Echo                     break log >> Path\to\PowerShell\Script\example.ps1
Echo                 } >> Path\to\PowerShell\Script\example.ps1
Echo         } >> Path\to\PowerShell\Script\example.ps1
Echo     } >> Path\to\PowerShell\Script\example.ps1
Echo Pause >> Path\to\PowerShell\Script\example.ps1

它打破了这一行:

Echo                     ECHO $Line >> Path\to\Output\File\Match.txt >> Path\to\PowerShell\Script\example.ps1

这是生成的 Powershell 脚本:

CLS 
Echo "Please wait while we compare files" 
Echo " " 
$file1 = (Get-Content -Path Path\to\Footprint\File\footprint) 
:sig ForEach ($Foot In $file1) 
    { 
        $Logfile = (Get-Content -Path Path\to\Log\File\Log.log) 
        :log ForEach ($Line In $Logfile) 
        { 
         If (($Line -match $Foot)) 
                { 
                    ECHO $Line 
                    ECHO "We have found a match" 
                    break log 
                } 
        } 
    } 
Pause 

我尝试用双引号和单引号引用该行,并尝试转义重定向,但没有运气。我错过了什么?

标签: powershellbatch-file

解决方案


cmd.exe/ 批处理文件要求shell 元字符,例如>- 如果"..."(双引号字符串)之外使用 -单独^转义

注意:对于echo, 使用双引号并不是一个真正的选择,因为双引号将保留在输出中

因此,正如Compo已经在评论中指出的那样,您必须使用:

Echo                     ECHO $Line ^>^> Path\to\Output\File\Match.txt >> Path\to\PowerShell\Script\example.ps1

还值得指出的是,echo' 的输出将包括重定向输出之前或之中的任何空格。>>>

例如,echo hi > test.txt将字符串hi (注意尾随空格)写入文件test.txt


推荐阅读