I need help fixing this powershell Unzip and copy script

Welcome Forums General PowerShell Q&A I need help fixing this powershell Unzip and copy script

This topic contains 3 replies, has 3 voices, and was last updated by

1 year, 4 months ago.

  • Author
  • #91277

    Topics: 8
    Replies: 13
    Points: 0
    Rank: Member

    I'm getting an error message when I run this script.

    It does copy the file to the target location.

    I will be a scheduled task so I just want to C:\Source\$subfolder because it will recurse.

    The folder nested will be 20180111 or 20180112

    This is the error that I'm getting

    xtract: C:\Target\New\20180108/D2_August_27_2017-workspace.xml
    New-Object : Exception calling ".ctor" with "2" argument(s): "The directory name is invalid."
    At line:32 char:110
    + ... | Out-Null |New-Object IO.FileSystemWatcher $path, $filter -Property ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

    This is the script

    # Exit if any command/function sees an error
    $ErrorActionPreference = "Stop"

    function Create-Dir-If-Not-Exist($fullPath) {
    if (!(Test-Path $fullPath)) {
    Write-Host "Create dir: $fullPath"
    New-Item -ItemType Directory -Path $fullPath

    function Unzip($zipfile, $outdir)
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    $zip = [System.IO.Compression.ZipFile]::OpenRead($zipfile)
    foreach ($entry in $zip.Entries)
    $destFilePath = [System.IO.Path]::Combine($outdir, $entry.FullName)
    $isDir = ($destFilePath.EndsWith("\") -or $destFilePath.EndsWith("/"))

    if ($isDir) {
    } else {
    $parentDir = [System.IO.Path]::GetDirectoryName($destFilePath)

    # Sometimes its parent directory is not an entry in $zip.
    # Therefore, we need to make sure its parent dir exists.
    # Also, Create-Dir-If-Not-Exist(..) is an equivalent of `mkdir -p`.
    # Therefore, we don't need to worry about the parent's parent.

    Write-Host "Extract: $destFilePath"
    [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $destFilePath, $true) | Out-Null |New-Object IO.FileSystemWatcher $path, $filter -Property @{
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'

    $zip_file_path = [IO.Path]::GetFullPath("C:\Source\20180111\20180108.zip")
    $dest_path = [IO.Path]::GetFullPath("C:\Target\New")
    Get-Date -DisplayHint Date

    Unzip $zip_file_path $dest_path

    I left out the part of the script with the email details.

    This is the original script before modification:

    #powershell Set-ExecutionPolicy RemoteSigned

    $Username = "cohen.carryl@gmail.com";
    $Password= "N4ture2017";

    function Send-ToEmail([string]$email, $foldername, $srcOrTarget){

    $message = new-object Net.Mail.MailMessage;
    $message.From = "ccarrylab@gmail.com";

    $FileNames = Get-ChildItem -Path $foldername
    if(Compare-Object $srcOrTarget "SRC"){
    $message.Subject = "$foldername folder recived ";
    $message.Body = "$FileNames files are received in the source folder";
    }else {
    $message.Subject = "$foldername folder copied";
    $message.Body = "$FileNames files are copied in the target folder";

    $smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", "587");
    $smtp.EnableSSL = $true;
    $smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);


    $srcPath = "C:\Source"
    $targetPath = "C:\Users\greatness\Target\"
    $fname = (get-date).ToString("yyyMMdd")
    $sourceFolder = "$srcPath\$fname"
    $targetFolder = "$targetPath\$fname"

    Add-Type -AssemblyName System.IO.Compression.FileSystem
    function Unzip
    param([string]$zipfile, [string]$outpath)
    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)

    if (Test-Path $sourceFolder ){
    $Files = Get-ChildItem $sourceFolder\*.* -include *.zip,*.out,*.err
    $srcZipFile = $Files | where {($_.extension -eq ".zip") }#Identifying zip file in the source path#

    if ((Test-Path $sourceFolder\*.out) -or (Test-Path $sourceFolder\*.err)){
    Send-ToEmail -email "ccarrylab@gmail.com" $sourceFolder $srcOrTarget;
    if (Test-Path $srcZipFile){
    $zipFolderName = $([io.fileinfo]"$srcZipFile").basename
    Unzip "$srcZipFile" "$sourceFolder\$zipFolderName"
    $tempList = get-childitem "$sourceFolder\$zipFolderName" -recurse
    $zipFileList = $tempList | where {($_.extension -eq ".err") -or ($_.extension -eq ".out") }

    if ($zipFileList.length -gt 0 ){

    Remove-Item $sourceFolder\$zipFolderName -Force -Recurse

    Remove-Item $sourceFolder\$zipFolderName -Force -Recurse


    Copy-Item $sourceFolder $targetPath -Force -recurse
    if (Test-Path $targetPath){
    $srcOrTarget = 'TGT'
    Send-ToEmail -email "ccarrylab@gmail.com" $targetFolder $srcOrTarget;

    Write-Host "There is no files received today yet"

  • #91280

    Topics: 2
    Replies: 929
    Points: 1,594
    Helping Hand
    Rank: Community Hero

    Cohen, this appears to be the same question your asked here-
    Are you saying that what was provide there did not get you to your resolution?

  • #91283

    Topics: 1
    Replies: 1330
    Points: 1,674
    Helping Hand
    Rank: Community Hero

    Is it really that hard to use the code formatting tags? You would do yourself and us a favor using them. I'd be easier to read and to debug your badly formatted scripts.
    If I can see right you're trying to pipe Out-Null to New-Object. What should be the purpose of that construct?

    • #91340

      Topics: 8
      Replies: 13
      Points: 0
      Rank: Member

      I was able to get it fixed.

      I used this script instead. It works, but the things I want to do is to only look for the latest folder. The client is sending folder in yyyymmdd Where do I need to add this to the script. I want to add a line on the only scan for the most reached created folder. It scans all the other subfolders and transfers all the files.

      param (
      [Parameter( Mandatory=$false)]

      [Parameter( Mandatory=$false)]

      [Parameter( Mandatory=$false)]

      [Parameter( Mandatory=$true)]

      [Parameter( Mandatory=$false)]
      #Declaring additional variables
      $EmailData = @()
      $ReportEmailSubject = "Great news. You received new wonder files from ABCD."
      $SMTPPass = $SMTPPass | ConvertTo-SecureString -AsPlainText -Force
      $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User,$Pass

      # Modify these Email Settings

      $smtpsettings = @{
      To = "cohen.carryl@yahoo.com","cohen.carryl@gmail.com","cohen.carryl@hotmail.com","cohen.carryl@msn.com"
      From = "Outbound@yahoo.com"
      Subject = "$ReportEmailSubject – $date"
      SmtpServer = "smtp.office365.com"
      Credential = $cred

      Function New-ReportRequest {
      [Parameter( Position=0,Mandatory=$true)]

      [Parameter( Mandatory=$true)]
      if ($Data.count -gt '0') {
      #Generating HTML Report

      BODY{font-family: Arial; font-size: 8pt;}
      H1{font-size: 18px; color: #419944}
      H2{font-size: 14px;}
      H3{font-size: 12px;}
      TABLE{border: 1px solid black; border-collapse: collapse; font-size: 8pt; margin-left: auto; margin-right: auto}
      TH{border: 1px solid black; background: #dddddd; padding: 5px; color: #000000;}
      TD{border: 1px solid black; padding: 5px; }

      Report Created: $now
      Total Files Moved: $($Data.count)
      $htmlbody = $Data | Sort-Object UserName | ConvertTo-Html
      $htmltail = "


      $htmlreport = $htmlhead + $htmlbody + $htmltail

      Send-MailMessage @smtpsettings -Body $htmlreport -BodyAsHtml -Encoding ([System.Text.Encoding]::UTF8) -UseSsl

      $allFiles = Get-ChildItem -Path $SourcePath -Recurse -Include $SearchParameters

      foreach ($file in $allFiles) {
      if ($file.Extension -eq ".zip") {
      Expand-Archive -Path $file.FullName -DestinationPath "$SourcePath\Temp" -Force
      $subFiles = Get-ChildItem -Path "$SourcePath\Temp" -Include $SearchParameters -Recurse
      foreach ($sub in $subFiles) {
      Copy-Item -Path $sub.FullName -Destination $TargetPath -Force
      $obj = New-Object PSObject
      $obj | Add-Member -MemberType NoteProperty -Name "SourceFile" -Value $($sub.FullName)
      $obj | Add-Member -MemberType NoteProperty -Name "TargetPath" -Value $TargetPath
      $EmailData += $obj
      } else {
      Copy-Item -Path $file.FullName -Destination $TargetPath -Force
      $obj = New-Object PSObject
      $obj | Add-Member -MemberType NoteProperty -Name "SourceFile" -Value $($file.FullName)
      $obj | Add-Member -MemberType NoteProperty -Name "TargetPath" -Value $TargetPath
      $EmailData += $obj

      New-ReportRequest -Subject $ReportEmailSubject -Data $EmailData

      The script work, but it is scanning all the folder in the source path.

The topic ‘I need help fixing this powershell Unzip and copy script’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort