按CANCEL按钮后退出Powershell脚本

时间:2014-08-21 19:56:44

标签: function powershell exit

我有一个powershell函数会提示用户输入两次密码,但只要按下CANCEL,脚本就会退出。该脚本将提示用户提供尽可能多的匹配密码对,即一些用户可能有5个密码,其他用户可能有10个等,以填充文本文件,并希望停止条件为用户按下{{1 },即当用户不再输入密码时,CANCEL将设置为$continue

$false

这是整个脚本

if ($confirmpassword -eq $null){$continue = $False; exit}

$working_dir = split-path -parent $MyInvocation.MyCommand.Definition $cred_path = "$working_dir\cred" $pwd_path = "$working_dir\pwd" $continue = $True function createPwdFiles(){ $stamp = $(get-date -f HH_mm_ss) $password = Read-Host "Enter password" -AsSecureString $confirmpassword = Read-Host "Confirm password" -AsSecureString $pwd1_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)) $pwd2_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($confirmpassword)) if($pwd1_text -ne $pwd2_text) { [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”) | Out-Null [Windows.Forms.MessageBox]::Show(“Passwords don't match, please try again”, “Passwords don't match”, [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information) | Out-Null } else{ $password | convertfrom-securestring | out-file $pwd_path\$stamp.txt Add-Content $cred_path\pwd_list.txt $pwd_path\$stamp.txt } } if (!(Test-Path -path $cred_path)){ New-Item $cred_path -type directory | out-null } if (!(Test-Path -path $pwd_path)){ New-Item $pwd_path -type directory | out-null } while ($continue -eq $True){ createPwdFiles } write-output "hello world" 永远不会被执行。

如何让CANCEL按钮起作用,以便将write-output "hello world"设置为$continue,并退出该功能,但不退出该脚本。

修改

这是Read-Host弹出窗口

enter image description here

1 个答案:

答案 0 :(得分:2)

这是Do {} While()类的东西。

function createPwdFiles(){
Do{
    $stamp = $(get-date -f HH_mm_ss) 

    $password = Read-Host "Enter password" -AsSecureString

    $confirmpassword = Read-Host "Confirm password" -AsSecureString

    $pwd1_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
    $pwd2_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($confirmpassword))
    if($pwd1_text -ne $pwd2_text) {
        [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”) | Out-Null
        [Windows.Forms.MessageBox]::Show(“Passwords don't match, please try again”, “Passwords don't match”, [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information) | Out-Null

    } 
}While($pwd1_text -ne $pwd2_text)
        $password | convertfrom-securestring | out-file $pwd_path\$stamp.txt
        Add-Content $cred_path\pwd_list.txt $pwd_path\$stamp.txt

}