Appending variable to string to pull value of existing variable - powershell

I'm currently learning PowerShell and I can't work out how to combine a string and a variable to pull information from an existing variable.
The user input will just be a number, so 1,2,3 etc. which I need to append to the end of $option which will pull the title information from the variable $optionX.
So far everything I've tried just interprets it as a string and print $OptionX into the console, as opposed to the value held by $OptionX.
So for example:
function Title{
Write-host "$OptionName for:"$computerSystem.Name -BackgroundColor DarkCyan
}
function GetMenu {
# Set the menu options
$Option1 = "1) System Information"
# Get menu selection
$Navigation = Read-Host "Enter Selection"
ToolBox
}
function ToolBox{
Clear-Host
switch ($Navigation){
1 { #Script 1
Title
}

You can do what you do in the self-answer. I would suggest using a hash-map for it though - seems cleaner to me. (I have no idea what the $computersystem.Name-part is, so I just left it in):
function Title{
Write-host "$($Options[$Navigation]) for:"$computerSystem.Name -BackgroundColor DarkCyan
}
function GetMenu {
# Set the menu options
$Options = #{
"1" = "1) System Information"
"2" = "2) Something else"
}
# Get menu selection
$Navigation = Read-Host "Enter Selection"
ToolBox
}
function ToolBox{
Clear-Host
switch ($Navigation){
1 { #Script 1
Title
}
}
}
For the rest of your script I can see that you are using Global Variables extensively, which I would avoid (it will confuse you, makes it harder to understand what is going on, and many other reasons not to use them). Look into using parameters for your functions, using the snippet menu (CTRL+J) in Powershell ISE will make a quick function skeleton for you. When you want to develop further in Powershell functions look into the Cmdlet (advanced function) template in the same menu.

I figured out how to do it, I'm not sure if it's the best method but it does what I need it to do.
function Title{
$OptionCombine = "Option"+$Navigation
$OptionName = Get-variable $OptionCombine -ValueOnly
Write-host "$OptionName for:"$computerSystem.Name -BackgroundColor DarkCyan
}

Related

Powershell Switch Break Label not being executed

As part of a larger script I have implemented the switch detailed below. The intention is that when the script is executed a user can choose to either
enter users to be migrated on-screen, or
import from a file.
If the import from file option is selected - I want to test the file is present - if not I want to break out and go back to the switch label :choose. However when I select the import from file option and provide a non-existent path the script continues and does not break or return to the label. Where am I going wrong?
$chooseInputMethod = #"
This script migrates one or more user accounts between two trusted domains in a forest e.g. from domain1 to domain2 (or vice versa)
Select method to specify user(s) to migrate:
1. Enter name(s) on-screen (default)
2. Import name(s) from file
Enter selection number
"#
$choosePath = #"
Enter path to file..
Notes
- Filename:
If file is located in script directory ($pwd) you can enter the filename without a path e.g. users.txt
- No quotation marks:
DO NOT put any quotes around the path even if it contains spaces e.g. e:\temp\new folder\users.txt
Enter path or filename
"#
$enterUsernames = #"
Enter username(s) seperate each with a comma e.g. test1 or test1,test2,test3`n`nEnter name(s)
"#
cls
:choose switch (Read-Host $chooseInputMethod) {
1 { cls; $usersFromScreen = Read-Host $enterUsernames }
2 {
cls;
$usersFromFile = Read-Host $choosePath;
if (-not (Test-Path $usersFromFile -PathType Leaf)) {
break choose
}
}
default { cls; $usersFromScreen = Read-Host $enterUsernames }
}
Write-Host "hello"
From the documentation for break:
In PowerShell, only loop keywords, such as Foreach, For, and While can have a label.
So, switch, even though it has looping capabilities, is not considered a loop in this case.
However, in this case I don't see why break without a label would not suffice.
A break to the switch will exit it. There's only one loop (switch, which works on arrays), so there's no difference between a plain break and breaking to the switch. You seem to want the switch inside another loop to repeat it.
# only runs once
:outer while (1) {
'outer'
while (1) {
'inner'
break outer
}
}
outer
inner
Demo of switch with a label and looping. The documentation isn't perfect.
# only runs once
:outer switch (1..10) {
default {
'outer'
foreach ($i in 1..10) {
'inner'
break outer
}
}
}
outer
inner
Another switch demo.
switch (1..4) {
{ $_ % 2 } { "$_ is odd" }
default { "$_ is even" }
}
1 is odd
2 is even
3 is odd
4 is even

Why weird assignment from variable inside Powershell switch statement?

I'm a beginner at Powershell and am struggling to understand some syntax from some code I found on Github. I've read the docs on Powershell assignment, and on switch statements, and can't understand what is going on with the = $Yes and = $No in this code snippet:
Switch ($Prompt3) {
Yes {
Stop-EdgePDF
Write-Output "Edge will no longer take over as the default PDF viewer."; = $Yes
}
No {
= $No
}
}
I haven't been able to find any references to this kind of syntax, and it doesn't seem to do anything in the script. So why is it there?
UPDATE: This issue has been resolved.
Looks to me like the variable name that was getting the assignment was deleted in a change back in August.
$PublishSettings = $Yes
Was changed to:
= $Yes
And:
$PublishSettings = $No
Was changed to:
= $No
Looks like poor search and replace.
I've created an issue for the problem at GitHub.
There are many characters that are valid in a function (or variable) name; this includes the = symbol. What you're observing is a function or alias.
Examples:
# standard function
function =
{
return $args
}
# accessing the function: drive
${Function:=} = {
return $args
}
# defining a new alias
New-Alias -Name = -Value Get-Variable
# using the Alias attribute
function Test-Thing
{
[Alias('=')]
param()
return $args
}

Return output from Powershell script to UIPath using Invoke power shell

I am trying to get a value from an input box from a Powershell script back to a UI Path Sequence. I have created a simple sequence as an example. Yes, I know I could do this all in UI Path, I am just using an easy example as a way to try and test this for future use cases. Here is my sequence:
My text file from "Read text file" is:
$test = "Desktop/PassingArgs2of2.ps1 -Message foo"
Invoke-Expression -Command $test
The activity in UiPath looks like so:
The psCmd that I am running in the Invoke power shell activity looks like this:
Param(
[parameter(Mandatory=$true)]
[string]
$Message)
try{
$Global:fooVar = $null
function Test-InputBox(){
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$msg = "fooMsg"
$title = "fooTitle"
$localtest = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
$Global:fooVar = $localtest.ToString()
}
Test-InputBox
}
catch{}
I tried setting fooVar equal to testLocal in the PowerShellVariables within Invoke power shell and then writing it, but that did not work.
Basically I want to get fooVar back into UI Path. Any help would be greatly appreciated. Thank you!
You're almost there. First, your Powershell script has to return a value. Take this for example:
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$title = 'Your title goes here'
$msg = 'Your favorite color:'
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
return $text
Here's the script in action (note that I called it twice and provided "red" the first time:
Then, just use this script directly in the Invoke Powershell activity. Note that the most important part here is the Output property - here, I decided to go for an array of strings. Naturally, as we only return a single value, you can just access the text provided by the user by accessing output(0).ToString().

Writing a hashtable value to an attribute

Powershell newbie here, my first script.
I have user objects with an AD custom attribute named tvCode with a values of 123456 or 6787682 or 983736 etc.
I would like to script something that will get the tvCode value from the user object
When:
123456 = Sony
6787682 = Samsung
9837343 = LG
Write the value of "Sony" or "Samsung" or "LG" to the "City" attribute of the user object.
Looks like i may need to use a hashtable.
If possible do this for a specific OU
hope this makes sense
thanks
function Convert-TVCode {
Param
(
[parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
[String[]]
$Code
)
Process {
foreach ($C in $Code) {
switch ($C) {
"123456" {$brand = "Sony"}
"6787682" {$brand = "Samsung"}
"9837343" {$brand = "LG"}
default {
$brand = $null
Write-Warning "$C not included in switch statement. Returning"
return
}
}
if ($brand) {
Write-Verbose "Code '$C' matched to Brand '$brand' -- searching for users to update"
Get-ADUser -Filter "tvCode -eq '$C'" | Set-ADUser -Replace #{tvCode=$brand}
}
}
}
}
This function will allow you to update any users that have their tvCode attribute set as one of the target numerical values. You can have it hit multiple codes at once as well.
Examples:
Convert-TVCode -Code 123456
Convert-TVCode -Code 123456,6787682
Convert-TVCode -Code 123456,6787682,9837343 -Verbose
Update the switch statement in the function to customize it to your actual values and let me know if you have any questions!

How do I tell my script to go back to a certain point of the script?

Here is my script so far:
$BookTitle = Read-Host "Enter Book Title"
If ($BookTitle -eq "")
{
[System.Media.SystemSounds]::Beep.Play();
Write-Host "Please enter a book title"
}
Else
{
Write-Host "" ;
Write-Host "Book title is: $BookTitle"
}
What I want to do is if a user enters a book title that is null, I want the script to execute the error code block:
{
[System.Media.SystemSounds]::Beep.Play();
Write-Host "Please enter a book title"
}
and jump back to the beginning of this particular segment:
$BookTitle = Read-Host "Enter Book Title"
Instead of continuing on with the rest of the script. I don't want it to jump to the beginning of the entire script because I plan on using this kind of logic frequently within the script.
I'm not sure how to do it. I've tried using loops instead like Do...While, Do...Until, While, but I keep getting infinite loops.
So my question is, what am I doing wrong? Should I be using loops instead of conditional statements? A mixture of both?
Do {
$BookTitle = read-host "enter booktitle.."
[System.Media.SystemSounds]::Beep.Play();
} while ($BookTitle -eq "")
$BookTitle