我正在使用批处理文件编写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
我试图用双引号和单引号引起来,并尝试转义重定向,但是没有运气。我想念什么?
最佳答案
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
关于powershell - 从批处理重定向到Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55347050/