【问题标题】:How to convert a Windows CMD Forloop in PowerShell如何在 PowerShell 中转换 Windows CMD For Loop
【发布时间】:2017-03-31 20:24:15
【问题描述】:

我在命令外壳代码中有以下代码。

SET MYdir=%NewPath%\%CUST%\SuppliesTypes
SET "MYsCount=1"
SET /p MYsCount="Number of MYs in project? (default: %MYSCount%): "
for /L %%a in (1,1,%MYsCount%) do ( 
    SET /p MYNums="Enter %%a MY Number: " 
    call md "%MYdir%\MY_%%MYNums%%"
    )
SET "MYsCount="

但是,我正在将我的代码从 CMD 转换为 PowerShell。我不完全理解转换过来的正确方法。这可能是它应该如何完成的,但它不工作,因为它只是跳过。

SET MYdir=%NewPath%\%CUST%\Product
SET "MYsCount=1"
SET /p MYsCount="Number of MYs in project? (default: %MYSCount%): "
For ($MYsCount = 1; $MYsCount -eq 10; $MYsCount++){
   SET /p MyNums="Enter %%a Product Numbers: " 
   CALL MD "%MYdir%\%CUST%\Product_%%"
} 
SET "$MYsCount="

我查看了以下网站和文章:

  1. PowerShell Basics: Programming With Loops(帮助验证)
  2. How to do a forloop in a Django template?(没有真正帮助)
  3. Windows PowerShell Cookbook, 3rd Edition (第170页)

我在 While 循环中运行此代码。

感谢您的帮助!

【问题讨论】:

  • 您使用$MYsCount -eq 10 作为条件。它应该是$MYsCount -le 10(小于或等于)。仅供参考,powershell 示例中的其余代码(循环除外)不是 powershell 代码...

标签: windows powershell for-loop while-loop counter


【解决方案1】:

您的第二个代码块中有一个有趣的批处理文件和 powershell 组合。当有些东西是一种语言而有些东西是另一种语言时,很难阅读。让我们看看我们是否不能在此处将其全部导入 PowerShell。

$MYdir = "$NewPath\$CUST\Product"
$MYsCount = 1
$UserMYsCount = Read-Host "Number of MYs in project? (default: $MYSCount): "
If([string]::IsNullOrEmpty($UserMYsCount){
    $UserMYsCount = $MYsCount
}
For ($i = 1; $i -le $UserMYsCount; $I++){
   $MyNums = Read-Host "Enter $i Product Numbers: " 
   New-Item -Path "$MYdir\MY_$MyNums" -ItemType Directory
}

【讨论】:

  • 你可以用if ($UserMYsCount -notmatch '^[0-9]+$') {$UserMYsCount = $MYsCount} 来验证而不是IsNullOrEmpty
  • @BenH isnullorempty 方法对于普通读者来说更明显的是它在做什么。
【解决方案2】:

我认为问题出在您声明变量的方式上。 SET 将变量创建为 powershell 本机无法访问的环境变量。以下是我将如何编写您的代码部分:

$MYDir = "$env:NewPath\$env:CUST\SuppliesTypes"
$MYsCount = 1
$MYsCount = read-host -prompt "Number of MYs in project? (default: $MYSCount): "
foreach ($a in 0..$MYsCount){
    $MYNums = Read-Host -Prompt "Enter $a Product Numbers: "
    New-Item -Path "$MYDir\MY_$MYNums" -ItemType Directory
}
$MYsCount = $null

我使用了 foreach 循环而不是普通的 for 循环,因为您每次都递增 1,而且我注意到在步骤不复杂时使用 foreach 会带来小的性能提升。 0..$variable 是使用从 0 到声明变量的每个数字的简写。

如果你确实想使用你提到的 for 循环,那么你可以使用:

For ($MYsCount = 1; $MYsCount -eq 10; $MYsCount++){

正如你所料。这个循环只有在 $MYsCount 变量等于 10 时才会停止,所以如果有人将变量设置为高于 10 的值,它将无限期地运行。

【讨论】:

  • 您的For 循环是他们意图的触发。你会像我在For 循环的答案中所做的那样。干得好,包括$env: 的东西虽然
  • 谢谢,我不确定循环的目标是否只是多次执行代码块,或者我不知道的其余代码中是否存在特定条件所以我想我会保留原来的边界检查,并包含一条关于如何处理边界检查的风险的消息。我喜欢你的答案中包含的错误处理!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 2019-10-09
  • 2019-09-17
  • 1970-01-01
  • 2021-06-20
相关资源
最近更新 更多