Frage

I'm trying to make a script where I copy a file from some place and store it in another one. I'm using foreach recursively to get all the files.

The question is: How can I get a path segment and replace it with another string? I want to do something like this:

Copy files from

C:\sites\somefolder\folder1\file.php

to

C:\sites\anotherfolder\folder1\file.php

In this example, I need to replace 'somefolder' with 'anotherfolder'. This is how I'm getting the full path:

foreach ($i in Get-ChildItem -Recurse -Force) { 
   Write-host $i.Fullname
}

Inside the loop, I tried to replace it using Fullname.replace, but things didn't work as expected:

$i.Fullname.Replace($PWD, "anotherfolder")
# This returns "anotherfolder/folder1/file.php", 
# instead of "c:\sites\anotherfolder\folder1\file.php

I don't know much of Powershell programming, so bear with me, ok?

Thx!

War es hilfreich?

Lösung

$PWD returns a PathInfo object, instead of a string like you were probably expecting. $PWD.Path returns a string, but even that could be problematic because you're trying to match for the entire path. If you know ahead of time the source and destinations, and they are both to remain in c:\sites\, you could do something like this:

$source = "somefolder"
$destination = "anotherfolder"

foreach ($i in Get-ChildItem -Recurse -Force) 
{ 
    $path = $i.DirectoryName -replace $source, $destination
    $name = $i.Fullname -replace $source, $destination
    if(!(Test-Path $path)) { New-Item -Path $path -ItemType directory }
    Copy-Item $i $name
}

I made this a little verbose, since you mentioned you're new to powershell. It replaces source content for both a new path and name variable with destination content. It then checks to see if your destination directory exists, creates it if it does not, and then copies the item there.

When you are changing parent directories, you could just include more of the source path in the source string to be replaced. In that circumstance, you would want to use [regex]::Escape($Source) to escape special characters.

Andere Tipps

$i.Fullname.Replace($PWD, "anotherfolder")

I think that your problem is in the $PWD variable; try to set a string name directly or to check the $PWD object type.

I tried the same thing on my pc; it works fine when the variable $PWD contains the Name property:

$PWD = (gi .).Name
foreach ($i in (Get-ChildItem -Recurse -Force)) { 
   $destination = $i.DirectoryName -Replace '\\somefolder','\anotherfolder'
   copy-item -path $i.fullname -destination $destination
}

Notes: .Replace method would not work $i.directoryname but -replace will work fine and has the benefit of being a regex operator (hence double \ to escape ).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top