Share via

Powershell Replace issues

Anonymous
2022-07-09T16:42:22+00:00

I have this script that works perfect

$Source= "C:\Dir1" 

$Destination= "C:\Dir2" 

$LogfilePath= $Destination + "\Log.txt"

 Get-ChildItem -Path $Source -File -Recurse | ForEach-Object {

     $NewDir = $_.DirectoryName.Replace($Source, $Destination) 

     #see if destination directory exists

     if(-not(Test-Path -Path $NewDir)){

         New-Item -Path $NewDir -ItemType Directory | Out-Null   

     }

     Copy-Item -Path $_.FullName -Destination $NewDir

     Write-Host '.' -NoNewline

     #added to validate time stamp in log file is working

 Start-Sleep -Seconds 1

     "$([DateTime]::Now) copied - '$($_.name)' from '$($_.DirectoryName)' to '$NewDir' Size: $([System.Math]::Round(($($_.Length)/1KB),2))KB"  | Add-Content $LogfilePath

 }

If i try to get user input for $source

$Source= Read-Host -Prompt "Enter the source directory (example c:\dir1)"

The Replace does not work. It keeps it as $source instead of making it Dir2

Can anyone help me figure this out? I have been messing with it for a couple hours now

Windows for home | Windows 10 | Settings

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Anonymous
    2022-07-09T17:46:29+00:00

    Hi, my name is Anderson Souza, I hope I can help you with your issue.

    I believe that your question will be better resolved if it is posted in a more suitable location such as the new Microsoft Q&A forum that is replacing the old TechNet. As it is a question aimed at professionals with scripting skills, I believe that you will get better results there, since this forum here is intended for home Windows users. Please, check the link below:

    https://docs.microsoft.com/en-us/answers/products/

    You can try posting you question on the PowerShell forum.

    https://docs.microsoft.com/en-us/answers/topics...

    Was this answer helpful?

    0 comments No comments