This is my first of a few scripts that will use a hashtable. the following scripts will work with info from each previous hashtable. My conundrum is that when I run the script using a command line that points to it, the hashtable variables do not get updated, yet when I run the script as a whole, copy and pate it all into PS, the hashtable variable is exactly as it should be. I then add/remove a file or two from the directory, paste the full script again and the results are perfect again. I do run PS as an Administrator to process these scripts.
I've learned to make sure to run these all from the same PS tab. I've also concluded it really doesn't matter what dir shows in the PS tab as I'm pointing to the location of the script and pointing to the working dir all in the same line.
The filePath variable points to the folder where with the files I'm working with. The command line looks like this: C:\Users\Me\Powershell\DocumentCount.ps1 -filePath $filePath
Although the script is working perfectly, I'm showing it just so you see what I'm working with.
#Clear Variables at start:
if (Test-Path variable:Documents) {clear-variable -Name Documents}
if (Test-Path variable:files) {Clear-Variable -Name files}
# Get all files in the specified path
$files = Get-ChildItem -Path $filePath | Where-Object { $_.PSIsContainer -eq $false }
# Initialize a hashtable to store values and counts for each section[1]
$Documents = @{}
# Loop through each file
foreach ($file in $files) {
# Split the file name based on underscores
$sect = $file.BaseName -split '_'
$DocName = (($sect[0],$sect[1]) -join '_')
# Increment the count in the hashtable
if ($Documents.ContainsKey($DocName)) {
$Documents[$DocName]++
} else {
$Documents[$DocName] = 1
}
}
# Display the values and counts for each section[1]
foreach ($sectionKey in $Documents.Keys) {
Write-Host "$sectionKey Count: $($Documents[$sectionKey])"
}
Again, I simply can not figure out why this script is not processing correctly when run as a command line.
Thank you.
filePathas a parameter. But here is a tip while writing scripts in a language you are not yet familiar with, take each step one at a time and test as you go. In your case, the first step is getting the$filePath, so create a script with only one line:Write-Host $filePath. Open a fresh copy of PowerShell and run the script to see what happens. Better yet, use VSCode and follow these instructions to insure each execution is on a fresh copy of PowerShell.