首页 > 解决方案 > 使用文件名作为变量重命名我的项目不使用 Powershell

问题描述

我正在使用 Powershell。我的目标是将一个项目复制到不同的目录(我已经知道该怎么做),获取用户 ID(我已经知道怎么做),并使用变量中存在的文件名重命名文件(我我不确定我做错了什么)。

当我运行我的代码时,它给了我一个错误:重命名项目:无法将参数绑定到参数“NewName”,因为它为空。我不知道我做错了什么。

我从https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/rename-item?view=powershell-7得到这个

我的代码如下:

$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

标签: powershellfile-rename

解决方案


你把这复杂化了。这是一个简单的复制命令。

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

About_EnvironmentVariables


推荐阅读