首页 > 解决方案 > Powershell 不填充变量

问题描述

我有一个 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

解决方案


你的管道有点快:

$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的是没有。


推荐阅读