powershell - '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 '')
- 此 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}}
解决方案
正如我所提到的,没有建立 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 的块。
推荐阅读
- c - 为什么编译器无法检测到我的代码中的减号?
- hadoop - 未能放置足够的副本:预期大小为 1,但只能选择 0 个存储类型
- kotlin - 改造查询参数添加apiKey
- c - 在“header.h”文件中声明了一个自引用结构并尝试在“main.c”中定义它,这会导致错误
- .net - .Net应用程序在调试时提示登录浏览器
- c# - 如何在 WPF 页面中实现 IDataErrorInfo(部分类)
- node.js - Express JS - 从 REST 调用加载数据并在应用程序启动时设置为应用程序变量
- php - 将 mailchimp 与 CRM 集成
- quill - QuillJs 处理大文档时速度很慢
- css - CSS - 带有边框半径的动画比例