简体   繁体   English

在 foreach 循环中执行 powershell 命令

[英]Execute powershell command in foreach loop

I am trying to execute aws s3 cp command in Powershell.我正在尝试在 Powershell 中执行 aws s3 cp 命令。 I have a list of files which I defined in an array-like below.我有一个文件列表,我在下面的类似数组中定义了这些文件。

$filearray = ("file1.txt", "file2.txt", "file3.txt", "file4.txt", "file5.txt")

Now when I am trying to copy these files from s3 using aws s3 cp command nothing works.现在,当我尝试使用 aws s3 cp 命令从 s3 复制这些文件时,没有任何效果。

$filearray | foreach { "aws s3 cp s3://<bucket_name/path_to_file/$_ . --sse aws:kms --sse-kms-key-id 12345-abcxzd" }

I tried below as well.我也在下面尝试过。 But it didn't work.但它没有用。 Can someone point out the mistake I am doing?有人可以指出我正在做的错误吗?

foreach ($element in $filearray) { "aws s3 cp s3://<bucket_name/path_to_file/$element . --sse aws:kms --sse-kms-key-id 12345-abcxzd" }

Now I have added variables to my aws command also which will be like below when the loop executes.现在我已经将变量添加到我的 aws 命令中,当循环执行时,它也将如下所示。

$kms_key_option="--sse aws:kms --sse-kms-key-id 12345-abcxzd" $s3_location="s3://<bucket_name/path_to_file/" $kms_key_option="--sse aws:kms --sse-kms-key-id 12345-abcxzd" $s3_location="s3://<bucket_name/path_to_file/"

foreach ($element in $filearray) { & aws s3 cp $s3_location/$element $current_location $kms_key_option }

But there is a catch in this.但这有一个问题。 Only the first 2 variables in command block work as variables rest 2 do not work as variables.只有命令块中的前 2 个变量作为变量工作,其余 2 不作为变量工作。 ie $current_location $kms_key_option So the problem statement is changing here a little bit.$current_location $kms_key_option所以问题陈述在这里有一点变化。

Note: I have aws cli installed on my windows machine it works with normal command but it doesn't work in foreach loop.注意:我在我的 Windows 机器上安装了 aws cli,它可以使用普通命令,但在 foreach 循环中不起作用。

您正在寻找 & 运算符。

foreach ($element in $filearray) { & "aws s3 cp s3://<bucket_name/path_to_file/$($element) . --sse aws:kms --sse-kms-key-id 12345-abcxzd" }

I'd say try it without the Quotes in the foreach loops?我会说在 foreach 循环中没有引号的情况下尝试一下?

foreach ($element in $filearray) {
    aws s3 cp s3://<bucket_name/path_to_file/$element . --sse aws:kms --sse-kms-key-id 12345-abcxzd
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM