使用 Try Catch 命令远程执行 Powershell 命令,然后在失败时使用本机命令回退? [英] Using Try Catch command to execute Powershell command remotely and then fallback with native command when failed?

查看:23
本文介绍了使用 Try Catch 命令远程执行 Powershell 命令,然后在失败时使用本机命令回退?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编译脚本以手动连接到每个服务器,然后远程执行 Powershell 命令,如果找不到 Powershell 模块,则故障回复到本机命令.

I'm trying to compile the script to manually connect to each server and then perform the Powershell command remotely, and if the Powershell module is not found, then failback to the native command.

脚本如下:

Get-DfsrMember | Select-Object -ExpandProperty ComputerName -Unique | Sort-Object | ForEach-Object {
    $session = New-PSSession -ComputerName $_
    Invoke-Command -Session $session -ScriptBlock {
        Try {
            # User Powershell Module DFSR to force Replicate all DFS server content to all its peers
            Try {
                Write-Host "Processing Server ... $($_) using DFSR Powershell Module" -ForegroundColor Yellow
                Import-Module -Name 'DFSR' -ErrorAction Stop
                Update-DfsrConfigurationFromAD
                Sync-DfsReplicationGroup
            }
            Catch {
                Write-Warning -Message "PowerShell Module not found"
                Write-Warning -Message $Error[0].Exception.Message                
            }
            Finally {
                Write-Host "All DFS Servers has been updated succesfully using DFSR Powershell Module" -ForegroundColor Green
                Exit
            }


            # User the builtin DFSR command to force Replicate all DFS server content to all its peers
            Try {
                Write-Host "Processing Server ... $($_) using DFSR native command" -ForegroundColor Yellow
                Dfsrdiag PollAD
                Dfsrdiag SyncNow
            }
            Catch {
                Write-Warning -Message "Unable to execute command"
                Write-Warning -Message $Error[0].Exception.Message                
            }
            Finally {
                Write-Host "All DFS Servers has been updated succesfully using DFSR builtin command" -ForegroundColor Green
                Exit
            }            
        }
        Catch {
            Write-Warning -Message "[PROCESS] Something wrong happened, nothing is updated"
            Write-Warning -Message $Error[0].Exception.Message
        }
        Finally {
            Clear-Variable * -Scope Global
            [System.GC]::Collect()
        }
    }
    Remove-PSSession $session
}

该脚本已在我的笔记本电脑上本地执行为 DOMAINEnterprise.Administrator

The script has been executed locally on my laptop as DOMAINEnterprise.Administrator

但是,错误如下,每台服务器三个错误?

However, the error is like the below, three errors for each of the servers?

Cannot overwrite variable false because it is read-only or constant.
    + CategoryInfo          : WriteError: (false:String) [Clear-Variable], SessionStateUnauthorizedAccessException
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand
    + PSComputerName        : DFS-ServerA
 
Cannot overwrite variable true because it is read-only or constant.
    + CategoryInfo          : WriteError: (true:String) [Clear-Variable], SessionStateUnauthorizedAccessException
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand
    + PSComputerName        : DFS-ServerA
 
The variable cannot be validated because the value 0 is not a valid value for the MaximumErrorCount variable.
    + CategoryInfo          : MetadataError: (:) [Clear-Variable], ValidationMetadataException
    + FullyQualifiedErrorId : ValidateSetFailure,Microsoft.PowerShell.Commands.ClearVariableCommand
    + PSComputerName        : DFS-ServerA


    
Cannot overwrite variable false because it is read-only or constant.
    + CategoryInfo          : WriteError: (false:String) [Clear-Variable], SessionStateUnauthorizedAccessException
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand
    + PSComputerName        : DFS-ServerB
 
Cannot overwrite variable true because it is read-only or constant.
    + CategoryInfo          : WriteError: (true:String) [Clear-Variable], SessionStateUnauthorizedAccessException
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand
    + PSComputerName        : DFS-ServerB
 
The variable cannot be validated because the value 0 is not a valid value for the MaximumErrorCount variable.
    + CategoryInfo          : MetadataError: (:) [Clear-Variable], ValidationMetadataException
    + FullyQualifiedErrorId : ValidateSetFailure,Microsoft.PowerShell.Commands.ClearVariableCommand
    + PSComputerName        : DFS-ServerB

推荐答案

运行时 Invoke-Command 针对远程会话,局部变量 未在远程会话中定义.您要么需要将这些变量作为参数传递给脚本块,要么使用 using: 范围 修饰符.语法是$using:variable.

When running Invoke-Command against remote sessions, local variables from the calling session are not defined in the remote sessions. You either need to pass in those variables as arguments to a script block or use the using: scope modifier. The syntax is $using:variable.

在您的情况下,局部变量是 $_.所以你需要使用 $using:_.

In your case, the local variable is $_. So you would need to use $using:_.

Write-Host "Processing Server ... $($using:_) using DFSR Powershell Module" -ForegroundColor Yellow

请记住,using: 作用域修饰符只读取变量,不允许写入.

Keep in mind that the using: scope modifier only reads variables and does not allow writes.

这篇关于使用 Try Catch 命令远程执行 Powershell 命令,然后在失败时使用本机命令回退?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆