powershell - 使用文件名作为变量重命名我的项目不使用 Powershell
问题描述
我正在使用 Powershell。我的目标是将一个项目复制到不同的目录(我已经知道该怎么做),获取用户 ID(我已经知道怎么做),并使用变量中存在的文件名重命名文件(我我不确定我做错了什么)。
当我运行我的代码时,它给了我一个错误:重命名项目:无法将参数绑定到参数“NewName”,因为它为空。我不知道我做错了什么。
我的代码如下:
$name = [Environment]::UserName
$mainFile = "\\example\example.xlsx"
$copiedFile = "\\example\example\copiedFolder\example.xlsx"
#Once I have copied the file to the new directory, I do the following code which does not work:
$copiedFile = Rename-Item -Path $copiedFile -NewName $name.xlsx
解决方案
你把这复杂化了。这是一个简单的复制命令。
Get-ChildItem -Path 'D:\temp\reconcile.*'
<#
# Results
Directory: D:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 03-Feb-20 12:54 644 reconcile.txt
#>
$mainFile = 'D:\temp\reconcile.txt'
$FileTarget = 'D:\temp\'
Copy-Item -Path $mainFile -Destination "$FileTarget\reconcile.xlsx" -Force
Get-ChildItem -Path 'D:\temp\reconcile.*'
<#
# Results
Directory: D:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 03-Feb-20 12:54 644 reconcile.txt
-a---- 03-Feb-20 12:54 644 reconcile.xlsx
#>
我不知道为什么这...
[Environment]::UserName
...在您的代码中,并且在其中两次,因为您没有显示它是如何使用的。但是,您可以为此使用内置变量。
$env:USERNAME
推荐阅读
- java - JBoss River 序列化库:java.lang.NegativeArraySizeException 仅在某些对象上
- maven - 通过 Git Bash 推送代码时出现 Maven 插件错误
- node.js - 使用 slack API 访问用户的地理位置
- amazon-web-services - 使用 Symfony 5 和 AWS Elasticsearch 配置 FOSElasticaBundle
- grafana - Grafana/Prometheus 无数据
- c - 为什么这个程序的打印部分获取 11 辆汽车的信息并打印红色汽车的型号名称不起作用?
- ros - FIWARE FIROS 从非 ROS 世界发布 cmd_vel
- javascript - Javascript类,方法不是函数
- java - SwingUtilities3.setDelegateRepaintManager 的 Java 9 替代品
- apache-kafka - Flume - java.lang.OutOfMemoryError:与 Kafka 集成时的 Java 堆空间