【问题标题】:Powershell doesn't fill variablePowershell 不填充变量
【发布时间】:2020-12-03 19:56:43
【问题描述】:

我有一个 Powershell 脚本,它使用包含文件名的参数调用。我想从文件名中删除扩展名。这是脚本:

param([string]$input_filename)
$inputFileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension($input_filename) | Out-file "myfile.log" -Append
Write-Output "input filename without extension: " $inputFileNameOnly | Out-file "myfile.log" -Append

当我运行文件时: .\myscript.ps1 "E:\Projectdata\Test book.html"

我可以看到调用 [System.IO.Path]::GetFileNameWithoutExtension($input_filename) 有效:我的日志文件中的第一行是“测试书”。

但是“输入文件名不带扩展名:”之后没有放置任何内容。变量 $inputFileNameOnly 没有赋值。

我在这里做错了什么?似乎没有类型不匹配:[System.IO.Path]::GetFileNameWithoutExtension 输出一个字符串。

我在 Windows 10 中使用 Powershell 5。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    你的管道有点快:

    $inputFileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension($input_filename) | Out-file "myfile.log" -Append
    

    这两步合二为一: [System.IO.Path]::GetFileNameWithoutExtension($input_filename) | Out-file... 将获取您的值并将其写入文件。但是,此操作不会提供可以在$inputFileNameOnly 中捕获的任何输出。 $inputFileNameOnly$Null

    而是先将文件名保存在变量中,然后将其用于Out-File

    $inputFileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension($input_filename) 
    Out-file -InputObject $inputFileNameOnly -FilePath "myfile.log" -Append
    

    某些不向管道提供输出的 cmdlet 具有参数 -PassThru 以强制它们将某些内容发送到管道中。不幸的是 Out-File 没有。

    【讨论】:

    • 就是这样。以这种方式使用管道可以在批处理文件中使用(我比 powershell 更熟悉)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2013-07-04
    • 2022-11-27
    • 1970-01-01
    相关资源
    最近更新 更多