首页 > 解决方案 > ForEach-Object 脚本块中的命令意外提示输入参数

问题描述

我有以下脚本

$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++

我试图参考这篇文章,但最终在 powershell 控制台中得到了以下提示。

为以下参数提供值:

路径[0]:

标签: powershellsyntaxpipeline

解决方案


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

{ ... }$_输入进行操作脚本_

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

copy -Destination $destinationRoot  -Recurse -Force

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

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

如果没有源参数(传递给-Pathor -LiteralPath) - 这是强制性的 -Copy-Item 会提示输入它,这是您所经历的(默认参数是-Path)。

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


推荐阅读