【问题标题】:powershell replace text withpowershell 将文本替换为
【发布时间】:2014-02-11 14:33:06
【问题描述】:

我对 powershell 还是很陌生,我还在努力学习。

这是我正在处理的问题:

我有一堆 bat 文件,我需要用某些文本替换它们。 唯一的问题是文本中有一个需要用变量替换的东西。

让我举例说明:

Printer1.bat 打印机2.bat

需要写的文字:

 @echo off
 setlocal EnableDelayedExpansion

    ::Identify OS
    for /F "delims=" %%a in ('ver') do set ver=%%a
    set Version=
    for %%a in (95=95 98=98 ME=ME NT=NT 2000=2000 5.1.=XP 5.2.=2003 6.0.=Vista 6.1.=7 6.2.=8)  
do        (

if "!Version!" equ "this" (
  set Version=Windows %%a
) else if "!ver: %%a=!" neq "%ver%" (
          set Version=this
        )
    )

    if "!Version!" equ "Windows XP" (

    rundll32 printui.dll,PrintUIEntry /ga /n\\printserver\$printername
    call P:\Script\wait.cmd 1
    sc stop spooler
    call P:\Script\wait.cmd 4
    sc start spooler
    call P:\Script\wait.cmd 1

    ) else echo Scriptet skal ikke kjøres på Windows7

    Ping –n 5 –w 1 127.0.0.1>null


    "@

如果您注意到变量 $printername 实际上与文件名相同。 所以我想要的是用文本覆盖文件,但用文件名替换变量(不带.bat)

不确定你是否明白我想要做什么。

我知道如何通过拆分路径仅获取不带 .bat 的文件名并替换为“”

我尝试了很多方法,例如 foreach 语句。 .do while..我所做的一切都是正确的

【问题讨论】:

    标签: variables powershell text replace


    【解决方案1】:

    如果您正在寻找的是获取文件名,没有路径或文件扩展名,您可以使用[System.IO.Path]::GetFileNameWithoutExtension 方法。所以像下面这样的东西就可以了:

    $batfiles = ls *.bat
    
    foreach ($file in $batfiles)
    {
        $printername = [System.IO.Path]::GetFileNameWithoutExtension($file.Name) 
        $newFileContents = @"
        [... script content removed for brevity ...]
    
        rundll32 printui.dll,PrintUIEntry /ga /n\\printserver\$printername
    
        [... script content removed for brevity ...]
    "@
        $newFileContents | Set-Content $file.FullName -Encoding UTF8
    }
    

    【讨论】:

    • 谢谢。这成功了。忘记了 system.io.path 我并没有完全放弃我的尝试。再次感谢你
    • System.IO.FileInfo-objects 包含一个BaseName 属性,您可以使用它来代替system.io.path。例如:$printername = $file.BaseName
    • BaseName 属性仅在使用 Get-ChildItemls 是其别名)获取 FileInfo 对象时可用,因为它是由 cmdlet 添加的脚本属性。如果您以其他方式获取文件列表,例如来自任何System.IO 类型,或者如果您只有带有文件名的字符串,则不能使用BaseName,但可以使用[System.IO.Path]。不过这是个好建议,因为只要您使用 Get-ChildItem 获取 FileInfo 对象,BaseName 就会缩短代码。
    猜你喜欢
    • 1970-01-01
    • 2022-10-06
    • 2022-01-23
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    相关资源
    最近更新 更多