【问题标题】:I am trying to force a script to accept user input, but it breaks on the second input我试图强制脚本接受用户输入,但它在第二个输入时中断
【发布时间】:2013-04-02 13:53:53
【问题描述】:

我是 Power shell 的新手,我似乎无法理解这个。

当您取出输入并为每个 $number 和 $Name 放入实际值时,代码会起作用,如底部示例所示。我发现与指定值不同,第 7 行 char 13 不能是 -$Name,而是必须是 $Name。这样做之后,它告诉我 ln 15 char 13 “找不到接受参数“-”的位置字符。其中“-”= $Name。

我需要进行哪些更改才能使其正常工作?我已经厌倦了使用 [parameter(Mandatory=$true,name='What would you like your folder to be named: ')] 但我似乎也无法让它工作。

任何帮助将不胜感激。

$number = read-host "How Many Folders would you like to create: "
$Name = read-host "What would you like your folder to be named: "
$intFolders = $number 
$intPad
$i = 1

New-Variable -$Name strPrefix -Value "$Name" -Option constant

    do {

        if ($i -lt $number)
            {$intPad=0 
                new-item -path c:\mytest -$Name $strPrefix$intPad$i -type directory}
        else
            {new-item -path c:\mytest -$Name $strPrefix$i -type directory}
            $i++}
        until ($i -eq $intFolders+1)

这是我能够开始工作的下面的代码,但我想确保当我离开时,这里的人们仍然可以使用它来满足他们的需求,因为他们不懂编码。

$intFolders = 500
$intPad
$i = 1

New-Variable -Name strPrefix -Value "0001_" -Option constant

    do {

        if ($i -lt 500)
            {$intPad=0 
                new-item -path c:\mytest -name $strPrefix$intPad$i -type directory}
        else
            {new-item -path c:\mytest -name $strPrefix$i -type directory}
            $i++}
        until ($i -eq $intFolders+1)

感谢 Bruce,这里的最终代码可以正常工作:)

[int]$start = read-host "What number would you like your folder to start at"
[int]$number = read-host "How Many Folders would you like to create"
$Name = read-host "What would you like your folder to be named"
$intFolders = $number 
$intPad
$i = $start

New-Variable -Name strPrefix -Value "$Name" -Option constant

    do {

        if ($i -lt 10)
            {$intPad="" 
                new-item -path c:\mytest -Name $strPrefix$intPad$i -type directory}
        else
            {new-item -path c:\mytest -Name $strPrefix$i -type directory}
            $i++}
        until ($i -eq $intFolders+1)

【问题讨论】:

标签: string powershell input directory


【解决方案1】:

改变

New-Variable -$Name strPrefix -Value "$Name" -Option constant
New-Variable -Name strPrefix -Value "$Name" -Option constant
与新项目行中的 -$name 相同。请参阅 Get-Help New-Variable 和 Get-Help New-Item。

【讨论】:

  • 谢谢,这就像一个魅力,但它增加了一个额外的 0。例如。我告诉它创建 1 个文件夹,它创建 10 个,我告诉它创建 1,000 它创建 10,000。
  • 将您的第一行更改为 [int]$number = read-host "您要创建多少个文件夹:" 另外,我认为您可能希望将 IF 条件更改为 "if ($ i -lt 10)" 获取填充字符。
  • 布鲁斯,再次感谢您!它现在像冠军一样工作!我将在上面添加最终代码。
猜你喜欢
  • 2022-01-17
  • 2021-11-12
  • 2021-08-17
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 2013-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多