1

I am trying to get the path for the OU my laptop is currently in. Here is what I have

gpresult /r /scope computer >> c:\temp\ou.txt

FIND "CN=" "C:\Temp\ou.txt" > C:\Temp\ou1.txt

The output is CN=My-PC,OU=Computers,OU=Information Technology,OU=XXXXXXX,OU=Corporate,DC=XXXXXXXX,DC=com

What I need to do is get the CN=MY-PC and extract the CN= The names will be different every time, so I need from the first , back to the beginning of the line

I havent found anything that gets me close.

Does anyone have any idea how to get the desired output?

Edited to answer Ricardo Desired output is My-pc stored as a variable %My-pc%

4
  • Can you show what the output you want should look like, I got a bit confused in " so I need from the first , back to the beginning of the line" Commented Jan 20, 2023 at 17:13
  • CMD doesn't have many options for splitting strings - take a look at FOR /F loops to split out tokens like stackoverflow.com/a/40784439/7411885. If you can use powershell, then $MyPC = (Get-Content c:\temp\ou.txt | Select-String 'CN=(.*?),').Matches.Groups[1].Value is pretty simple.
    – Cpt.Whale
    Commented Jan 20, 2023 at 17:49
  • Can you explain why you're grabbing computer name from gpresult rather than just using hostname? There are some better ways even if you need to look up with AD/ldap. gpresult can also dump to xml or html if you want better data formatting
    – Cpt.Whale
    Commented Jan 20, 2023 at 17:53
  • As part of as data migration script for my company, I want to grab the ou path and then remove the pc name and have the new pc name put in and move the object. If I do it manually, it works. I am trying to get the info so it does it without help. Commented Jan 20, 2023 at 19:26

1 Answer 1

0

enter image description here

Use a direct filter in a for loop filtering the line where it's easier to get the CN

for /f tokens^=6 %%i in ('gpresult /r /scope computer ^| findstr /e Mode')do echo\%%i
:: Or...
for /f tokens^=6 %%i in ('gpresult /v ^| findstr /e Mode')do echo\%%i


Additional resources:

3
  • 1 last think lo-ol What is the variable called so I can apply it to other parts of the script? Commented Jan 23, 2023 at 14:09
  • replace: ...)do echo\%%i to ...)do set "_my_variable=%%~i" and use %_my_variable%...
    – Io-oI
    Commented Jan 23, 2023 at 14:11
  • echo just echo, to define use set "name=value"
    – Io-oI
    Commented Jan 23, 2023 at 14:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .