PowerShell is a powerful scripting language that allows you to automate tasks on your computer. One common task is moving files and directories from one location to another. In this article, we will focus on using the Move-Item cmdlet in PowerShell to only affect directories.
First, let's understand what Move-Item does. It is a cmdlet that allows you to move items, such as files and directories, from one location to another. By default, Move-Item moves both files and directories. However, if you only want to affect directories, you can use a simple trick.
The trick is to use the -Directory parameter with Move-Item. This parameter tells PowerShell to only move directories and ignore any files. Here's an example:
Move-Item -Path "C:\Source\*" -Destination "C:\Destination\" -Directory
In the above example, we are moving all directories from the "C:\Source\" directory to the "C:\Destination\" directory. The -Path parameter specifies the source directory, and the -Destination parameter specifies the destination directory. The -Directory parameter ensures that only directories are moved.
It's important to note that the -Directory parameter is only available in PowerShell 3.0 and later versions. If you are using an older version of PowerShell, you won't be able to use this parameter. In that case, you can use a workaround.
The workaround involves using the Get-ChildItem cmdlet to get all directories and then using a loop to move each directory individually. Here's an example:
$directories = Get-ChildItem -Path "C:\Source\" -Directory
foreach ($directory in $directories) {
Move-Item -Path $directory.FullName -Destination "C:\Destination\"
}
In the above example, we first use Get-ChildItem to get all directories in the "C:\Source\" directory. We store the directories in the $directories variable. Then, we use a foreach loop to iterate over each directory and move it to the "C:\Destination\" directory using Move-Item.
Now you know how to use Move-Item in PowerShell to only affect directories. Whether you are using the -Directory parameter or the workaround with Get-ChildItem, you can easily move directories to a new location.
References
| Source | Link |
|---|---|
| Microsoft Docs - Move-Item | https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/move-item?view=powershell-7 |
| Microsoft Docs - Get-ChildItem | https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7 |