I am new to PowerShell, and am having trouble getting it to "echo" some variables back to a generated '.ps1' file. The use case is that I am attempting to make a script generator for media conversion that will generate another re-useable script once you enter all the required information.
Here is a sample of the code:
# Initialize
$TRACK_COUNTER=0
$artist=Read-Host -Prompt "Artist/Band Name"
$language=Read-Host -Prompt "Language (use ISO 639-2 codes)"
$album_or_single=Read-Host -Prompt "Is this an Album/Sound-Track or a collection of Singles (0 for album/sound-track, 1 for single's)"
# Album
if ($album_or_single -eq 0) {
$album=Read-Host -Prompt "Name of the Album"
$date=Read-Host -Prompt "Enter the release date of the album (in YYYY-MM-DD format, or type nothing if unknown)"
$genre=Read-Host -Prompt "Genre of the Album"
$cover_art=Read-Host -Prompt "Select the audio/image file with the Cover Art (ex. MP3/M4A or JPG/PNG)"
Get-ChildItem "*.mp3"
$track_amount=Read-Host -Prompt "How many Tracks/Songs are in this Album"
New-Item "$album [Generated].ps1" -ItemType File
Write-Output -Path "$album [Generated].ps1" -Value 'This is a text test.'
}
# Singles
if ($album_or_single -eq 1) {
$track_amount=Read-Host -Prompt "How many seperate Single's are there"
}
Sorry for the bad formatting, and the (probably) improper use of brackets. The problem is that nothing ends up going into the generated file (it actually ends up generating). The last thing Powershell spits out is:
"-Path
In Sound Mind [Generated].ps1 (example sound-track)
-Value
This is a text test."
I'm sure I'm doing something very wrong, sorry if its a really easy fix. Thanks! (Also I'm doing this on Linux)
Revised sample (thanks Theo):
# Initialize
$TRACK_COUNTER=0
$artist=Read-Host -Prompt "Artist/Band Name"
$language=Read-Host -Prompt "Language (use ISO 639-2 codes)"
$album_or_single=Read-Host -Prompt "Is this an Album/Sound-Track or a collection of Singles (0 for album/sound-track, 1 for single's)"
# Album
if ($album_or_single -eq 0) {
$album=Read-Host -Prompt "Name of the Album"
$date=Read-Host -Prompt "Enter the release date of the album (in YYYY-MM-DD format, or type nothing if unknown)"
$genre=Read-Host -Prompt "Genre of the Album"
$cover_art=Read-Host -Prompt "Select the audio/image file with the Cover Art (ex. MP3/M4A or JPG/PNG)"
Get-ChildItem "*.mp3"
$track_amount=Read-Host -Prompt "How many Tracks/Songs are in this Album"
New-Item "$album [Generated].ps1" -ItemType File
Add-Content -LiteralPath "$album [Generated].ps1" -Value 'This is a text test.'
}
# Singles
if ($album_or_single -eq 1) {
$track_amount=Read-Host -Prompt "How many seperate Single's are there"
}
Related
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.
I have a snippet in powershell that reads questions from a flat file and prompts the user to provide a boolean or string response (i.e. Do you like flying cars? Why do you like skydiving?). All answers are written to a .xls for consumption to a DB later.
I can make the script repeat question for users that do not select a boolean answer (i.e. A, B, C or "Yes", "No"). However getting a user to provide a string (short) answer) is a bit more trickier.
$Question7 = Get-Content -path $PSScriptRoot\src\Question7.txt -raw
Write-Host $Question7 -ForegroundColor Yellow
$reason_for_hobby = Read-Host -Prompt "Please write in the answer"
Writ-Host "Answer: $reason_for_hobby" -ForegroundColor Green
Add-Member -inputObject $infoObject -memberType NoteProperty -name "HBYREASON" -
value $reason_for_hobby
I am trying to figure out how to force users to provide at least a 215 character response, and to repeat the question if one is not provided.
Thanks and stay safe.
You can achieve this with a simple while-loop (While $reason_for_hobby has less than 215 characters repeate):
while ($reason_for_hobby.Length -lt 215){
$reason_for_hobby = Read-Host -Prompt "Please write in the answer"
}
However better would be a do-while-loop if the variable $reason_for_hobby is not initialized before (do this once and repeate while $reason_for_hobby has less than 215 characters):
do{
$reason_for_hobby = Read-Host -Prompt "Please write in the answer"
}while ($reason_for_hobby.Length -lt 215)
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.
I have a script which asks for user input and then uses it as a variable to validate a directory path exists, however when a user inputs * the validation comes back successful where it should fail.
the input is done via Read-Host, sample of the code is below.
$userinput = Read-Host -Prompt "Enter Value"
if(Test-Path -Path "c:\$userinput\") {"Valid"} else {"not valid"}
Just writing #PetSerAl's comment as an answer
-path treats * as a wild card which likely causes the success.
The solution is to use -LiteralPath which treats the path literally.
$userinput = Read-Host -Prompt "Enter Value"
if(Test-Path -LiteralPath "c:\$userinput\")
{
"Valid"
}
else
{
"not valid"
}
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.