Display a variable's name along with output? - powershell

Sometimes when I'm writing a script I want to dump the value of a bunch of variables in my script to the console along with the variable's name.
Instead of having to do "var1: $var1" for all of my variables is there a powershellism that can display a bunch of variables along with their names? Is there some kind of convenient reflectiony thing for this?

You can use Get-Variable cmdlet, which return PSVariable objects to you. By default, them formatted as table with two columns: Name and Value.

Related

Format command output in powershell

I have a output like below from a command
IpPrefix
--------
15.181.232.0/21
142.4.160.136/29
3.2.0.0/24
161.188.154.0/23
Using above output, need write a command in powershell to get format like :
15.181.232.0/21,142.4.160.136/29,3.2.0.0/24,161.188.154.0/23
Basically combine multiple lines to one line with comma separated. Please help.
Welcome to PowerShell! The results of commands are objects. This object you have made has at least 1 property called IpPrefix. If your object is stored in a variable $object, then you can reference the property like this:
$object = (some-command -param something)
$object.IpPrefix
Once you're got the items in just that one column, without the column header, you now have an array of strings. They're still objects, but they are string objects.
The -join operator works against arrays.
$object = (some-command -param something)
$object.IpPrefix -join ','
This will give you what you want in the simplest way possible.
Let's say maybe you don't want to store your data in a variable (aka in Memory). You might have a pipeline or some other situation where storing the data slows you down. You would do that like this:
(some-command -param something).IpPrefix -join ','
Same idea, different syntax. Hope this helps you understand the shell better!

Powershell outputs vertically

I just wanted to run a simple command like echo #profile, but the output is vertical. I can theoretically read and understand the output, but it is a big unconvenience. How can I fix it?
You don't normally reference variables with an # symbol, you almost always use the $ to reference a variable's value by the variable name. You can also use the Variable: provider or Get-Variable, but I won't get into those here.
If you were to omit echo, you would actually get the following error message:
The splatting operator '#' cannot be used to reference variables in an expression.
'#var' can be used only as an argument to a command. To reference variables
in an expression use '$var'.
This is because using #var is a technique called Splatting, which is the practice of using an array or hashtable to provide the arguments to a command, function, or cmdlet. Note you cannot currently splat arguments to methods. Review my answer linked above for more information on how to actually splat arguments in several use cases.
As for why you get the vertical output, note that echo is actually an alias to Write-Output. Write-Output accepts positional arguments, for which it will output each object passed in on its own line. When you splat a string as an array of arguments to a function, it converts the string to an array of characters, so effectively you are passing in each character of #profile to Write-Output as its own argument, then spitting each element of the array back out. And when PowerShell displays an array directly to the console, it displays each element on its own line.
Note: Of the different Write- cmdlets, Write-Output is unique in that it will output each positional parameter on its own line as it returns an array for each argument you pass in. The other Write- cmdlets will instead join each element of the array into a single space-delimited string. The Write- cmdlets come into play when working with the different output streams in PowerShell. Here is another answer of mine which explains what the different output streams mean and how to write to them.
In addition, for displaying purely information text to the end user that does not need additional programmatic processing in your script or session, use Write-Host.
This is why you get the vertical output, because #profile is being converted to an array, then splatted into Write-Output as an array of characters, and Write-Output will write back all arguments of an array as individual elements of a new array. PowerShell will then display the new array with each element on its own line.
I suspect what you actually want to do is output $profile. You can use one of the following techniques (note that echo/Write-Output are often redundant to use):
# Use the alias
echo $profile
# Use Write-Output
Write-Output $profile
# Omit Write-Output entirely
$profile
# View one of the alternative profiles by name
# CurrentUserCurrentHost is the default
# and is most often the one you are looking for
$profile.CurrentUserCurrentHost
$profile.CurrentUserAllHosts
$profile.AllUsersCurrentHost
$profile.AllUsersAllHosts

Remove imported localized data

How do I remove localized data in PowerShell?
Say that I have imported localized strings for a script and then want to remove this to be able to import it again.
I haven't found any cmdlet for it and don't know if this is saved in $host and can be removed there.
The data is imported, with the following:
Import-LocalizedData -BindingVariable msgTable -FileName $SomePSDataFile -BaseDirectory $SomeNeighbouringFolder
If you mean you have imported the strings as variables, you should be able to clear them using the Clear-Variable command.
PowerShell stores its variables on a drive called Variable:. You can treat this like a normal drive and list the variables using a dir or a Get-ChildItem, for example, dir Variable:\ will return all your currently defined variables.
You can then clear the variables you want with the Clear-Variable command. You provide this command with the variable name without the $ sign in front of it.

How to change default output Formatting of Powershell to use Format-Table -autosize?

How can I enforce powershell to use
Format-Table -auto
as a default formatting when writing a returned array of objects to the console?
Thanks
If you are OK calling the cmdlet every time and if you have at least PowerShell v3.0 then you can set a $PSDefaultParameterValues which you can read more about at about_Parameters_Default_Values.
The syntax that would satisfy your need would be:
$PSDefaultParameterValues=#{"<CmdletName>:<ParameterName>"="<DefaultValue>"}
So we add in the switch by setting it to $true.
$PSDefaultParameterValues = #{"Format-Table:Autosize"=$true}
To remove this you would have to do it much the same as you would a hashtable element
$PSDefaultParameterValues.Remove("Format-Table:Autosize")
From the aforementioned article here is some pertinent information as to how to deal with these.
$PSDefaultParameterValues is a preference variable, so it exists only in the session
in which it is set. It has no default value.
To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs
at the command line.
If you type another $PSDefaultParameterValues command, its value replaces the original
value. The original is not retained.
To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues
command to your Windows PowerShell profile. For more information, see about_Profiles.
Outside of that I am not sure as it would be difficult to change in a dynamic sense. You would want to be sure that data sent to the stream appears on screen in the same way that format-table -auto does but you would have to make sure that it does not affect data so that you could not capture it or send it down the pipe.
You are looking at creating custom output format files, like Frode F. talks about, then you would need to consider looking at about_Format.ps1xml but you would need to configure this for every object that you would want to display this way.
FileSystem.format.ps1xml, for example, would govern the output from Get-ChildItem. Format-Table is more dynamic and I don't think you can say just use Format-Table in that file.

Start script B with ALL variables from script A

I've written a powershell script that I run several times a day. It's getting to be somewhat of a chore to execute the script manually (from within Powergui or the shell), so I'd like to create a frontend which prompts me for the variables. I've found that Primalforms can supply me with pre-populated fields that can be adjusted if needed.
My problem is that I would like to create a gui and pass ALL the variables to my external script (this script is already written and will not be part of the Primalforms project).
How would I do this? Or should I pass the variables manually? How would I do that?
(I do not think this would be specific to Primalforms.. I'm rather executing a script with variables with another script as input.)
Any help would be greatly appreciated!
Use splatting. Collect all the values for the parameters in a hashtable (key names match parameter names) and assign each name the value of the parameter from the corresponding text feild in your form. Then pass the hashtable to script B. The following assumes that you have two text fields with names of: filter and path.
## scriptA ##
$params = #{
path=$path.text
filter=$filter.text
}
D:\Scripts\scriptB.ps1 #params