我们可以在PowerShell中编写星级程序吗?

时间:2019-03-04 16:29:37

标签: powershell powershell-core

我是Power Shell的新手,正在练习一些程序。如果我可以在Powershell中编写程序,请告诉我。我知道它是一个脚本工具,已在系统管理中使用。为了掌握基本知识,我正在尝试使用此脚本。

这是我编写的代码:

cls
for ($i = 1; $i -le 4 ;$i++)
{
for ($j = 1; $j -le $i; $j++){
write-host "*"
}

write-host "`n"
}
  

所需的输出:

     

*

     

*   *

     

*   *   *

     

*   *   *   *

我得到的输出为:

Actual Output

有人可以帮我吗?非常感谢您的帮助。

  

已解决

cls
for ($i = 1; $i -le 4 ;$i++)
{
for ($j = 1; $j -le 4 ; $j++){
write-host "*" -NoNewline
}

write-host "`n"
}

2 个答案:

答案 0 :(得分:2)

您发布的解决方案不适用于我。 [ frown ]给出4行,每行4个星号,每个星号之间用一个空白行隔开。

此版本使用foreach循环,遍历所需的行数,绘制使用字符串乘法构建的行,插入一条空行,然后对行数中的每个其余行重复。

$LineCount = 8
$LineChar = '*'

foreach ($LC_Item in 1..$LineCount)
    {
    Write-Host ($LineChar * $LC_Item)
    Write-Host
    }

输出...

*

**

***

****

*****

******

*******

********

答案 1 :(得分:2)

该任务有很多代码。 PowerShell提供了多种方法来完成相同或相似的任务。至于您的努力,可以轻松地将其简化为一个衬板。不需要写主机。

# Use the range operator, pipe to a ForEach with a string repeat '*' X times per the range number passed in.

1..8 | ForEach{('*')*$PSItem}

# Results
*
**
***
****
*****
******
*******
********

更新为包含空白行。

李,嘿,简洁,我错过了必要的空白行。用...轻松固定...

# Use the range operator, pipe to a ForEach with a string repeat '*' X times per the range number passed in and a blank line for each pass
1..8 | ForEach{('*')*$PSItem + "`n"}

# Results

*

**

***

****

*****

******

*******

********