powershell函数可排除csv

问题描述

我有以下脚本i,我正在尝试关闭所有具有群集的来宾,但csv中列出的来宾除外。在下面的代码中,我将“选择名称”放在“ stop-vmguest”上,以便我可以进行测试而不会破坏任何内容。当前,它正在忽略csv并仅输出集群中每个服务器的名称,因此将关闭所有电源。

$exclusion = get-content "C:\scripts\input\vmExclusion.csv"

$vms = get-cluster "mycluster" | get-vm

Foreach($vm in $vms){

$vm | Where-object {$_.name -notlike $esxclusion.Name }  | select name

}

解决方法

使用-notlike代替-notin ref-Use -notlike to filter out multiple strings in PowerShellhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7

,

-notlike comparison operator用于将字符串与字符串进行比较。它确实提供了执行简单通配符匹配的功能。但是,在将字符串与集合进行比较或将集合与字符串进行比较时,-notin-notcontains分别使工作变得简单。

$SingleString -notin $ArrayOfStrings
$ArrayOfStrings -notcontains $SingleString

如果由于某种原因需要在使用通配符时将字符串与集合进行比较,则可以使用-notmatch。该运算符使用正则表达式匹配,后者依赖于其自己的模式匹配语法语言。下面的示例将$SingleString值与$ArrayOfStrings中的每个值与周围的通配符(例如*value1**value2*等)进行比较。

$Regex = ($ArrayOfStrings |% {[regex]::Escape($_)}) -join '|'
$SingleString -notmatch $Regex

要将内容作为具有自定义属性的对象读取,Import-Csv使生活更轻松。如果文件包含标题行(带分隔符的属性名称的第一行),则可以简单地将命令与匹配的分隔符一起使用。您的会话将具有基于区域性设置的默认分隔符。在我的系统上,这是,。如果文件仅包含数据,则可以添加一个-Header参数作为属性集。

# If the file contains a header row
$exclusion = Import-Csv "C:\scripts\input\vmExclusion.csv"

# If file contains one column of text without a header row
$exclusion = Import-Csv "C:\scripts\input\vmExclusion.csv" -Header Name

# outputs all Name property values from the file
$exclusion.Name

# outputs the first Name property value only
$exclusion[0].Name

# loops over each data row in the csv
$exclusion | Foreach-Object {
    $_ # Current data row as the loop iterates
    $_.Name # Current Name property value
}

SelectSelect-Object的别名。使用不带Select-Object参数的-ExpandProperty将返回具有属性的自定义对象。使用-ExpandProperty仅返回单个属性的值。

# returns a custom object with only the Name property
$vm | Where-object {$_.name -notin $exclusion.Name }  | Select Name

# returns the value of the Name property
$vm | Where-object {$_.name -notin $exclusion.Name }  | Select -ExpandProperty Name

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...