Link to home
Create AccountLog in
Avatar of SQLM_M
SQLM_MFlag for India

asked on

File Split and move processed to archive using powershell

Hi,

I tried to make code dynamic, but couldn't able to move the files. Please help me the solve this..

$pattern = @("Mobile Originated Call", "Mobile Terminated Call", "Network Info")

$SourcePath = "D:\tap3"
$FileType = "*.cdr"
$DestPath = "D:\tap3\Archive\"

Get-ChildItem "$SourcePath\$FileType" |
  % { # $_ is file
    $name = $_.name
    get-content $_ |
    % { # $_ is single line
      foreach ($p in $pattern)
      { if ($_.StartsWith($p))
        { Out-File -Append -FilePath "$SourcePath\$p\$name" -InputObject $_  }
      }
    }
Move-Item "$SourcePath\$p\$name" "$DestPath\$name" -Force
     
  }
Avatar of the_endjinn
the_endjinn
Flag of United Kingdom of Great Britain and Northern Ireland image

You are calling the variable $p outside of the foreach loop that defines it, therefore $p will be empty.

Move the move-item line into the foreach loop at the end.
Avatar of Qlemo
Exactly. Move the move-item line two lines higher, so it comes after the Out-File line.
And, please, put code into a code snippet tag (select the code, and press the CODE button). That improves reading.
$pattern = @("Mobile Originated Call", "Mobile Terminated Call", "Network Info")

$SourcePath = "D:\tap3"
$FileType = "*.cdr"
$DestPath = "D:\tap3\Archive\"

Get-ChildItem "$SourcePath\$FileType" |
  % { # $_ is file
    $name = $_.name
    get-content $_ |
    % { # $_ is single line
      foreach ($p in $pattern)
      { if ($_.StartsWith($p))
        { Out-File -Append -FilePath "$SourcePath\$p\$name" -InputObject $_  }
        Move-Item "$SourcePath\$p\$name" "$DestPath\$name" -Force
      }
    }
  }

Open in new window

Avatar of SQLM_M

ASKER

Hi,

When i execute the above code i get the following error,

Cannot find the path because it does not exist..
ASKER CERTIFIED SOLUTION
Avatar of the_endjinn
the_endjinn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of SQLM_M

ASKER

Hi,

Along with the move files to archive, I also want the count of each pattern in a file...i tried the following code, but i couldn't get the output...please give a solution..


$pattern = @("Mobile Terminated Call")
$SourcePath = "D:\tap3"
$FileType = "*.cdr"
$file="D:\tap3\Log\file.txt"
$a = (Get-Content $file).Count

Get-ChildItem "$SourcePath\$FileType" |
  % { # $_ is file
    $name = $_.name
    get-content $_ |
    % { # $_ is single line
      foreach ($p in $pattern)
      { if ($_.StartsWith($p))
       { (Get-Content $_).Count}
	   write-host $a    
      }
	
    }
  }

Open in new window

SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account