Declare variable in home profile file don't work - powershell

I have home profile file Microsoft.PowerShell_profile.ps1 in C:\Users\User\Documents\WindowsPowerShell. I want declare some variable, e.g $A = 5. When I start new powershell terminal and want display this variable ($A) result is empty (I don't see 5).
P.S.
If I put in this place other command, e.g. Write-Host "Test text" I see this when open new powershell terminal.
Somebody know why? :(

Related

Cannot echo environment variable with space after storing in variable [duplicate]

This question already has answers here:
Return value of environment variable with powershell
(2 answers)
Closed 4 years ago.
Using Powershell prompt, I cannot seem to echo a system environment variable that has a space in it, stored in a variable.
For instance, if I do a simple:
echo ${env:My Var}
I get back the value of that environment variable - which is the word "test". That works great.
Then, if I echo a preset variable that is set to the string "My Var", I get back what I'd expect, the word "My Var".
echo $variable
If I then echo a hybrid of the two:
echo env:${variable}
I also get back what I'd expect, which is the string value "env:My Var".
But now I want to use that $variable to output the value of the corresponding environment variable. Meaning, I want to use something like:
echo ${env:${variable}}
... and get back the value of the environment variable, the word "test".
But that doesn't work. I get a red error saying Use `{ instead of { in variable names. But nothing like that works either.
Any help would be appreciated.
this worked for me:
cd env:
new-item 'test 123' -Value "123"
${env:test 123}
123
$var = 'test 123'
(Get-item env:$var).value
123
(Get-item env:$var).name
Test 123

Automate batch file prompts with powershell

I have a batch file which prompts the user a few times. I am looking to automate that with powershell. Is there any way to do this? I would need something like this:
Start-Process $InstallDir\Install.bat "y,*,$Version,y,y,y,y,y,y,y,y,y,y,y,y,y"
Install.bat runs an installation and there are a total of 16 prompts. The third I would like the be a variable that I have in my powershell script already, but the others will be static. Also, at the end of the script, you need to press any key to continue.
Is there any way to do this?
Depending on your batch file and what commands actually do the prompt, you might use input redirection <. Put the prompts into a text file pine by line and redirect that into your batch file.
Supposing the batch file prompts.bat contains the following commands...:
#echo off
set /P VAR="Please enter some text: "
echo/
echo Thank you for entering "%VAR%"!
choice /M "Do you want to continue "
if not ErrorLevel 2 del "%TEMP%\*.*"
pause
...and the text file prompts.txt contains the following lines...:
hello world
Y
n
End
...the console output of the command line prompts.bat < prompts.txt would be:
Please enter some text:
Thank you for entering "hello world"!
Do you want to continue [Y,N]?Y
C:\Users\operator\AppData\Local\Temp\*.*, Are you sure (Y/N)?
C:\Users\operator\AppData\Local\Temp\*.*, Are you sure (Y/N)? n
Press any key to continue . . .
(The del command shows two prompts here as it receives the RETURN behind Y which is not consumed by choice; since an empty entry is not accepted, the prompt appears one more time.)
Read-Host will display a prompt for entry, assigning it to a variable means you can then use that entry later in the script.
As your example is non-specific the below will only give you an idea of what you need to do.
$InstallDir = "C:\folder"
$Version = Read-Host -Prompt "Enter Version Number"
Start-Process "$InstallDir\Install.bat" -ArgumentList "y,*,$Version,y,y,y,y,y,y,y,y,y,y,y,y,y"

How to call a function within & in powershell?

Suppose I have a function in test.ps1, its name is show the code is like below:
. "some_path\some_other_script.ps1"
function show {
write-host "Hello World"
#some other function call from some_other_script.ps1
...
}
How can I call show in follow format (in a & - call operator)
powershell.exe "& '%test_script_path%\test.ps1'\show"
I think I need to dot source test.ps1 first in order to get dependencies in show function from some_other_script.ps1
I know I can create a new script and put the code in show in the new script instead of in a function. In that way, when do &... the script will be invoked. But I don't want to create a new script just for a very simple function
Thanks for any suggestion
You could dot source it and then call it like this.
powershell -Command ". '%test_script_path%\toolsql.ps1'; show"
The ; is used as a separator between commands.
I am really appreciated for the help and time from #Patrick Meinecke, the following command works.
powershell -command ". .\test.ps1;show"
Like he mentioned in the chat,
"So to explain that
the .\ just indicates it's in the current directory
it still needed the other . to tell powershell to load the script into the current context"

Batch file to set a PowerShell variable

For some reason i simply can't understand most of the sites who explain this question. So i'll try to ask here, if i'm am in the wrong place, just tell me in the comments and i'll put this in another forum and delete this question.
Let's say that i have 2 files, Batch.bat and PowerShell.ps1.
Batch.bat:
set A="ThisIsSuchVar!"
PowerShell.ps1:
$B = "Well, i don't know what to do here"
What can i do to the B variable be the same as the A variable?
Remember: I want the Batch variable to go to the PowerShell file. It's an one-way script. I want to use the built-in windows sources. And please, consider that i am a complete newbie in programming and don't speak english very well, so be the simplest possible, please.
In your batch file run.bat, set the environment variable A and run the PowerShell script:
set A=8
PowerShell.exe -File .\script.ps1
pause
In script.ps1, get the environment variable A, and assign its value to B:
$B=$Env:A
echo $B
When you run run.bat you get:
C:\Temp\try>set A=8
C:\Temp\try>PowerShell.exe -File .\script.ps1
8
C:\Temp\try>pause
Press any key to continue . . .

How can I add color to the machine name in the prompt of a PowerShell Remoting session?

To make it more obvious when I'm remoted to a live/production server, I thought it'd be handy to be able to colour the machine name I'm connected to when using remote PowerShell sessions.
However, I can't see a way to do this... The server name prefix seems to be independent of the Prompt function, and even if I could use that, I'm not sure how I could define a new Prompt only for the duration of the session.
Is there a way to customise this? Note: I don't want to color all server names the same, I'd like a distinction between local/production servers.
After some searching around it seems like you are correct that there is not built-in hook to override the pre-prompt [computername]: tag.
Luckily, I have a hacky workaround which could work for you!
To get color, we can just use Write-Host. Write-Host output from the prompt function will be fully left-justified, which is what we want. Unfortunately, the default [computername]: tag is inserted directly afterward. That results in the computer name being duplicated in the prompt, once with color and once without.
We get around this by returning a string containing backspace characters, so the un-colored [computername]: will be overwritten. This is the normal prompt string, typically the current path.
Finally, in case the normal prompt string is short and does not fully overwrite the un-colored [computername]: tag, we need to do some final cleanup by adding dummy space characters. That might push out the caret, though, so we need to add more backspaces to return the caret to the corrent position.
All-up, use this on your remote machine:
# put your logic here for getting prompt color by machine name
function GetMachineColor($computerName)
{
[ConsoleColor]::Green
}
function GetComputerName
{
# if you want FQDN
$ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
"{0}.{1}" -f $ipProperties.HostName, $ipProperties.DomainName
# if you want host name only
# $env:computername
}
function prompt
{
$cn = GetComputerName
# write computer name with color
Write-Host "[${cn}]: " -Fore (GetMachineColor $cn) -NoNew
# generate regular prompt you would be showing
$defaultPrompt = "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
# generate backspaces to cover [computername]: pre-prompt printed by powershell
$backspaces = "`b" * ($cn.Length + 4)
# compute how much extra, if any, needs to be cleaned up at the end
$remainingChars = [Math]::Max(($cn.Length + 4) - $defaultPrompt.Length, 0)
$tail = (" " * $remainingChars) + ("`b" * $remainingChars)
"${backspaces}${defaultPrompt}${tail}"
}
I use Posh-Git to accomplish this. See their Prompt Customization. I noticed that some of the docs are a bit out of date, if you just type $GitPromptSettings in PowerShell you will see all the properties available. Using Posh-Git has the added bonus of seeing Git stats on the prompt.
The command I use to set the machine name is ...
$GitPromptSettings.DefaultPromptPrefix = '$(get-content env:computername) '
Here is the color setting
$GitPromptSettings.DefaultPromptPath.ForegroundColor = 'Orange'