I have a Powershell script which does a lot of things and one of them is moving files:
$from = $path + '\' + $_.substring(8)
$to = $quarantaine + '\' + $_.substring(8)
Move-Item $from $to
But it happens the directory structure isn't already present in the $to
path. So I would like Powershell to create it with this commando. I've tried Move-Item -Force $from $to
, but that didn't help out.
What can I do to make sure Powershell creates the needed directories in order to get things working?
I hope I make myself clear, if not, please ask!
PowerShell Create Directory If Not Exists using Test-Path If a path or directory is missing or doesn't exist, it will return $False. Using PowerShell New-Item cmdlet, it will create directory if not exists using Test-Path.
The Test-Path Cmdlet$Folder = 'C:\Windows' "Test to see if folder [$Folder] exists" if (Test-Path -Path $Folder) { "Path exists!" } else { "Path doesn't exist." } This is similar to the -d $filepath operator for IF statements in Bash. True is returned if $filepath exists, otherwise False is returned.
The Move-Item cmdlet moves an item, including its properties, contents, and child items, from one location to another location. The locations must be supported by the same provider. For example, it can move a file or subdirectory from one directory to another or move a registry subkey from one key to another.
In the PowerShell console, type Move-Item –Path c:\testfolder -Destination c:\temp and press ENTER. Replace c:\testfolder with the full path to the folder you want to move; and c:\temp with the full path of the target folder.
You could create it yourself:
$from = Join-Path $path $_.substring(8)
$to = Join-Path $quarantaine $_.substring(8)
if(!(Test-Path $to))
{
New-Item -Path $to -ItemType Directory -Force | Out-Null
}
Move-Item $from $to
You could use the system.io.directory .NET class to check for destination directory and create if it doesn't exist. Here is an example using your variables:-
if (!([system.io.directory]::Exists($quarantine))){
[system.io.directory]::CreateDirectory($quarantine)
}
Copy-File $from $to
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With