Как составить папки с помощью команд cmd и power shell

powershell substring

Strings are fundamental to programming and scripting, and often, we need to work with just a part or subset of a string variable. In PowerShell, the substring method allows you to extract specific parts of a string based on the starting index and length of characters. This powerful feature is incredibly useful for manipulating and working with strings in various scenarios.

Whether you need to extract a single character, a word, or a substring from a larger string, the substring method in PowerShell provides an efficient and straightforward solution. In this comprehensive guide, we will explore the ins and outs of using the substring method in PowerShell. We will discuss the syntax, explore examples, and provide practical tips for effectively leveraging this functionality. By the end of this article, you will have a solid understanding of how to extract parts of a string using PowerShell’s substring method.

Introduction to PowerShell Substring

PowerShell is a versatile scripting language that provides powerful string manipulation capabilities. One of the most frequently used operations with strings is extracting a substring. A substring is part of a string, which can be a single character, a word, or a sequence of characters. A string is a collection of characters enclosed within single quotes (”) or double quotes (“”). The substring method allows you to extract a portion of a string based on the specified start index and length.

Understanding the PowerShell Substring Syntax

substring(StartIndex)
substring(StartIndex, length)
$stringObject.Substring(int startIndex, int length)

The substring() method requires one or two parameters:

  1. The startIndex parameter represents the zero-based index of the starting character of the string object. It denotes the position from where the substring extraction should begin.
  2. The second argument length is optional and represents the number of characters to be extracted from the string. If the length parameter is not provided, the substring method will return all the remaining characters from the startIndex position until the end of the string.
# PowerShell to extract text from string
PS C:\> $string = "Hello World"
PS C:\> $substring = $string.Substring(6)
PS C:\> $substring
World

In this example, we’re using the Substring function to extract a substring starting from the 6th character (which is the first character of the word “World”), and it extracts all characters from the 6th characters.

PowerShell Substring

Extracting Substrings with Start Index and Length

To extract a substring from a string using the substring method, you need to provide the start position, optionally, the length of the substring. Let’s consider an example where we have the string “Hello, World!” and we want to extract the word “World”:

$originalString = "Hello, World!"
$substr = $originalString.substring(7, 5)
Write-Host $substr

In the above example, we assign the string “Hello, World!” to the variable $OriginalString. We then use the substring method on $OriginalString with the start index of 7 (corresponding to the “W” in “World”) and a length of 5 to extract the substring. The output will be “World”.

To understand the character position better, think of each character in a string as having a unique index number. The string starts with an index of 0. So, when you need to find characters inside a string, you’ll be working with these index numbers.

Sometimes you may need to extract a specific number of characters from the beginning of a string. To accomplish this, you can use the substring method with a start index of 0 and the desired length. Let’s see a PowerShell substring example:

$OriginalString = "Hello World"
$FirstFiveChars = $OriginalString.substring(0, 5)
Write-Host $FirstFiveChars

In the above example, we assign the string “Hello World” to the variable $OriginalString. We then use the substring method on $OriginalString with a start index of 0 and a length of 5. This will extract the leftmost characters from the 0th index to 5 characters in length (first five characters) and output “Hello”.

Similarly, you may need to extract a specific number of characters from the end position of a string. To achieve this, you can combine the substring method with the Length property of the string. Let’s consider an example:

$OriginalString = "Hello World"
$LastFiveChars = $OriginalString.substring($OriginalString.length - 5)
Write-Host $LastFiveChars

In the above example, we assign the string “Hello World” to the variable $originalString. We then use the substring method on $originalString with a start index calculated as the length of the string minus 5. The output will be “World”. Note that we have only used the first argument.

Sometimes, you may need to extract a substring from a specific position within a string, regardless of the length. To accomplish this, you can use the substring method with a start index and omit the length parameter. Let’s see an example:

$originalString = "PowerShell Substring"
$substring = $originalString.substring(9)
Write-Host $substring

In this instance, we assign the string “PowerShell Substring” to the variable $originalString. We then use the substring method on $originalString with a start index of 9 to extract the substring starting from position 9 until the end of the string. The output will be “Substring”.

Find Substrings Using IndexOf Method

The IndexOf method in PowerShell allows you to find the position of a specific character or substring within a string. The IndexOf method returns the index position of the first occurrence of a specified character or substring within a string. If the character or substring is not found, it returns -1.

$originalString = "Hello World"
#Get the position of the substring
$index = $originalString.IndexOf("World")
$index

In this example, the $index variable will store the value 6, as “World” starts at index position 6 within the string “Hello World”.

find index of a substring in powershell

Example 1: Extracting Substrings Using IndexOf Method

You can combine the IndexOf method with the Substring method to extract part of the string based on a specific character or substring.

$originalString = "Hello World"
$substring = $originalString.Substring($originalString.IndexOf("W"))

The $substring variable will now contain the value “World”, as it extracts the substring starting from the first occurrence of “W” till the end of the string. You can also use the method LastIndexOf to find the last occurrence of a character or word.

Example 2: Using Substrings with an Array of Strings

Let’s say you have an array of strings, each in the format “FirstName-LastName”. You want to extract just the first names from this array using the substring method. Here’s how you can do that:

# Define an array of strings
$Names = @("John-Doe", "Jane-Smith", "Alice-Johnson", "Bob-Williams")

# Extract first names using substring
$FirstNames = $Names | ForEach-Object {
    # Find the position of the hyphen
    $HyphenPosition = $_.IndexOf('-')
    
    # Extract substring from the beginning to the hyphen using index values
    $_.substring(0, $HyphenPosition)
}

# Display the extracted first names
$FirstNames

Similar to single-string values, the Substring method can be used with an array of strings as well, as shown above.

Working with Left Substrings

Left substrings refer to the characters extracted from the leftmost side of a string.

$originalString = "Hello World"
$leftSubstring = $originalString.Substring(0, 5)

In this example, the arguments used define the start position and end positions of the characters. The $leftSubstring variable will now contain the value “Hello”. You can also extract left substrings with variable lengths by calculating the length dynamically.

Working with Right Substrings

Right substrings refer to the characters extracted from the rightmost side of a string.

$originalString = "Hello World"
$length = 5 # Int Length
$rightSubstring = $originalString.Substring($originalString.Length - $length)

The $rightSubstring variable will now contain the value “World”. Similar to left substrings, you can extract right substrings with variable lengths by calculating the length dynamically. Here, the $length variable can be set to any desired value, and the Substring method will extract the right side of a string accordingly.

:/>  Сбивается время компьютера (сервера) после выключения / перезагрузки | Windows для системных администраторов

Apart from the basic Substring method, PowerShell provides several advanced techniques to extract substrings based on different criteria.

Regular expressions (regex) offer powerful pattern matching capabilities for substring extraction. PowerShell supports regex through the -match operator.

To extract substrings using regex, you can use the -match operator:

$originalString = "Hello World"
$pattern = "W\w+"  # Matches a word starting with "W"
If($originalString -match $pattern)
{
    $substring = $Matches[0]
    $substring
}

In this example, the $substring variable will contain the matched substring “World”. Here is another example:

$string = "Hello World"
$regex = [regex]::Match($string, "\b\w+$")
$substring = $regex.Value
$substring

#Output: World

In another situation, I had to extract the value of “CN” from the AD Object path. Here is what I have used:

$Text = "CN=Salaudeen Rajack, OU=Users,OU=Singapore,OU=Offices,DC=Crescent,DC=Com"
if ($Text -match 'CN=(.*?),') {
    $Name = $Matches[1]
    Write-Output $Name
}
#Output: Salaudeen Rajack

When it comes to extracting a string inside a string, based on specific delimiters, the PowerShell split operator comes into play. The Split operator allows you to split a string into an array of substrings based on a specified delimiter. You can then access the desired substring from the resulting array.

$originalString = "Hello World"
$delimiter = " " # WhiteSpace character
$splitString = $originalString.Split($delimiter)
$substring = $splitString[1]

The $substring variable will now contain the value “World”, as it extracts the second element from the $splitString array.

$UserData = "user:john.doe@company.com"
$Username = $userData -split ":" | Select-Object -Last 1
$Username

You can also use the Replace method in PowerShell to remove specific characters or substrings from a string, effectively extracting the desired substring.

$originalString = "Hello World"
$substring = $originalString.Replace("Hello ", "")

The $substring variable will now contain the value “World”, as it removes the “Hello ” substring from the original string.

Extracting Substrings with Contains Method

The Contains method in PowerShell allows you to check if a string contains a specific substring. You can then extract the desired substring based on the result of the Contains method.

$OriginalString = "Hello World"
$substring = $originalString.Substring($originalString.IndexOf("World"))
if ($OriginalString.Contains("World"))
{
    $substring = $originalString.Substring($originalString.IndexOf("World"))
}

In this example, the $substring variable will contain the value “World” only if the original string contains the substring “World”. The contains() method is case-sensitive.

Real-World Examples of PowerShell Substring Method

powershell substring

Now that we’ve covered the basics of PowerShell substring, let’s take a look at some real-world examples of how it can be used.

Example 1: Extracting a File Extension

$path = "C:\Users\JohnDoe\Documents\Report.docx"
$extension = $path.Substring($path.LastIndexOf(".") + 1)
$extension
#Output: docx

In this example, we’re using the Substring function to extract the file extension from the file path. We’re finding the position of the last dot in the string using LastIndexOf(".") and adding 1 to get the position of the first character of the file extension. Similarly, you can extract the filename from the path as:

$FilePath = "C:\Users\JohnDoe\Documents\Report.docx"
$FileName = $FilePath.Substring($FilePath.LastIndexOf("\") + 1)

Example 2: Extracting a Substring between Two Characters

$string = "Hello (World)"
$startIndex = $string.IndexOf("(") + 1
$length = $string.IndexOf(")") - $startIndex
$substring = $string.Substring($startIndex, $length)
$substring
#Output: World

In the above script, we’re using the IndexOf function to find the position of the opening and closing parentheses. We’re then using the Substring function to extract the substring between the parentheses.

Handling Common Errors

When working with the substring method, it’s important to consider the below cases to ensure your code behaves as expected. Here are a few scenarios to keep in mind:

Edge Case 1: Start Index Out of Bounds

If the start index provided to the substring method is outside the bounds of the string, an error “startIndex cannot be larger than the length of string” will occur. To avoid this, you can validate the start index before extracting the substring.

$originalString = "Hello"
$startIndex = 10

if ($startIndex -ge 0 -and $startIndex -lt $originalString.length) {
    $substring = $originalString.substring($startIndex)
    Write-Host $substring
} else {
    Write-Host "Invalid start index"
}

In the above example, we check if the start index is greater than or equal to 0 and less than the length of the string. If it’s within the valid range, we extract the substring. Otherwise, we display an error message.

Edge Case 2: Length Exceeds String Length

If the length parameter provided to the substring method exceeds the length of the string, you’ll see an error message, “Index and length must refer to a location within the string”.

$OriginalString = "Hello"
$StartIndex = 0
$Length = 10

If ($Length -le $originalString.length) {
    $substring = $originalString.substring($startIndex, $Length)
    Write-Host $substring
} Else {
    Write-Host "Invalid Length!"
}

Edge Case 3: Negative Start Index or Length

The Substring method does not support negative indices. You need to calculate the starting index from the length of the string. Providing a negative start index to the substring method will result in an error “StartIndex cannot be less than zero” or “Length cannot be less than zero”. Make sure to validate the start index parameter before using it in the substring method.

Tips and Tricks for Using Substring in PowerShell Scripts

  • To extract the entire string starting from a specific index, you can omit the second parameter (length) of the substring method.
  • You can combine the substring method with other string manipulation techniques, such as concatenation, to build complex strings.
  • Remember that the substring method uses a zero-based index, meaning that the first character of a string is at index 0.
  • Be cautious when using negative start indices or lengths that exceed the string’s length, as this may result in unexpected behavior.
  • Keep in mind that PowerShell is case-insensitive by default. When performing substring extraction, ensure that you account for case sensitivity if required.
  • Always include error handling and validation mechanisms when extracting substrings. This helps prevent unexpected errors and ensures the substring extraction is performed correctly.

Wrapping Up

To sum up, the substring method in PowerShell is a powerful way to extract specific parts of a string. Whether you need to extract a single character, a range of multiple characters, or multiple substrings, the substring method provides the flexibility and control you need.

How can I extract a substring from a string in PowerShell?

PowerShell provides multiple ways to extract a substring from a string. One common method is to use the .Substring() method of the string object. For example:
$string = "Hello, World!"
$substring = $string.Substring(0, 5)
This code extracts the substring “Hello” from the $string variable by specifying the starting index (0) and the length (5) of the desired substring.

How do I get the last 3 characters of a string in PowerShell?

To get the last three characters of a string in PowerShell, you can use the Substring() method combined with the Length property of the string. Here’s an example: $lastThreeCharacters = $fullString.Substring($fullString.Length - 3)

How do you split each character in a string in PowerShell?

To split each character in a string in PowerShell, you can use the -split operator with an empty string as the separator. Here’s an example: "Hello, World!" -split ""

How to check a string for a substring in PowerShell?

How to remove a substring from a string in PowerShell?

To remove a substring from a string in PowerShell, you can use the -replace operator or the Replace() method. Here are examples of both approaches:
$fullString = "The quick brown fox jumps over the lazy dog."
$substring = "brown "
$modifiedString = $fullString -replace $substring, ""
With Replace method:
$modifiedString = $fullString.Replace($substring, "")

How do you check if a string contains any substring in an array in PowerShell?

How do you substring after a character in PowerShell?

:/>  Как узнать операционную систему компьютера

To extract a substring after a specific character in PowerShell by using the Substring() method combined with the IndexOf() method. Here’s an example:
$FullString = "Hello,World!"
$character = ","
$Substring = $FullString.Substring($FullString.IndexOf($Character) + 1)

This will start extracting from character 5 and extract all the characters from the given string.

How can I split a string into an array of substrings based on a delimiter?

Can I replace a substring within a string in PowerShell?

Yes, you can replace a substring within a string using the -replace operator or the .Replace() method. For example:
$string = "Hello, World!"
$newString = $string -replace "World", "PowerShell"

How do I find the index of a substring within a string?

Use the IndexOf method to find the starting index of a substring:
$string = "Hello, PowerShell"
$index = $string.IndexOf("Power")
This finds the starting index of “Power”, which is 7.


Cover image for How to retrieve sub properties in a PowerShell script with the Invoke-Expression method

Sometimes, you may want to access the sub properties of an object, which are the properties of the properties. For example, if you have a process object, you can access its name, id, memory usage, and other properties. But what if you want to access the properties of the process’s main module, such as its file name, version, or description? How can you do that in PowerShell?

One way to do that is to use the Invoke-Expression method, which evaluates a string as a PowerShell command and returns the result. This method can be useful when you want to dynamically construct a command based on some variables or parameters. For example, suppose you have a variable $path that contains the registry key path, and you want to get the value of a sub property named InstallPath under that key. You can use the Invoke-Expression method to construct and execute the command like this:

"(Get-ItemProperty -Path '' -Name 'InstallPath').InstallPath"

Enter fullscreen mode

Exit fullscreen mode

The result of this command will be the value of the InstallPath sub property, which is a string that represents the installation path of the .NET Framework. Note that the command is enclosed in double quotes, and the $path variable is expanded inside the single quotes. The parentheses around the Get-ItemProperty cmdlet ensure that the sub property is accessed after the cmdlet is executed.

Another example is to use the Invoke-Expression method to access the sub properties of a process object. Suppose you have a variable $MyPowershellProcess that contains a process object for the PowerShell process. You can use the Invoke-Expression method to get the file name of the process’s main module like this:

Enter fullscreen mode

Exit fullscreen mode

The result of this command will be the file name of the PowerShell executable, which is a string that represents the full path of the file. Note that the command is enclosed in double quotes, and the $MyPowershellProcess variable is expanded inside the quotes. The dot operator is used to access the sub property FileName of the MainModule property.

Enter fullscreen mode

Exit fullscreen mode


Dev Dispatch

In this tutorial, you will learn how to list files, folders, and subfolders using Windows CMD commands and PowerShell.

I’ll also demonstrate using the NTFS Permissions Tool, which is a graphical program that displays the permissions on folders and subfolders.

In this article

Check it out.

List Files and folders using the DIR Command

The dir command is built into all versions of Windows. It is an easy to use command to list files, folders, and subfolders from the Windows command prompt.

Let’s look at some examples.

Example 1. List files and folders in the current directory

To list the files and folders in the current directory, open the Windows command prompt, enter dir and press enter. The dir command by default does not display subfolders.

dir

In this example, my current location is c:\it, so when I run the dir command it will list everything in this folder.

cmd list folders

I have put the command output into colored boxes to explain what each column means.

  • Red = This column is the last modified date of the file or folder
  • Green = Indicates if the item is a folder, folders are labeled with DIR
  • Purple = The size of the file
  • Yellow = Name of the file or folder.

Example 2. List subfolders

Use the /s option to include subfolders.

dir /s

I ran the command from the c:\it location and it lists all subfolders and files from this directory. I’ve highlighted some of the subfolders in the screenshot below.

cmd list folder and subfolders

Example 3. Specify a directory path

To list files and folders from a specific directory enter the complete directory path.

dir /s c:\it

For example, if my current location is the root of c: and I type dir /s c:\it the command will display the items from the c:\it directory.

Как составить папки с помощью команд cmd и power shell

Example 4. Export list of files and folders

To export the screen output use the command below. You can name the file whatever you want, in this example, I named the file files2.txt

dir > files2.txt

The file will be saved to the current directory.

Как составить папки с помощью команд cmd и power shell

Pretty easy right?

I covered some of the most basic dir command options. To see a full list of options type dir /? and press enter.

Как составить папки с помощью команд cmd и power shell

Display Folder Structure using TREE Command

The tree command is another built-in Windows command. This command will display the contents of a directory in a tree structure. This can be useful to give you an overview of the folder layout.

You must specify a path or this command will start at the root of c

Example 1. List all folders and subfolders using TREE

To list all folders and subfolders enter the tree command and the path.

tree c:\it\toolkit
Как составить папки с помощью команд cmd и power shell

Example 2. List all folders and files using TREE

To include files with the tree command use the /f option.

tree c:\it\toolkit /f
Как составить папки с помощью команд cmd и power shell

In my experience, I never use the tree command. I find it more useful when a command provides more details like modified dates, permissions, ownership, and so on. If you just need to see the files and folders with no other details then this is a great option.

Powershell List Folders and Subfolders

You can use the Get-Childitem PowerShell cmdlet to list files and folders. The Get-Childitem cmdlet is similar to dir but much more Powerful.

Let’s look at some examples

Example 1. List files and folders using Get-Childitem

This example gets the folder contents from a specific directory

Get-ChildItem -path c:\it\toolkit
powershell get list of folders

By default, the Get-ChildItem cmdlet lists the mode, LastWriteTime, Length, and Name of the filer or folder.

  • l = Link
  • d – directory
  • a = archive
  • r = read-only
  • h = hidden
  • s = system

Example 2. Get subfolders using Get-ChildItem

Use the -Recurse option to get subfolders and files.

Get-ChildItem -path c:\it\toolkit -Recurse
powershell list files and folders

Example 3. Get items using the Depth parameter

You can use the -Depth parameter to control how many subfolders deep to include in the list.

Get-ChildItem -Path C:\it -Depth 2

Example 4. PowerShell List only specific file types

In this example, I will list only files that end in a .msi file extension. This will search all subfolders in the directory path.

get-childitem -path c:\it -include *.msi -recurse
Как составить папки с помощью команд cmd и power shell

Example 5. PowerShell List only folder or files name

The -Name parameter will only return the file or folder name.

Get-ChildItem -path c:\it\toolkit -Name
Как составить папки с помощью команд cmd и power shell

Example 6. PowerShell List all Files and Folder Details

To display all details of a file or folder use the fl option.

Get-ChildItem -path c:\it\toolkit | FL

You can see below this command will display additional details, if there are any.

:/>  Таблица IP-маршрутизации
Как составить папки с помощью команд cmd и power shell

Example 7. PowerShell count files and folders

To get a count of the files and folders use the measure-object option.

Get-ChildItem -path c:\it\toolkit | Measure-Object
powershell count folders

Example 8. Powershell Get Folder Size

You can also use the measure-object option to get the folder size.

Get-ChildItem -path c:\it\toolkit | Measure-Object -Property Length -sum
powershell get folder size

As you can see using PowerShell there are a lot of options when it comes to getting files and folders, you can create some really powerful reports.

Get Folder and Subfolder NTFS Permissions

If you need a report of folders and subfolders that includes who has permission to what, then check out the NTFS Permissions Reporting Tool below.

Example 1. List NTFS Permissions on Shared Folder

Как составить папки с помощью команд cmd и power shell
  • DirectoryName = Path of the folder
  • Account = Account listed on the folder (this can be a user or group)
  • DirectoryOwner = Owner listed on the folder
  • DirectoryRights = Permissions the user or group has to the folder
  • Type = Allow or Deny
  • AppliesTo = What the permissions applies to
  • IsInherited = Are the permissions inherited from a parent folder

Example 2. List Folder Permissions on Local Folder

If you want to check the permissions on a local folder click the browse button or enter the folder path.

Как составить папки с помощью команд cmd и power shell

Which Command Will You Use?

In this article, I showed you three different commands to get files, folders, and subfolders.

Which command did you find most useful? Let me know in the comments below.

Related Articles

Anuraag Singh


8 Minutes Reading

There are times when AD managers need to use PowerShell to get a list of computers in OU and sub OU of their Active Directory.

Table of Contents

Prerequisites to Complete Before Using PowerShell-Based Computer Location Retrieval

Among the computer languages, PowerShell is on the simpler side so learning it won’t be that hard. Glance through a few tutorials and check out Microsoft’s official documentation; this should provide you with more than enough knowledge to understand what we are about to do here.

  • Install the Remote Server Admin tools.
  • Add the ADDS (Active Directory Domain Services Role) role.
  • Upgrade the Windows Management Framework to version 3.0 or later.
  • Use the Active Directory Administrator account.
  • At last, download the AD Module for PowerShell by typing the following inside a fresh module.
Install-Module -Name RSAT-AD-PowerShell

After this is done, we can start with our main objective.

Basic PowerShell to Get List of Computers in OU and Sub OU in AD

First Scenario: Computer Objects in each OU.

Get-ADOrganizationalUnit -Filter * | ForEach-Object { 
    Write-Host $_.DistinguishedName
    Get-ADComputer -Filter * -SearchBase $_.DistinguishedName | ForEach-Object 
{ Write-Host ("  " + $_.Name) } 
}
  • The script retrieves all OUs.
  • Loops through each OU.
  • Displays OU’s Distinguished Name.
  • Retrieves computers within that OU.
  • Displays indented computer names.

Go for this approach when you want a detailed view of all OUs and their associated computers. It’s better for documentation purposes as it gives a complete picture of all OUs and their associated computer inventory.

Second Scenario: OU of each Computer Object.

Get-ADComputer -Filter * -Properties SAMAccountName, DistinguishedName | ForEach-Object {
  $ouPath = ($_.DistinguishedName -split ',')[1..($_.DistinguishedName -split ',').Length-1] -join '/'
  Write-Host $_.SAMAccountName + ": " + $ouPath

}
  • The script loops through each computer object in AD.
  • It extracts and stores the OU path from the DistinguishedName.
  • Finally, it displays the computer’s SAMAccountName, and its constructed OU path.

However, both of these scripts have some limitations.

  • Neither of them checks for any nested sub-OUs in AD.
  • Both give a temporary, non-shareable, read-only output.
  • Admin needs to run each of the “.ps1” cmdlets manually.

So to combat this, we have a better combination of scripts lined up for you.

Find Computer OU in Active Directory with Advanced PowerShell

Part 1. PowerShell script to make a CSV report of all OUs and Sub OUs a computer is in.

# Import the ADmodule
Import-Module ActiveDirectory
# Function to get OU/sub-OUs recursively
function Get-OUHierarchy {
    param (
        [string]$ou
    )
    $ouHierarchy = @($ou)
    $subOUs = Get-ADOrganizationalUnit -Filter * -SearchBase $ou -SearchScope OneLevel | Select-Object -ExpandProperty DistinguishedName
    foreach ($subOU in $subOUs) {
        $ouHierarchy += Get-OUHierarchy -ou $subOU
    }
    return $ouHierarchy
}

# Get all computers
$computers = Get-ADComputer -Filter * -Property DistinguishedName
# Create a custom object to store name and OU hierarchy
$computerOUs = $computers | ForEach-Object {
    $dnComponents = ($_ | Select-Object -ExpandProperty DistinguishedName).Split(',')
    $ouComponents = $dnComponents | Where-Object { $_ -like 'OU=*' }
    $ouPath = ($ouComponents -join ',').Replace('OU=', '').Replace(',', '/')
    # Get the full hierarchy of the OU
    $ouHierarchy = Get-OUHierarchy -ou $ouComponents[0]
    [PSCustomObject]@{
        ComputerName = $_.Name
        OUHierarchy = ($ouHierarchy -join ';').Replace('OU=', '').Replace(',', '/')
    }
}

# Export the results to a CSV
$computerOUs | Export-Csv -Path "C:\Temp\AD-Computer-Reports\Computer-Location $(get-date -f yyyy-MM-dd).csv" -NoTypeInformation

Save the script as Computer-Location-Reporter.ps1 on the path C:\Temp\AD-Computer-Reports\

We import an instance of the AD module and create a custom function that recursively gets all sub-OUs of an object in the hierarchy.

Then we call all the computer objects using their DN and split the DN into its components.

We filter out the OU part and use the custom function to see all that is in the overall hierarchy.

Then we put the results into yet another custom object and export it into a CSV output.

Part 2. Deploy a PowerShell script to set up continuous report generation via the Windows Task Scheduler app.

 $Time=New-ScheduledTaskTrigger -Weekly -WeeksInterval 2 -DaysOfWeek Monday -At 9am

 $Action=New-ScheduledTaskAction -Execute PowerShell.exe -WorkingDirectory C:/Scripts -Argument “C:\Temp\AD-Computer-Reports\Computer-Location-Reporter.ps1 -UserName <Admin> -Password <admin-pass>”

 Register-ScheduledTask -TaskName "Schedule Computer Location Status Report" -Trigger $Time -Action $Action -RunLevel Highest

We use PowerShell to create a scheduled task trigger that starts every Monday at 9 a.m.

The task is designed to start a PowerShell module on its own, set the directory to “C:\Temp\AD-Computer-Reports\” and then invoke the Computer-Location-Reporter.ps1 script.

However, truth be told, PowerShell in of itself is quite complex. Limiting the complexity of the script means losing out on functionality. So a better way would be to use an automated alternative.

Avoid PowerShell to Get List of Computers in OU and Sub OU in AD

If you want to retain the ability to pull CSV reports of computer OU data, then the SysTools AD Reporting Tool is the best possible choice. This tool combines countless lines of PowerShell scripts into a simple GUI-based interface.

Download Now Purchase Now

Step 2. Click on the big blue “REGISTER DOMAIN CONTROLLER” button.

Step 3. Type the custom domain-friendly name you want to use and add the IP address of the AD.

Step 4. On the domain details page, fill out the info section with appropriate data and validate.

Step 5. Go to the Reports tab and choose the All Computers option present in the Computers category.

Step 6. Click on the Preview button to get a list of computers in OU and sub OU without PowerShell.

Conclusion

author

By Mohit Jha

Mohit is a writer, researcher, and editor. Cyber ​​security and digital forensics are the two subjects that keep Mohit out of his seat. In addition, he hopes that the well-researched and thought-out articles he finds will help people learn.

Оставьте комментарий