简体   繁体   English

POWERSHELL:正则表达式查找和替换

[英]POWERSHELL: Regex Find and replace

I want to search and replace parts of UserObject paths using regex. 我想使用正则表达式搜索和替换部分UserObject路径。

If you query windows for Users in Local Groups it returns the members as in the example below. 如果您在本地组中查询用户的窗口,则会返回成员,如下例所示。 Local users are displayed with an domain related prefix and i want to find this domain prefix an delete it form local user paths. 本地用户显示与域相关的前缀,我想找到这个域前缀和从本地用户路径删除它。

Return Value:

\\MyDomain\PCTest\John Doe   #(Local User)
\\MyDomain\Julie Doe         #(Domain User)

After Formating: (how can i do this?)

\\PCTest\John Doe             #(Local User)
\\MyDomain\Julie Doe          #(Domain User)

This will remove the first element if the path contains more than two elements: 如果路径包含两个以上的元素,这将删除第一个元素:

'\\MyDomain\PCTest\John Doe','\\MyDomain\Julie Doe' | Foreach-Object{

    if( ($items = $_.Split('\',[System.StringSplitOptions]::RemoveEmptyEntries)).Count -gt 2)
    {
        '\\'+ ($items[1..$items.count] -join '\')

    }
    else
    {
        $_
    }
}

\\PCTest\John Doe
\\MyDomain\Julie Doe

supposing your values are stored in c:\\temp\\users.txt : 假设您的值存储在c:\\ temp \\ users.txt中:

gc C:\temp\users.txt |%{if ($_ -match "local"){$_.replace("MyDomain\","")}}

edit : 编辑:

$slices="\\MyDomain\PCTest\John Doe".split('\')
if($slices.Count -eq 5){wh "\\$($slices[3])\$($slices[4])"}
"\\MyDomain\PCTest\John Doe", "\\MyDomain\Julie Doe" | % {
  $_ -replace '\\MyDomain(\\.*\\)', '$1'
}

Another possibility: 另一种可能性

'\\MyDomain\PCTest\John Doe','\\MyDomain\Julie Doe' |
ForEach-Object {
'\\{0}\{1}' -f $_.split('\')[-2,-1]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM