文件夹选取器未加载到ISE外部

时间:2017-05-12 15:05:33

标签: powershell

我有一个以文件夹选择器对话框开头的脚本,但是我知道POSH不能像ISE那样在ISE之外执行脚本(STA与MTA),所以我有一个单独的脚本来点源它

我在第一个脚本中有错误处理,以防用户按下取消:

if ($Show -eq "OK") {
    return $objForm.SelectedPath
} else {
    Write-Error "Operation cancelled by user."
    exit
}

现在我需要第二个脚本(调用第一个脚本的脚本)来检测相同的取消。

这是我到目前为止所得到的:

"Choose a folder containing the items to be moved..."
""
try {
    powershell -STA -File "C:\Test\Script.ps1"
    ""
    "Operation completed. An event log has been created:"
    (Resolve-Path .\).Path +"\log.txt"
    ""
    "Press any key to continue..."
    ""
    $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
} catch {
    if ($LastExitCode -ne 0) { exit $LastExitCode }
    Write-Host "User cancelled the operation."
    ""
    "Press any key to continue..."
    ""
    $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}

这给了我一个令人讨厌的多行写错误例外红色文字。

At C:\Test\Script.ps1:27 char:30
+ $folder = Select-FolderDialog <<<<  #contains user's selected folder
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Select-FolderDialog

我不确定为什么它会生成引用其他脚本的错误消息,因为另一个脚本运行正常(当然是来自ISE)。

期望输出:

如果用户取消文件夹选择器,我只想要显示一条漂亮的干净错误消息:

  

用户取消了操作   按任意键继续。

修改

这是我的文件夹选择器脚本。它在ISE中工作正常,但是当您右键单击并选择Run with Powershell时,它只会启动一个空白提示窗口。为了防止最终用户意外编辑脚本,我希望它从ISE外部运行。顺便说一句,我正在使用POSH 2.

 # Function for folder picker dialog
Function Select-FolderDialog
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null     

$objForm = New-Object System.Windows.Forms.FolderBrowserDialog
# Default location is script's location
$objForm.SelectedPath = (Resolve-Path .\).Path
$objForm.Description = "Select Folder"
$Show = $objForm.ShowDialog()
If ($Show -eq "OK")
{Return $objForm.SelectedPath}
    Else
    {
    Write-Error "Operation cancelled by user."
    Exit
    }
}
$folder = Select-FolderDialog #contains user's selected folder

1 个答案:

答案 0 :(得分:0)

将您的功能保留在第二个脚本中,点源文件以加载该功能,然后将$folder = Select-FolderDialog调用放入主脚本,la:

"Choose a folder containing the items to be moved..."
""
try {
    . "C:\Test\Script.ps1" # this dot sources the function from the second file (no need to call a separate Powershell process to do this, as data from that process won't be returned to the primary process calling it)

    $folder = Select-FolderDialog # this runs the function in your original script, storing the result in the $folder variable

    ""
    "Operation completed. An event log has been created:"
    (Resolve-Path .\).Path +"\log.txt"
    ""
    "Press any key to continue..."
    ""
    $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
} catch {
    if ($LastExitCode -ne 0) { exit $LastExitCode }
    Write-Host "User cancelled the operation."
    ""
    "Press any key to continue..."
    ""
    $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}