powershell - 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。
解决方案
你的管道有点快:
$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
的是没有。
推荐阅读
- android - 上传图片失败,错误 EACCES(权限被拒绝)
- amazon-web-services - AWS:CloudFormation 如何知道模板已部署?
- python - 如何从 Spacy 加载任意语言
- r - 安装包“INLA”时出错
- c++ - 如何更改和删除堆栈中的变量?
- python - 网页抓取错误:请求和无连接
- c# - System.ArgumentException:句柄必须有效。参数名称:CrossSecureStorage 上的实例
- ruby-on-rails - 在 rails 目录中启动 sidekiq 和使用 fork 在现有 rails 进程(如控制台)中启动 sidekiq 有什么区别
- jquery - 如何在不使用 jquery 删除哈希的情况下更改动态创建的 href 值的字符
- python - 烧瓶python在循环时制作后台线程