powershell - 将重定向从批处理重定向到 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
我尝试用双引号和单引号引用该行,并尝试转义重定向,但没有运气。我错过了什么?
解决方案
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
推荐阅读
- ruby - Rails 5 - X 的副本已从模块树中删除但仍处于活动状态 - 使用 require: false gem
- android - 如何使用 Android 11 在 Bash 中解决此错误
- javascript - 从 Chrome 扩展程序访问 Dynamics
- wso2-am - 如何通过更多节点配置 wso2 api manager?
- html - 我要按顺序排列公告牌列表编号
- latex - 每个新页面开头的乳胶行号间距问题
- java - 处理程序类在新的 android studio Android Studio 北极狐中解析 | 2020.3.1
- swift - Swift 泛型类型检查协议一致性
- python - 时间序列数据:Resample.mean() 导致缺失值
- python - Matplotlib:此应用程序无法启动,因为它无法找到或加载 Qt 平台插件“windows”