【发布时间】:2019-09-20 08:59:43
【问题描述】:
我是使用powershell的新手,我想做以下脚本:
Copy-Item -Path args[0]\index.html -Destination args[0]\print.html
Get-Content args[0]\print.html | %{$_ -replace "root","print"}
我想做的是复制index.html 并命名为print.html。
然后我想获取那个print.html 的内容(在与上面相同的路径)并将所有“root”替换为“print”。
我遇到的问题是 PowerShell 无法识别带有 Get-Content 的 args[0],因此我需要一种动态传递该路径而不是硬编码的方法,因为路径可能会因用户而异。
这是错误:
Get-Content : 指定路径 args[0]\print.html 处的对象不 存在,或已被 -Include 或 -Exclude 参数过滤。 在 C:\Users\Gabriel\Documents\officine\prepare-print-page.ps1:2 char:1 + 获取内容参数 [0]\print.html | %{$_ -replace "root","print"} + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (System.String[]:String[]) [Get-Content], 异常 + FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand更新:
好的,抱歉我不是很清楚,我看过其他 stackoverflow 帖子,我发现了有关 param,所以现在我的脚本如下所示:
param ([string]$path)
Copy-Item $path\index.html -Destination $path\print.html
Get-Content $path\print.html | %{$_ -replace "root","print"}
当我构建我的应用程序时,在我的 js 文件中,我传递这样的参数:
`prepare-print-page.ps1 ${outputPath}`
outputPath 变量保存 index.html 所在的路径,如下所示:C:\Users\Gabriel\Documents\myapp\build
但它不会复制和创建 print.html,我基本上是在尝试和这个 bash 文件做同样的事情:
#!/bin/bash
# Duplicate the index page (which contains all the React scripts) and
# rename the id of the main element from "root" to "print". index.jsx
# will then render the correct component.
echo "Generating print.html in directory $1 ..."
cp $1/index.html $1/print.html
sed -i.bak 's/id="root"/id="print"/g' $1/print.html
rm $1/print.html.bak
【问题讨论】:
-
您从哪里复制了这段代码? [咧嘴]
-
您如何将信息输入
$Args? -
你有文字路径
C:\some\folder\args[0]\print.html吗?还是您想使用参数中的值调用Get-Content? -
我更新了我的帖子,抱歉我不够清楚
-
什么js文件?什么样的应用程序?如果您尝试从非 PowerShell 环境调用 PowerShell 脚本,请提供有关该环境的更多详细信息。 PowerShell 脚本是否正在运行?传递给脚本参数的实际值是多少?尝试在 PowerShell 脚本中添加一行
"-${path}-" > C:\Windows\Temp\output.txt(就在参数定义之后)。是否正在创建该文件?它的内容是什么?
标签: windows powershell