powershell - windows powershell 在 for each 循环期间显示管道中的当前变量

标签 powershell

我使用 get-wmi commandlet 删除配置文件。当代码遍历循环中的每个删除命令时,我想显示正在删除的配置文件。我试过这个:

$total = 0
$count = 1
foreach ($localpath in $dispaths)
{$total = $total + 1}
Foreach ($localpath in $dispaths) 
{cls
write-host "Deleting Profile: $_.localpath ($count of $total)"
$count = $count + 1
get-wmiobject -class win32_userprofile -computername $cname | where 
{$_.localpath -eq $localpath.localpath} | foreach {$_.Delete()}
}

但是当计数正常时,显示行按字面显示:

删除配置文件:./localpath(135 个中的 1 个)

而不是显示 localpath 变量中的当前字符串。我尝试删除 .来自 $._localpath 但这只是显示如下内容:

删除配置文件:(135 个中的 1 个)

它不显示任何变量字符串应该在的地方。我哪里错了?

最佳答案

循环是 ForEach循环不是 ForEach-Object .所以需要使用ForEach中定义的变量陈述。

您的 Foreach :

Foreach ($localpath in $dispaths) 

所以你需要在变量 $localpath 上设置属性不是 $_
write-host "Deleting Profile: $_.localpath ($count of $total)"

会成为:
write-host "Deleting Profile: $($Localpath.localpath) ($count of $total)"

请注意,这与您的最后一行不同,因为您使用的是 foreach作为 ForEach-Object 的别名.所以你的行可以更准确地写成:
Get-WMIObject -Class Win32_UserProfile -ComputerName $cname | 
    Where-Object {$_.localpath -eq $localpath.localpath} |
    ForEach-Object {$_.Delete()}

因此,由于这是行使用 ForEach-Object以及您使用的管道 $_值通过管道传递。但也使用 $localpath来自 parent ForEach环形。

关于powershell - windows powershell 在 for each 循环期间显示管道中的当前变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44549730/

相关文章:

regex - Powershell 2与Powershell 5行尾 anchor 的powershell regex问题

csv - 填充单元格时出错 "Unable to index into an object of type"

powershell - 查找该月的第三个星期六

multithreading - 我如何才能创建在完成时产生结果的工作?

azure - 由于源文件夹,AZCopy 返回错误

powershell - Powershell正在复制文件夹的内容,但忽略了复制文件夹

powershell - 首次打开 Outlook 时自动执行

powershell - 如何调用嵌套哈希表中的键?

excel - Powershell 脚本包括。 VBA Excel 宏

powershell - SWFUpload 使用 PowerShell 将文件上传到网站