【发布时间】:2020-05-10 21:48:24
【问题描述】:
如果直接放入 powershell,该命令将运行,但是如果我尝试在 bat 文件中使用 powershell -Command 标签运行,我会收到以下错误?
运行的命令是:
powershell -Command $tempFilePath = "$env:TEMP\$($filePath ^| Split-Path -Leaf)"
收到的错误是:
在 line:1 char:26
+ $tempFilePath = $env:TEMP\$($filePath ^| Split-Path -Leaf)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token '\$($filePath ^| Split-Path -Leaf)' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
我将不胜感激,如果您需要更多信息,请询问。谢谢你。
评论代码
$filePath = 'filedir/file.conf.js'
$tempFilePath = "$env:TEMP\$($filePath | Split-Path -Leaf)"
$find = 'texttochange'
$replace = 'newtext'
(Get-Content -Path $filePath) -replace $find, $replace | Add-Content -Path $tempFilePath
Remove-Item -Path $filePath
Move-Item -Path $tempFilePath -Destination $filePath
cmets 中概述的新错误:
Add-Content : Cannot find drive. A drive with the name '$env' does not exist.
At line:1 char:227
+ ... h) -replace $find, $replace | Add-Content -Path $tempFilePath; Remove ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: ($env:String) [Add-Content], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.AddContentCommand
Move-Item : Cannot find drive. A drive with the name '$env' does not exist.
At line:1 char:289
+ ... -Path $filePath; Move-Item -Path $tempFilePath -Destination $filePath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: ($env:String) [Move-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.MoveItemCommand
在我的 bat 文件中运行的完整命令会产生上述错误:
powershell -Command $filePath = 'filedir/file.conf.js'; "$tempFilePath = '$env:TEMP\$($filePath ^| Split-Path -Leaf)'"; $find = 'texttochange'; $replace = 'newtext'; (Get-Content -Path $filePath) -replace $find, $replace ^| Add-Content -Path $tempFilePath; Remove-Item -Path $filePath; Move-Item -Path $tempFilePath -Destination $filePath
对我有用的解决方法,我将所有的 powershell 命令放在一个 ps1 文件中,并从 bat 文件中调用它,如下所示。 pshellfile.ps1文件内容:
$filePath = 'filedir/file.conf.js'
$tempFilePath = "$env:TEMP\$($filePath | Split-Path -Leaf)"
$find = 'texttochage'
$replace = 'newtext'
(Get-Content -Path $filePath) -replace $find, $replace | Add-Content -Path $tempFilePath
Remove-Item -Path $filePath
Move-Item -Path $tempFilePath -Destination $filePath
这是我的 bat 文件中的命令:
powershell.exe -ExecutionPolicy ByPass -File pshellfile.ps1
【问题讨论】:
-
powershell -Command "$tempFilePath = '$env:TEMP\$($filePath ^| Split-Path -Leaf)'"
-
这个命令对我来说没有意义!
$filePath在哪里定义?当然,即使它已定义,您所做的只是在 powershell 中设置一个变量,然后关闭它,从而再次取消定义该变量! -
还是一样的结果,一样的错误。谢谢。
-
您是否完全复制了我的建议?我完全没有错误。
-
您不能在批处理文件的一行中输入所有这些
>>字符。我认为它们应该代表新行,因此我已将它们添加到您的问题中的各个行。今后请不要将代码发布到评论区,并在复制和粘贴时以我们或系统可读的格式显示。
标签: powershell batch-file cmd scripting