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

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.

Related

Change currently running script

Is there any way to add text to specific part of script to the currently running script?
If i have a menu with options:
Install All
Add item
Quit
Could the Add item be possible?
Learning to use powershell (heavy user of batches).
When entering Add item, then a read-host would pop up, adding a row between the long row of ### addwifi -wnm $USERINPUT afterwards 'restarting' the script.
Current script:
#cmd: title Add****
$host.ui.RawUI.WindowTitle = "Add Wi-Fi networks"
#When Show-Menu –Title 'SetupWi-Fi' is called
function Show-Menu
{
# NOTE if changing warible from somewhere else (Show-Menu -WARIBLE VALUE) then param part must be included
param (
[string]$Title = 'SetupWi-Fi'
)
Clear-Host
#cls and echo on #echo off
Write-Host "================ $Title ================"
Write-Host "a: Add Wi-Fi networks."
Write-Host "q: Quit."
}
#Do this until x
#For future shortening purposes
function addwifi
{
param (
[string]$wnm
#wnm= wifi name
)
netsh wlan add profile filename="$wnm.xml"
#for some reason (nice for this script) . stops the warible name
}
do
{
# call Show-Menu and optionally change varible: –Title 'Warible' changes the $title varible
Show-Menu
# makin varible chaase equal user input, placing Selection before it
$chaase = Read-Host "Selection:"
#switch according to the varible chaase
switch ($chaase)
{
'a' {
#'single quote' acts as echo, now executing commands of 'a' varible
'Adding Wi-Fi networks.'
$host.ui.RawUI.WindowTitle = "Adding Wi-Fi networks"
#note the upper function is called with warible
#add below here! #####################################################################
addwifi -wnm laptopidee
#add above here! #####################################################################
}
#close a execution
#close switch
}
#close do
}
#until x: selection == input q
until ($chaase -eq 'q')
One possibility is to use placeholders that you replace at runtime, though I'm not sure how well it will hold up for more complex scripts.
For example, if you have the following script:
$scriptPath = "$PsScriptRoot\$($MyInvocation.MyCommand.Name)"
$scriptContent = Get-Content "$PsScriptRoot\$($MyInvocation.MyCommand.Name)" -Raw
$newItem = Read-Host "Please enter new command"
##Placeholder
$scriptContent -replace "$([char]0x0023)$([char]0x0023)Placeholder", "$([char]0x0023)$([char]0x0023)Placeholder$([char]0x000D)$([char]0x000A)$newItem" |
Set-Content -Path $scriptPath
Each time you run it, you will be prompted for a new command, which will be added below the ##Placeholder. So, if you enter Get-Process when prompted, the script would end up on-disk like this:
$scriptPath = "$PsScriptRoot\$($MyInvocation.MyCommand.Name)"
$scriptContent = Get-Content "$PsScriptRoot\$($MyInvocation.MyCommand.Name)" -Raw
$newItem = Read-Host "Please enter new command"
##Placeholder
Get-Process
$scriptContent -replace "$([char]0x0023)$([char]0x0023)Placeholder", "$([char]0x0023)$([char]0x0023)Placeholder$([char]0x000D)$([char]0x000A)$newItem" |
Set-Content -Path $scriptPath
Next time you run the script you will be prompted for a new command, which is added to the list, and all commands already on the list will be executed.
Yes. Use external files as sources to be pulled in. The Add Item menu option creates another file to be read in at next execution.
Many people did this with batch files using .ini files to hold parameters. Similar construct.

PowerShell to read or parse a numberset within a filename

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.

Powershell don't continue until certain key pressed

I have a script that's waiting for user input then depending on what they press does something. But, the problem is the script continues no matter what they press (but if it's not one of the two keys it's expecting, I just get errors). Here's the snippint I'm working on
Write-Host "What do you want to do next?" -nonewline
Write-Host "
u - Search for another user
c - Enter a computer name
"
# Prompt for an action
Write-Host ">> Select shortcut action: " -nonewline
$key = [Console]::ReadKey()
$value = $key.KeyChar
switch($value) {
c { $c = Read-Host "Enter computer or IP"}
u { $u = Read-Host "Enter user" }
}
# now we continue on with the code depending on what was pressed
What I'd like is if anything beyond c or u are pressed tell the user that's not a valid key and go back to the top of this snippint and prompt the user again for what action to do next.
Just wrap your code in a do-while loop that continues as long as $value is not c or u:
do
{
$key = [Console]::ReadKey($true)
$value = $key.KeyChar
switch($value) {
c { $c = Read-Host "Enter computer or IP"}
u { $u = Read-Host "Enter user" }
}
}
while ($value -notmatch 'c|u')

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.

Powershell - Loop script until user chooses to exit

How can I start a script over again? I have 3 switches and I want them to revert back to the beginning of the script.
Import-Module ActiveDirectory
Write-Host "--Please Login using a.account--"
#login
$credential = Get-Credential
#Main
Write-Host "--Remote Computer Rename v2.0--"
Write-Host "1. Query AD (Outputs to a text file)"
Write-Host "2. Quick computer rename"
Write-host "3. Quit"
$choice=Read-Host "Chose a number to continue"
#AD Query for computer
switch ($choice)
{
1 {
Write-Host "--Enter first five characters of computer name or full computer name i.e. USCLT--"
$cn=Read-Host 'Computer name'
$out="$cn*"
Get-ADComputer -Filter 'SamAccountName -like $out' >> c:\myscripts\dsquery.txt
Write-Host "Query complete. See dsquery.txt saved to Desktop."
}
...rest of my code.
So after See dsquery.txt saved to Desktop." I want it to go back to write-host portion.
Simple, short, stupid:
& cmd /c pause
exit
This will even contribute the "Press any key" message the TO requested. If you prefer to stay in PowerShell:
Read-Host "Press any key to exit..."
exit
But we may also get the input back:
$reply = Read-Host "Please type EXIT to exit"
if ($reply -eq "EXIT") { exit; }
I like that Read-Host exits the script when typing Ctrl-C, like cmd's pause does.
My personal favorite for checking user input is the do { } until () loop. Here is your code with the added loop, this will accomplish what your looking for:
Import-Module ActiveDirectory
Write-Host "--Please Login using a.account--"
#login
$credential = Get-Credential
#Main
do {
Write-Host "--Remote Computer Rename v2.0--"
Write-Host "1. Query AD (Outputs to a text file)"
Write-Host "2. Quick computer rename"
Write-host "3. Quit"
$choice=Read-Host "Chose a number to continue"
#AD Query for computer
switch ($choice)
{
1 {
Write-Host "--Enter first five characters of computer name or full computer name i.e. USCLT--"
$cn=Read-Host 'Computer name'
$out="$cn*"
Get-ADComputer -Filter 'SamAccountName -like $out' >> c:\myscripts\dsquery.txt
Write-Host "Query complete. See dsquery.txt saved to Desktop."
}
...rest of my code.
} until ($choice -eq 3)
This is a pretty unique strategy in my opinion. I took this from Jerry Lee Ford’s book : Microsoft Windows PowerShell Programming for the absolute beginner
you can read more about these and every other loop in powershell here : http://www.powershellpro.com/powershell-tutorial-introduction/logic-using-loops/
From a blog post I found:
echo "Press any key to exit..."
$Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") | OUT-NULL
$Host.UI.RawUI.FlushInputbuffer()
Enclose the whole thing in a while (1) {} block. That creates an infinite loop that will only terminate if it encounters a break (end the loop) or exit (end the script). Presumably, option 3 will lead to one of those statements.