【问题标题】:Get-ChildItem -Path Getting Current DirectoryGet-ChildItem -Path 获取当前目录
【发布时间】:2026-01-03 21:30:01
【问题描述】:

我有一个简单的任务,即从一个路径获取文件并使用 PowerShell 脚本将其复制到另一个路径。现在,我明白了,使用Get-ChildItem,如果没有指定-Path,它将获取当前目录。我正在使用这段代码,设置文件所在的目录,但它仍然获取当前目录:

$file = Get-ChildItem -Path "\\w102xnk172\c$\inetpub\wwwroot\PC_REPORTS\exemplo\DCT\Files\STC" | Sort-Object LastWriteTime | Select-Object -Last 1
Copy-Item $file -Destination "\\Brhnx3kfs01.vcp.amer.dell.com\brh_shipping$\DEMAND_MONITOR\"
cmd /c pause | out-null

暂停时返回此错误:

这是遵循Get-ChildItemCopy-Item 文档中的规则的脚本。我错过了什么吗?为什么它仍然获取当前目录?我尝试了多种语法差异,从逗号中获取路径,不设置 -Path 或 -Destination,直接在 Copy-Item 中设置文件而不使用 $file 变量...

【问题讨论】:

  • Copy-Item $file ... -> $file |Copy-Item ...Copy-Item $file.FullName

标签: powershell


【解决方案1】:

Copy-Item 需要 [string] 作为第一个位置参数 - 因此它会尝试将 $file 转换为字符串,从而生成文件的 name

要么引用文件的FullName 属性值(完整路径):

Copy-Item $file.FullName -Destination "\\Brhnx3kfs01.vcp.amer.dell.com\brh_shipping$\DEMAND_MONITOR\"

或者将$file 对象通过管道传递给Copy-Item,然后让管道绑定为您施展魔法:

$file |Copy-Item -Destination "\\Brhnx3kfs01.vcp.amer.dell.com\brh_shipping$\DEMAND_MONITOR\"

如果您想亲自了解 powershell 是如何在内部为自己处理的,请使用Trace-Command

Trace-Command -Name ParameterBinding -Expression {Copy-Item $file -Destination "\\Brhnx3kfs01.vcp.amer.dell.com\brh_shipping$\DEMAND_MONITOR\"} -PSHost

【讨论】: