How to write to user input in powershell - powershell

In my profile script for powershell I want to write to user input, so that when i start powershell I will already have something in my input and have only to press enter.
I need something like "write-input".
I have already tries "echo", "write-input".

I would do something like:
$defaultvalue = "This is the default value"
$a = read-host -Prompt "$defaultvalue (enter)"
if (!$a) {$a = $defaultvalue}
write-host "the value is now $a"

Related

Giving a predefined value to a Read-Host operation in powershell [duplicate]

I have a PowerShell script (which I cannot change) with the following function inside it:
function Foo ([string] param1) {
[...]
$var1 = Read-Host "Test"
$var2 = Read-Host "Test2"
[...]
}
I want to call the function from my PowerShell script and want to prevent that the user has to input any values, instead I want to prepare hardcoded values.
I tried the following:
#("Var1Value", "Var2Value") | Foo "Param1Value"
But it still prompts the user. Any ideas?
During command discovery, functions take precedence over binary cmdlets, so you can "hide" Read-Host behind a fake Read-Host function:
# define local Read-Host function
function Read-Host {
param([string]$Prompt)
return #{Test = 'Var1Value'; Test2 = 'Var2Value'}[$Prompt]
}
# call foo
foo
# remove fake `Read-Host` function again
Remove-Item function:\Read-Host -Force

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.

Powershell beginner here, cant figure out how to transfer parameters from funtions to outside the function, like this

Heres an example that wont give a value to the $Prompt outside the function, atleast not from my perspective
function funkyfunction {
$Prompt = Read-Host "Write something"
}
funkyfunction
Write-Host "You wrote: $Prompt"
You want to return the Prompt variable
function funkyfunction {
$Prompt = Read-Host "Write something"
return $Prompt
}
$Prompt = (funkyfunction)
Write-Host "You wrote: $Prompt"
Another way, if you are going to output all the time, is simply to use the variable squeezing also, the variable scope is important.
function funkyfunction
{
$Script:Prompt = Read-Host "Write something"
}
funkyfunction
# Output to the screen is the default, so Write-* not really needed
"You wrote: $Prompt"
# Results
<#
Write something: test
You wrote: test
#>
Or squeezing
function funkyfunction
{
("You wrote: $(($Prompt = Read-Host 'Write something'))")
}
funkyfunction
# Results
<#
Write something: test
You wrote: test
#>

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.

Testing for Working Directory

My first steps were to create 2 variables and set their value to args[0] and args[1], then have an if statement containing some error checking with Write-Warning and a Read-Host to capture user input and store the value in the variables.
Here is my code:
# Create 2 command line variables
$workingdirectory = ARGS[0]
$directoryname = ARGS[1]
## Check if variables are empty and get user input if necessary
if ("$workingdirecytory" -eq "") {
Write-Warning "Parameter Required"
$workingdirectory = Read-Host "Enter absolute path to working directory"
Write-Warning "Parameter Required"
$directoryname = Read-Host "Enter directory name to search for in $workingdirectory"
}
Write-Host "$workingdirectory"
Write-Host "$directoryname"
The question is:
Write an if statement like this: If (“$WorkingDirectory” –eq “”) {
Inside the script blocks add the following:
use Write-Warning cmdlet to display a message “Parameter Required”
use Read-host to capture user input and store the value in the variable $WorkingDirectory
Repeat for DirectoryName
Am I suppose to have another if statement for the directory name?
Trying to make the output look like this:
by:
Now execute your code by typing the file name with no parameters
Execute the code by typing the file name and one parameter
Execute the code with the correct parameters