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 '')
- 此cmdlet存在相同问题:
{Get-WMIObject Win32_UserProfile -ComputerName $hostname | Select-Object -Property LocalPath,LastUseTime}
- 工作,但间隔有趣:
{Get-WMIObject Win32_UserProfile -ComputerName $hostname | Format-List LocalPath, LastUseTime}
- 工作,但间隔有趣&具有奇怪的runspaceID项:
{Invoke-Command -ComputerName $hostname -HideComputerName -ScriptBlock {Get-WMIObject Win32_UserProfile | Select-Object LocalPath, LastUseTime}}
您的代码出现语法错误,缺少一个用于关闭开关的大括号。混合文本输出和对象输出会导致powershell出现问题。例如,这很好用。
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"
$hostname = 'comp001'
switch (3) {
1 {'You choose opt1'}
2 {'You choose opt2'}
3 {Get-CimInstance Win32_UserProfile -CimSession $hostname |
Select-Object -Property LocalPath, LastUseTime}
}
} UNTIL (1)
正如我所提到的,没有为您建立的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 '')
除了一些小的语法问题外,您应该在#3选择中有$hostname
提示。除非,您也希望将该变量用于其他选择。当然,如果连接到机器时发生错误,您需要一些错误处理,我们可以使用try{}
和catch{}
块来处理;添加了用于cimsessions清理的finally{}
块。