ForEach-Object 脚本块中的命令意外提示输入参数

Command in ForEach-Object script block unexpectedly prompts for arguments

我有以下脚本

$sourceRoot = "C:\Users\skywalker\Desktop\deathStar\server"
$destinationRoot = "C:\Users\skywalker\Desktop\deathStar/server-sandbox"
$dir = get-childitem $sourceRoot  -Exclude .env, web.config   

Write-Output "Copying Folders"
$i=1
$dir| %{
    [int]$percent = $i / $dir.count * 100
    Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete $percent -verbose
    copy -Destination $destinationRoot  -Recurse -Force
    $i++

我试图引用这个 post,但我最终在 powershell 控制台中收到以下提示。

Supply values for the following parameters:

Path[0]:

您正在使用 % (ForEach-Object) 逐对象处理来自管道 ($dir) 的输入。

在对输入进行操作的脚本块({ ... })中,必须使用automatic $_ variable来引用手头的管道输入对象 -您在脚本块内使用的命令执行本身会自动接收该对象作为其输入。

因此,您的 copy (Copy-Item) 命令:

copy -Destination $destinationRoot  -Recurse -Force

缺少源参数,必须更改为类似:

$_ | copy -Destination $destinationRoot  -Recurse -Force

没有源参数(传递给 -Path-LiteralPath) - 这是强制性的 - Copy-Item 提示 它是你经历了什么(默认参数是-Path)。

在上面的固定命令中,通过管道传递 $_ 隐式绑定到 Copy-Item-LiteralPath 参数。