小编kiw*_*san的帖子

Powershell 范围:添加到第二个数组时,循环内的变量数组不会填充

在以下 Powershell 示例中,如何$server在第 5 行内进行填充?我正在尝试将Get-EventLog查询的结果保存到每次$server循环迭代的数组中。

例子:

$serversArray = @("one", "two", "three")
ForEach ($server in $serversArray) {
  echo $server "Variable array iteration populates here correctly"
  $eventArray = @()
  $eventArray += Get-EventLog -computerName $server #But not here, where I need it
  $eventArray  #Yet it populates from calling the second array correctly
}
Run Code Online (Sandbox Code Playgroud)
  1. 我试过将 $server 变量的范围分配给全局或脚本。
  2. 我研究了其他类似的问题,但我找不到任何有这种情况的
  3. 我尝试了管道、引号、反引号等的不同组合。

与往常一样,提前致谢。

编辑好的,ISE 正在缓存一些变量(或一些奇怪的东西),因为上面的示例在我重新启动 ISE 后开始工作。无论如何,问题在于$servers数组输入,它在完整脚本中来自 MySQL 查询。如果我用服务器名称静态分配数组(如上例所示),脚本将起作用。如果我使用 MySQL 查询的输入,则Get-EventLog失败并显示The network path was not …

arrays variables powershell scope

2
推荐指数
1
解决办法
6453
查看次数

bash 命令替换与空格问题

我正在尝试通过从外部文件中读取值并在它们前面加上-x. 将有不同数量的排除项,包括根本没有排除项。我遇到的问题是当 bash 扩展这个变量时,它用单引号将它框起来。这会混淆备份脚本。

#cat sss2.sh:

#!/bin/bash
IFS=$'\n'
xcl=""
for x in $(cat /root/exfile)
 do
 xcl="$xcl -x $x"
 done
backupbin /sourcepath /destination "$xcl"

# cat exfile
"*.tgz"
"*.zip"
Run Code Online (Sandbox Code Playgroud)

当我运行它时,bash$xcl用单引号扩展变量,这会阻止backupbin运行。这是由于空格,因为如果我没有-x,单引号就会消失。

# /bin/bash -x ./sss2
+ IFS=''
+ xcl=
++ cat exfile
+ for x in '$(cat /root/exfile)'
+ xcl=' -x "*.tgz"'
+ for x in '$(cat exfile)'
+ backupbin /sourcepath /destination ' -x "*.tgz" -x "*.zip"'
Run Code Online (Sandbox Code Playgroud)

我曾尝试将其作为扩展填充数组,并尝试过单引号、双引号和反引号的不同组合。我试过使用 eval 没有成功:

backupbin /sourcepath /destination $(eval …
Run Code Online (Sandbox Code Playgroud)

variables bash shell substitution

1
推荐指数
1
解决办法
818
查看次数

标签 统计

variables ×2

arrays ×1

bash ×1

powershell ×1

scope ×1

shell ×1

substitution ×1