using a global variable in multiple functions powershell

3.8k views Asked by At

I have this code :

$Count=0

Function DryRun-UploadFile($DestinationFolder, $File, $FileSource, $Count)
{


    if($FileSource -eq $null){
        $FileSource = $Folder
    }
    $path= [String]$FileSource+'\'+$File
            $Size = get-item $Path
        $Size = $Size.length

    if($Size -lt 160000){
    Write-Host "Passed"
    }else{
    $Count=$Count+1

    }
}

function DryRun-PopulateFolder($ListRootFolder, $FolderRelativePath, $Count)
{

        Write-Host "Uploading file " $file.Name "to" $WorkingFolder.name -ForegroundColor Cyan
        if(!($File -like '*.txt')){

        #Upload the file
        DryRun-UploadFile $WorkingFolder $File $FileSource $Count
        }else{
            $Count=$Count+1

        }

    }



}


Function DryRun-Copy-Files{


    $AllFolders = Get-ChildItem -Recurse -Path $Folder |? {$_.psIsContainer -eq $True}

    #Get a list of all files that exist directly at the root of the folder supplied by the operator
    $FilesInRoot = Get-ChildItem -Path $Folder | ? {$_.psIsContainer -eq $False}

    #Upload all files in the root of the folder supplied by the operator
    Foreach ($File in ($FilesInRoot))
    {

        #Notify the operator that the file is being uploaded to a specific location
        Write-Host "Uploading file " $File.Name "to" $DocLibName -ForegroundColor Cyan

        if(!($File -like '*.txt')){
        #Upload the file
        DryRun-UploadFile($list.RootFolder) $File $null $Count
        }else{
             $Count=$Count+1

        }



    }

    #Loop through all folders (recursive) that exist within the folder supplied by the operator
    foreach($CurrentFolder in $AllFolders)
    {

        DryRun-PopulateFolder ($list.RootFolder) $FolderRelativePath $Count



    }

Write-output "Number of files excluded is: "$Count | Out-file DryRun.txt -append



}

I have removed some of my code for simplicity sake as it has nothing to do with my problem. My code goes through a file structure and counts up if the file is above 160000 bytes or is a txt file. run calling DryRun-Copy-Files. And I have a variable called $count which I want to use in all the functions and then output what the count is to a file. The problem is it only counts in the first function DryRun-Copy-Files not in the others

1

There are 1 answers

0
Martin Brandl On BEST ANSWER

define the variable with global:

$global:count=0 

and use it in the functions (don't explicit pass it)