【问题标题】:Partial Replace in PowershellPowershell 中的部分替换
【发布时间】:2020-05-19 16:17:11
【问题描述】:

假设我们有以下代码

Get-ADUser -Filter {Enabled -eq $false} -properties * | sort Surname| FT GivenName, Surname, description

它产生:

 GivenName      Surname           description                          
 ---------      ---------         ------- -----------                                              
 Tom            Abbott            AccountingSystems 
 Tim            Baker             AccountingSystems 
 Tyler          Cabot             AccountingSystems

我需要在“会计”和“系统”之间留一个空格

我认为这会起作用:

Get-ADUser -Filter {Enabled -eq $false} -properties *
% {
   $Description = $.replace("Accounting","Accounting ")
   Set-ADUser = -Description $Description
  }

但是……它没有。

【问题讨论】:

  • 这看起来不对...可能更像这样$_.Description.replace("Accounting","Accounting ")
  • 顺便说一句:如果this answer 是正确的,Enabled -eq $false 实际上并没有按预期工作。是吗?

标签: string powershell replace


【解决方案1】:

我建议你研究一些事情,

  1. 没有 $ 这样的变量。当您使用 ForEach 遍历项目时,您必须使用 $_(带下划线)
  2. 您不能为 cmdlet (Set-ADUser = ) 赋值。
  3. 您使用 |然后 %(不是 % | )

试试这个,

Get-ADUser -Filter {Enabled -eq $false} -properties Description | % {
   if ($_.Description) {
       $description = $_.Description.replace("Accounting","Accounting ") 
       Set-ADUser $_ -Description $Description
   } # else description is null.
}

Documentation for Set-ADGroup
Documentation for ForEach

【讨论】:

    猜你喜欢
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 2016-01-19
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多