【问题标题】:supplying filter value as variable in powershell yields different results在 powershell 中提供过滤器值作为变量会产生不同的结果
【发布时间】:2015-06-24 18:07:29
【问题描述】:

我正在尝试对我的 Exchange 2010 服务器上的一组邮箱执行批量操作。为了限制我需要操作的数字框,我想过滤结果。我知道我需要处理的那些是在 2015 年 1 月 1 日之后创建的,所以我将其作为过滤器值提供(有效):

$boxes = Get-Mailbox -filter { whenCreated -gt '2015-01-01' }

我希望稍后能够重用我的脚本,所以我尝试将其设置为采用参数,但它返回所有框(不起作用)...

$filterdate = '2015-01-01'; $boxes = Get-Mailbox -filter { whenCreated -gt $filterdate }

我的猜测是,当我提供字符串文字与提供字符串变量时,-Filter 会进行某种隐式类型转换

如何为 -Filter 提供变量?

编辑:

这也返回一个未过滤的列表:

$filterdate = [System.DateTime]'2015-01-01'; get-mailbox -filter { whencreated -gt $filterdate }

导致错误:

$filterdate = '2015-01-01'; get-mailbox -filter { whencreated -gt "$filterdate" }

【问题讨论】:

  • 尝试将值设为实际日期:$filterdate = Get-Date '2015-01-01'
  • @AnsgarWiechers get-date 产生相同的结果
  • 尝试扩展字符串? { whenCreated -gt "$filterdate" }
  • 无法将参数“过滤器”绑定到目标。异常设置“Filter”:“值“$filterdate”无法转换为 System.Nullable`1[System.DateTime] 类型。”
  • 不是因为脚本块的原因吗?该变量在该范围内没有值。使用带引号的字符串并删除括号。 -filter "whencreated -gt '$filterdate'"

标签: powershell scope


【解决方案1】:

我确定问题是变量$filterdate 不存在于您创建的脚本块{ whencreated -gt "$filterdate" } 的范围内。语法很好....直到您将变量添加到组合中。可以肯定的是,在该范围内,$filterdate 将是空的。然后你得到了所有的邮箱,因为任何东西都大于 null(当然接受它自己)。

1 -gt $null
"asdf" -gt $null
True

使用正确引用的字符串,您可以获得相同的结果。

-filter "whencreated -gt '$filterdate'"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2014-04-14
    相关资源
    最近更新 更多