首页 > 解决方案 > 'get-ciminstance win32_userprofile -CimSession | select' WITHIN DO & SWITCH 语句不起作用

问题描述

下面的 Cmdlet 可以正常工作,但是在底部代码块的do&语句中什么都不做?switch在 ISE 中进行调试不会提供任何帮助。删除| Select-Object确实使它起作用,但会产生太多信息。删除-CimSession $hostname确实使它起作用。所以问题似乎与远程 PC 和/或 SELECT 语句有关。

Get-CimInstance Win32_UserProfile -CimSession $hostname | Select-Object -Property LocalPath, LastUseTime

function Show-Menu {
    Write-Host "
    1)Option A
    2)Option B
    3)User Profiles of Remote PC
    "}
DO {Show-Menu
    $UserChoice = Read-Host "Enter # of tool you want to run"
    $hostname=Read-Host "enter hostname"
    switch ($UserChoice) {
        1 {'You choose opt1'}
        2 {'You choose opt2'}
        3 {Get-CimInstance Win32_UserProfile -CimSession $hostname | Select-Object -Property LocalPath, LastUseTime}
   }
} UNTIL ($hostname -eq '')

标签: powershellpowershell-remotingget-wmiobjectselect-object

解决方案


正如我所提到的,没有建立 cimsession 供您指出。因此,让我们使用New-CimSession和提供的计算机名称来创建它$hostname

function Show-Menu 
{
Write-Host "
    1)Option A
    2)Option B
    3)User Profiles of Remote PC
"
}

Do {

    Show-Menu
    $User_Choice = Read-Host -Prompt "Enter # of tool you want to run"
        switch ($User_Choice) {

            1 {'You choose opt1'}
            2 {'You choose opt2'}
            3 {

                $hostname = Read-Host -Prompt "Enter Computer Name"
                    if ([string]::IsNullOrEmpty($hostname) -eq $true) {
                        "No Computer Name was specified";
                        Break
                    }

                    try {
                        
                        $CIMSession = New-CimSession -ComputerName $hostname -ErrorAction stop

                        Get-CimInstance -ClassName Win32_UserProfile -CimSession $CIMSession | Select-Object -Property LocalPath, LastUseTime 

                    }
                    Catch [Microsoft.Management.Infrastructure.CimException] {
                        $Error[0].Message.Split('.')[1].Trim()

                    }
                    Finally {
                        if (Get-CimSession) {
                            Get-CimSession | Remove-CimSession
                            
                        }
                    } 
                }
        }

} Until ($User_Choice -notcontains '')

除了一些小的语法问题外,您应该$hostname在 #3 选择中包含提示。除非,您也想将该变量用于其他选择。当然,您需要一些错误处理,以防连接到机器时发生错误,我们可以使用 atry{}catch{}块来做;添加了一个finally{}用于清理 cimsessions 的块。


推荐阅读