微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

取消循环中的获取凭证

如何解决取消循环中的获取凭证

我正在开发 PowerShell 脚本,以通过将 Invoke-Command 与 WinRM 结合使用来自动执行远程服务器上的任务。

该脚本将获取服务器 IP、测试 WinRM 和“Get-Credential”cmdlet 以建立会话并使用 Invoke-Command 在远程服务器上运行另一个脚本。我已经取得了我想要实现的重大进展,但是,我在如何设置代码方面遇到了麻烦,因此当我在 Get-Credential 提示上按“取消”或“X”按钮时,它应该中止脚本并返回到常规 PowerShell 命令行提示符。

以下是我到目前为止所拥有的,我已经删除代码的注释和描述,以减少此处的字数。

function SS
{

    Add-Type -AssemblyName System.Windows.Forms
    $BInput = [System.Windows.Forms.MessageBox]::Show('Do you want to proceed?','Confirmation',[System.Windows.Forms.MessageBoxButtons]::YesNo)
         switch ($BInput)
         { 
            "Yes" {             
                    while ($true)
                        {
                            $server=Read-Host "Enter Server IP Address"  
                            set-item -Path WSMan:\localhost\Client\TrustedHosts -Value "$server" -Force
                                if(Test-WSMan -ComputerName $server -ErrorAction SilentlyContinue)
                                    {
                                        Write-Host "$server is accessible,enter credentials to connect"
                                        
                                            while ($true)
                                                {
                                                    $creden=Get-Credential -Message "Please enter the server credentials that you want to connect"
                                                    $serversession = New-Pssession -ComputerName $server -Credential $creden -ErrorAction SilentlyContinue
                                                    if(-not($serversession))
                                                       {
                                                        write-warning "Credentials are not valild,please try again"                                                            
                                                       }
                                                    else
                                                       {
                                                        write-host "$server is connected,starting the workflow ......"                                                            
                                                        Invoke-Command -Session $serversession -FilePath "C:\Temp\XXX.ps1"                                                            
                                                       }                                                                         
                                                }
                                            Break
                                    }
                                else
                                    {
                                        write-host "Windows Remote Management (WinRM) protocol is not running,please check service and confirm."
                                    }
                        }
                    
                    Get-Pssession | Remove-PSSession
                    
                  }
                                     
            "No"  {  

                    Break
                  }
        }     
      
 }

我知道我必须在此行之后应用更改/逻辑

$creden=Get-Credential -Message "Please enter the server credentials that you want to connect"

但是好像还没有找到。我在网上查看并采取了不同的方法,但到目前为止没有成功。我想就如何解决这个问题提出意见或建议,感谢您的帮助。

谢谢

解决方法

我看到的是你可能想太多了。一个简单的 /api 语句应该可以解决问题,请尝试:

if
,

继续我的评论。 尝试对您的用例进行重构。

注意点:注意已经过全面测试,因为我目前没有要测试的环境。

Function Start-WorkFlow
{
    <#
    .Synopsis
        Execute a workflow
    .DESCRIPTION
        Sets up a WinRM session to a remote host to execute the defined workflow
    .EXAMPLE
        Start-WorkFlow
    .EXAMPLE
        swf
    .INPUTS
        Remote host IPAddress
        Remove host credentials
    .OUTPUTS
        Resutls of teh workflow
    .NOTES
        V 0.0.1 - Prototype script. Clean-Up before production use
    .COMPONENT
        Stand-alone script
    .ROLE
        Administrative actions
    .FUNCTIONALITY
        Implemetned error logic for each code block
        Restrict the user input to only be a proper IPAddress
        Validate TCPIP state 
        Validate WSman state
        Establish a new session
        Process workflow
        Exit session
    #>

    [cmdletbinding(SupportsShouldProcess)]
    [Alias('swf')]
    Param
    (

    )

    
    If ((Read-Host -Prompt 'Do you want to proceed: [Yes/No]') -eq 'No' )
    {Break}
    Else
    {
        Do {$RemoteServerIPAddress = (Read-Host -Prompt 'Enter Server IP Address')}
        Until ($RemoteServerIPAddress -match "^\d{1,3}\.\d{1,3}$")

        Get-ChildItem -Path 'WSMan:\localhost\Client\TrustedHosts'

        Try
        {
            (Test-Connection -ComputerName $RemoteServerIPAddress -Count 1 -ErrorAction Stop).IPV4Address
            # Set-Item -Path 'WSMan:\localhost\Client\TrustedHosts' -Value $RemoteServerIPAddress -Force

            Get-ChildItem -Path 'WSMan:\localhost\Client\TrustedHosts'

            Try 
            {
                Test-WSMan -ComputerName $RemoteServerIPAddress -ErrorAction Stop
                "$RemoteServerIPAddress is accessible,enter credentials to connect"
                Do 
                {
                    $Creds        = $null
                    $CredMesssage = 'Please enter the remote server credentials that you want to connect.' 
                    $CredMesssage = "$CredMesssage If credentials are not valid,you will be prompted to re-enter them."
                    $Creds        = Get-Credential -Message $CredMesssage

                    if(-Not $creds)
                    {
                        Write-Warning -Message 'Credential request cancelled.'
                        Start-Sleep -Seconds 3
                        Exit
                    }
                    
                    $NewPSSessionSplat = @{
                        ComputerName = $RemoteServerIPAddress
                        Credential   = $Creds 
                        Name         = 'RemoteSessionName'
                        ErrorAction  = 'Stop'
                    }
                    New-PSSession $NewPSSessionSplat
                }
                Until (Get-PSSession -Name 'RemoteSessionName')

                "$RemoteServerIPAddress is connected,starting the workflow ......"
                Invoke-Command -Session $RemoteServerSession -FilePath 'C:\Temp\XXX.ps1'
            }
            Catch 
            {
                Write-Warning -Message 'Session connection results:'
                $PSitem.Exception.Message
            }
            Finally
            {
                Get-PSSession | 
                Remove-PSSession -ErrorAction SilentlyContinue        
            }
        }
        Catch
        {
            Write-Warning -Message "
            The remote server $RemoteServerIPAddress is not available
            Exiting the session."
            Start-Sleep -Seconds 3
            Exit
        }
    }
}


Start-WorkFlow

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。