PowerShell to read or parse a numberset within a filename - powershell

I'm using PowerShell to check that certain files are present in a folder location. If they are all present then the script will just state that 0 files are missing and if there are missing files it will tell you which ones are missing.
The files that I'm checking have a date at the end of the filename. I need my script to ignore that part of the filename or read the date part and so long as the rest of the filename is present return no errors.
Filename example: 0106-pos-20170917123002.data
The bit of the filename I'm really interested in is 0106-pos-.data.
Here is my script:
$storenum = Read-Host -Prompt "Store number (include leading zero)"
#$mbo_ip = Read-Host -Prompt "Back office IP"
$missing = 0
$sdc_pump = "\\10.xxx.xxx.xxx\gkretail\sdc\stores\device-pump"
$pos_data_file = $storenum + "-pos-"
$sdc_path = $sdc_pump + "\" + $pos_data_file
"--"
"Device Pump: config\parameter files"
if (-not $(Test-Path $sdc_path\.data)) {
$missing++; "$sdc_path\.data not present"
}
"=="
"Store $storenum is missing $missing entries"
"=="
if (0) {
}

Another person called Curtis (from Powershell forum) helped me get this script working so I'm sharing it here.
I was trying to get the wild card option working but just couldn't get it right but Curtis managed it.
$storenum = Read-Host -Prompt "Store number (include leading zero)"
$missing = 0
$sdc_pump = "\\10.xxx.xxx.xxx\gkretail\sdc\stores\device-pump"
$pos_data_file = $storenum + "-pos-"
$sdc_path = $sdc_pump + "\" + $pos_data_file
"--"
"Device Pump: config\parameter files"
if (-not (Get-ChildItem "$sdc_path*.data")) {
$missing++
"$sdc_path.data not present"
}
"=="
"Store $storenum is missing $missing entries"
"=="
This script now works fine.
I still want to thank you guys for any help and time you spent on my issue.

Related

Cleaning up filenames from MAC using Powershell

I'm writing a script that iterates over files that are copied from a MAC computer to a Exfat disk and checks the name of the files for Windows forbidden characters.(Writing it in PowerShell)
And hopefully replace the forbidden characters with another character, for example a "-".
Why i am doing this is because i see it as a good way for me to practice coding and it might be used in my work when we get users with a lot of local files that we want to move to Onedrive.(Onedrive has a function to rename but it doesn't touch the forbidden characters, and i don't know Bash)
The issue is when I'm trying to find the characters within the script itself, it cant find the characters if i write them in the script.(For example if i write that it should look for ">")
Even if i escape the characters it just skips it(Or rather doesn't find it).
It just skips over the file i know has one in it, at first i though it might be due to encoding, but no matter what i use as a default encoding it wont display the filename correctly.(I assume this is due to how Windows reads filenames?)
edit: These are the forbidden characters im goint to look for " * : < > ? / \ |
The script itself is able to remove letters and stuff if i ask it to.
I also tried getting the char of the byte([byte][char]"") but i get this error:
Cannot convert value "" to type "System.Byte". Error: "Value was either too large or too small for an unsigned byte." Edit: the  changed by itself during the day not sure what to say.
If i just add it to the function it just returns the error:Rename-Item : The input to the script block for parameter 'NewName' failed. Exception calling "Replace" with "2" argument(s): "String cannot be of zero length.
The characters are displayed like this in visual studio code.
Any ideas are welcome or if you know of any better ways of doing it?(Maybe its better if i just learn bash. )
Here is the script itself:
edit: cleaned up the script abit and some small changes.
$provided_path = Read-Host "What Directory and its subfolders do you want to check?"
# Iterates over the folders and files within.
Write-Host "Creating list of files..."
$dictionary_filenames = ""
$dictionary_filenames = Get-ChildItem -Path $provided_path -Recurse -Force -File | Select-Object FullName,BaseName,Extension
# Resetting counter
$counter_skipped = 0
# Function for character replacment
function rename_file_name($names_function,$forbidden_char){
$old_name = $names_function.BaseName
$new_name = $names_function | Rename-Item -LiteralPath $names_function.FullName -NewName{$_.BaseName.Replace("$forbidden_char","-") + $_.extension} -PassThru
if($old_name -ne $new_name.BaseName){
Write-host "$old_name changed to $new_name"
}
}
foreach($names in $dictionary_filenames){
if($names.BaseName[0] -eq "." -and $names.BaseName[1] -match "_"){
$counter_skipped ++
$counter ++
continue
}
else{
if($names.BaseName[0] -eq " " -or $names.BaseName[-1] -eq " "){
$old_name = $names.BaseName
$new_name = $names | Rename-Item -LiteralPath $names.FullName -NewName{$_.BaseName.trim() + $_.extension} -PassThru
Write-Host "Trimming whitespace: $old_name"
}
else{
Write-Host "Trimming not needed "$names.BaseName
}
Write-host "Checking forbidden characters "$names.BaseName
rename_file_name $names ">"
rename_file_name $names "<"
rename_file_name $names "/"
}
}
Write-Host "Files checked: "$dictionary_filenames.Count
Write-Host "Files Skipped: "$counter_skipped
Read-Host 'Close window by pressing "Enter"'```
 is U+F021, two bytes long or [int16]. You can put it in a utf8 with bom encoded script.

Powershell Script to compare File-Hash from a Stream and published

Good morning guys,
I'm new to powershell scripting. And i can't figure out what I'm doing wrong.
I tried to write a .ps1 script to compare the hash value of a stream. I used the microsoft documentation for help and modify it to a runable script so i don't need to write it over and over again.
$wc = [System.Net.WebClient]::new()
$pkgurl = Read-Host "Please enter Package Url: "
$publishedHash = Read-Host "Enter Published Hash: "
$FileHash = Get-FileHash -InputStream ($wc.OpenRead($pkgurl))
if ($FileHash.Hash -eq $publishedHash) {
Write-Host "File Hash is equal to published Hash."
}
else {
Write-Host "File Hash NOT equal to published Hash."
}
When i run the script and enter the package url and the published Hash, the program all of a sudden abruptly shuts down.
Please, anyone an idea?
The script ends as it has nothing else to do.
You can add read-host at the end to wait for user input before it closes. (it wont do anything with the input, this just forces it to stay open until input has been made.)
Alternatively if you want to use it multiple times without it closing you can create a loop:
$KeepOpen = $true
While($KeepOpen -eq $true){
$wc = [System.Net.WebClient]::new()
$pkgurl = Read-Host "Please enter Package Url: "
$publishedHash = Read-Host "Enter Published Hash: "
$FileHash = Get-FileHash -InputStream ($wc.OpenRead($pkgurl))
if ($FileHash.Hash -eq $publishedHash) {
Write-Host "File Hash is equal to published Hash."
}
else {
Write-Host "File Hash NOT equal to published Hash."
}
$user_input = Read-Host "Please enter Y to run again"
if($user_input -ne "Y"){
$KeepOpen = $false
}
}
This will keep the script open so you can see the results and if you want it to run again insert Y and hit enter and you should be back to where you start.

Automate Removal of a Path System Environment Variable

I'm running into an issue where a removal and reinstallation of a particular application is creating duplicate entries in System Variables under Path. So for example, it's showing C:\Apps\folder;C:\Apps\folder;typical entries.
While this is not causing a problem with functionality of the app, I'd prefer to not have the entry in there twice (or more if it requires an additional removal/installation). I want to automate something so I don't have to go into each system and manually remove one of those entries.
Can this be done through either a batch file or a PowerShell script? I'm not able to find a way, but hopefully someone here will know a way. It's fine if the method removes both entries, as I can add something to the script to add one of them back. One important note, I need to make sure everything else under Path is left intact.
Here is a script (taken from a Microsoft repository) that I used to do the exact same thing.
$RegKey = ([Microsoft.Win32.Registry]::LocalMachine).OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\Environment", $True)
$PathValue = $RegKey.GetValue("Path", $Null, "DoNotExpandEnvironmentNames")
Write-host "Original path :" + $PathValue
$PathValues = $PathValue.Split(";", [System.StringSplitOptions]::RemoveEmptyEntries)
$IsDuplicate = $False
$NewValues = #()
ForEach ($Value in $PathValues)
{
if ($NewValues -notcontains $Value)
{
$NewValues += $Value
}
else
{
$IsDuplicate = $True
}
}
if ($IsDuplicate)
{
$NewValue = $NewValues -join ";"
$RegKey.SetValue("Path", $NewValue, [Microsoft.Win32.RegistryValueKind]::ExpandString)
Write-Host "Duplicate PATH entry found and new PATH built removing all duplicates. New Path :" + $NewValue
}
else
{
Write-Host "No Duplicate PATH entries found. The PATH will remain the same."
}
$RegKey.Close()

Printing ZPL (Zebra Programming language) file via Powershell

I wrote a Powershell script that asks questions, takes the user's input, plugs those variables in a label created in ZPL, then print it out via Out-Printer. Everything seems to work fine except the label that prints has incorrect spacing or missing data.
Originally I had the script create a .txt file that held the label in ZPL format. Checking the label all the data was correct. When I would print the .txt file from Notepad using the same printer (Driver was set to Generic/ Plain text). The label would be perfect.
I also tried switching the printing method to the WMI variant. It would do the same formatting issues and missing data, but now in different spots.
It almost seems Powershell is formatting the data before it prints.
Here is the current code I have with some data censored for privacy concerns.
$i = 0
$global:counter = $i + 1
$AllPrinters = gwmi win32_printer -computername $env:computername
$DefaultPrinterString = $AllPrinters | where {$_.Default -eq $true}
$DefaultPrinter = [regex]::match($DefaultPrinterString, '\"([^\"]+)\"').Groups[1].Value
Write-Host "========== Print Company Labels =========="
Write-Host "Question will be on the left, type in answer and hit ENTER"
$location = Read-Host "Which location? (LOC1 or LOC2)"
$pro = Read-Host "What is the Pro#?"
$quote = Read-Host "What is the quote number?"
$pallet = Read-Host "How many pallets are there?"
$printer = Read-Host "What printer do you want?"
While ($global:counter -le $pallet)
{
$printcode = "^XA^MCY^XZ^XA^SZ2^MMT^MTT~JSN^LT0^MD0^MNY^PR5^PON^PMN^CI0^LRN
^FT300,1300^A0B,350,160^FDPRO: $pro^FS
^FT480,1300^A0B,175,150^FD$location^FS
^FT480,1300^A0B,175,150^FD$location^FS
^FT480,900^A0B,175,100^FDQuote: $quote^FS
^FT800,1300^A0B,350,225^FDPallet $global:counter of $pallet^FS
^PQ01~*QUANT,04~,0,~*COPIES,04~,N^MCY^XZ"
(New-Object -ComObject WScript.Network).SetDefaultPrinter($printer)
$printcode | Out-Printer
Start-Sleep 1
(New-Object -ComObject WScript.Network).SetDefaultPrinter($DefaultPrinter)
$global:counter++
}
Any help would be greatly appreciated.
Thanks in advance

powershell Import-csv pop up

so i am working with a bit of code that after setting a static location for the CSV i am using for import. When i run the code it seems to run until i get the Windows can't open this File pop. you know the one with what do you want to do options, like user the web services to find the correct program. i am copying the code so hopefully someone can point on where i made this fubar. just for note before i made the CSV static the Script asked you to type the location in every time so maybe i missed a setting there
if ($args[0] -eq $null)
{
$userNameFile = D:\lync_creation\userlog.csv
$userNameFile = $usernamefile -replace '"',""}
else
{$usernamefile = $args[0]}
if ($userNameFile -ne "")
{$csv=import-csv $userNameFile}
else
{"Could not find a valid .csv with the user information."
exit}
foreach($c in $csv)
# enable for lync
{
"Enabling " + $c.Identity + " for Lync 2010"
Enable-csuser -identity $c.Identity -registrarpool pool01.west.com –sipaddresstype EmailAddress
}
write-host "Press any key to continue..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,AllowCtrlC")
You are seriously over complicating things if you're just going to use a static location for your CSV file.
$csv = Import-CSV D:\lync_creation\userlog.csv
foreach($c in $csv){
"Enabling $($c.Identity) for Lync 2010"
Enable-csuser -identity $c.Identity -registrarpool pool01.west.com –sipaddresstype EmailAddress
}
write-host "Press any key to continue..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,AllowCtrlC")
The first line imports the CSV file into a variable.
The next 4 loops through all entries in that variable, write the host who it's enabling and then enables the person.
The last 2 lines give a Press any key to continue message and then waits for a key press before continuing.