【问题标题】:How to get a specific path with PowerShell如何使用 PowerShell 获取特定路径
【发布时间】: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


【解决方案1】:

我假设你有一个名为 $args 的带有参数的数组。 您应该通过使用 $ 符号来访问数组 $args 的值

     $args[0]\index.html

将检索数组中第一个条目的值并将其添加到您的路径中

来自 microsoft technet 的关于 _Arrays 的更多文档: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_arrays?view=powershell-6

我认为如果你想使用参数,你必须创建一个函数: 这应该可以实现您想要实现的目标:

    function prepare-print-page {
    Param(
        [Parameter(Mandatory=$true
        )][String]$path)
        $content= Get-Content "$path\index.html" | %{$_ -replace "root","print"} 
        $content > $path\print.html
    }

要调用该函数,请将其粘贴到您的 powershell 中并调用它:

prepare-print-page "C:\Temp"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多