im trying to save the output from a command to a variable,
but i just cant get it to work.
It should look something like this :
$test = (Get-SmbShare | Select Name,CurrentUsers,CurrentUserLimit | fl)
Write-Host $test
Output: The Output of Get-SmbShare
I was looking through the comments and I saw you said that you want to store it in a text file.
#Lee_Dailey Thats what i want to do, the output is gonna go into a text file. – Jan
So if you want to skip the variable part and just send it straight to a text file, you could use:
Get-SmbShare | Select Name, CurrentUsers, CurrentUserLimit | fl | Out-File -filepath "C:\Temp\file.txt"
Related
This will be easy for most of you answer, but I'm struggling with it.
For instance, if I input Get-Tpm, the return I get is,
Get-tpm written to console, as shown below.
If I enter
ECHO Get-tpm > C:\dssupport\output.txt
the output is a text file containing 'Get-tpm:'
Is there a way to do both, so that I can see it on my monitor,
and also saved as a text file?
I'm grateful for any help at all.
Thank you
Most PowerShell cmdlets like Get-Tpm output objects which usually display on the console screen formatted as table or as list.
You can easily write output like that to a file, usually a structured Csv file you can open in Excel using Export-Csv.
That last cmdlet however does not have something neat like a parameter called -PassThru, but what you can do is use a cmdlet that does let you do that.
In your example, you could do
# show on screen AND write to CSV file
Get-Tpm | ConvertTo-Csv -NoTypeInformation | Set-Content -Path 'X:\TPM.csv' -PassThru
or
# show on screen AND write to JSON file
Get-Tpm | ConvertTo-Json | Set-Content -Path 'X:\TPM.json' -PassThru
or even
# show on screen as list AND write to text file
Get-Tpm | Format-List | Out-String | Set-Content -Path 'X:\TPM.txt' -PassThru
Although a file written like that is not really meant to be used for anything other than display purposes.
Or you can do this in separate lines of code where you show on screen as list for instance and in the other line write the csv file.
For that, you need to capture the results from the cmdlet in a variable:
$result = Get-Tpm
# show on screen as list (or table)
$result | Format-List # or do Format-Table -AutoSize
# show in a separate grid view window
$result | Out-GridView -Title "My TPM results"
# output to CSV file
$result | Export-Csv -Path 'X:\TPM.csv' -NoTypeInformation
I recently started using Powershell and I'm trying out some code.
I have a .cfg file with several rules of code. The code is written like this:
ad.name=1
ad.virtual=active
ad.set=none
ad.partition=78
Now I want to export the value of ad.partition, which is 78, to a new file. I don't want to export ad.partition or = but only the number 78.
So far I got this:
Get-Content -Path C:\file.cfg | Where-Object {$_ -like 'ad.partition=78'}
But then I -obviously- just get the variable and the value. Not sure how to continue...
I hope someone has a way of achieving what I want.
After saving the value in a new file, would it be possible to add spaces? For example, the value consists out of 9 digits, e.g. 123456789. The desired output result would be 123 456 789.
Use ConvertFrom-StringData cmdlet to create a hash table from your file, then simply index the key you are after:
$h=(Get-Content -Path C:\file.cfg | ConvertFrom-StringData)
$h.("ad.partition") -replace ('^(\d{1,3})(\d{1,3})?(\d{1,3})?','$1 $2 $3') > C:\out.cfg
You can use the Select-String cmdlet to capture your desired value using a regex. Then just pipe the result to the Out-File cmdlet. To get your desired output with spaces, you can use a simple format string:
"{0:### ### ###}" -f [int](Select-string 'ad\.partition=(.*)' -Path C:\file.cfg).Matches.Groups[1].Value |
Out-File C:\result.cfg
Hi I use the PowerShell command Get-AzureRmLocation to list the available locations from azure. I want to display them neatly in a table or some well formatted manner instead of listing them line by line.
I tried
$locations = #(Get-AzureRmLocation | Select-Object -ExpandProperty DisplayName)
Write-Host -ForegroundColor Yellow "Available Locations :"
$locations | Format-Table
But that also listing everything which makes the screen look long and not so good. is there a way?
I am getting the output as a list like this https://imgur.com/a/MjstD
I want it to be a two table column with all available locations something like that.
Thanks.
Is this what you want?
$locations = Get-AzureRmLocation
$locations | Format-Table #{n="Available Locations";e={$_.DisplayName}}
Maybe you could try to following example:
$locations = Get-AzureRmLocation
$locations | Format-Table -Property Location,DisplayName
I test in my lab, I get like below:
To list all Azure locations I would suggest using the Get-AzLocation
Get-AzLocation | Format-Table -Property Location, DisplayName
Result:
PowerShell version:
I have the following line of code:
Get-Item \\MachineNAME\c$\Windows\System32\GroupPolicy\Machine\Registry.pol |
Foreach {$_.LastWriteTime}
This returns the last modified date of a given machine successfully. Using Out-File I can write the single result to a text file.
What I would really like to do it read in a list of machine names I have and output all the results to a text file. This would show a list of machines and the last modified date next to it.
assuming you have one machine per line in c:\temp\computers.txt, something like this could do the trick
get-content c:\temp\computers.txt | %{
$lwt= ls \\$_\c$\Windows\System32\GroupPolicy\Machine\Registry.pol | select -expand lastWriteTime
echo "$_ : $lwt" >> c:\temp\results.txt
}
I'm trying to do some processing logic - running some commands in parallel based on the tree configuration CSV file:
Operation;Parent;Enabled;Propagated;Job_ID;Status;Started;Finished
CA1;n/a;Y;N;;;;
PROD1;n/a;Y;N;;;Y;
CON1;CA1;N;N;;;Y;
CON2;CON1;N;N;;;Y;
I load the file into the variable and then I'm trying to find the next step which needs to be processed:
$Data = Import-Csv -delimiter ";" .\config.csv
$NextStep = $Data | Select-Object -first 1 | Where-Object {$_.Started -eq ""}
$NextStepText = $NextStep.Operation | ft -autosize | out-string
The problem is that it seems like $NextStep.Operation contains new line character. When I display it I get:
PS C:\temp\SalesForce> $NextStep.operation
CA1
PS C:\temp\SalesForce> $NextStep.Operation.Contains("`n")
False
Do you know what I'm doing wrong? I would like to display the content without the "dummy" new line character which is there even if contains method is saying it is not there.
Or please advise how to do it better. I'm still learning PowerShell; so far I just google the commands, and I'm trying to put it together.
The newline isn't in your data, it's being added by Out-String. Observe the output of the following (in particular, where you do and don't get the newline after CA1):
$Data = import-csv -delimiter ";" .\config.csv
$NextStep = $Data | select-object -first 1 | where-object {$_.Started -eq ""}
$NextStepText = $NextStep.Operation | ft -autosize | out-string
"hi"
$NextStepText
"hi"
$NextStep.Operation;
"hi"
$NextStep.Operation | ft -autosize
"hi"
You shouldn't be using Format-Table at that step (and Out-String is unnecessary in this script) if you intend to use $NextStepText for anything other than direct output later on. Consider Format-Table (or any of the Format-* cmdlets) the end of the line for usable data.
Why do you think that there is a new line character of some sort in there? If you are using the ISE then what you posted doesn't look like there is. It is normal to have a blank line between commands (in the v2/v3 ISE, not sure about v4), so what you posted would not indicate that it contains any new line characters.
You can always check the $NextStep.Operation.Length to see if it says 3 or 4. If there is a `n in there it'll show up in the length. For example (copied and pasted out of my v3 PS ISE):
PS C:\> $test = "Test`nTest2"
PS C:\> $test
Test
Test2
PS C:\> $test.Length
10
PS C:\>
That was to show that there is a new line character injected by following it with text, without any text following the new line character it looks like this:
PS C:\> $test = "Test`n"
PS C:\> $test
Test
PS C:\> $test.Length
5
PS C:\>
You'll notice that there are 2 blank lines after the text "Test" on the second command. The first is the line injected into the variable, and the second is the obligatory line that PS puts in to show separation between commands.
Out-String unexpectedly appends a trailing newline to the string it outputs.
This problematic behavior is discussed in GitHub issue #14444.
A simple demonstration:
# -> '42<newline>'
(42 | Out-String) -replace '\r?\n', '<newline>'
However, you neither need Format-Table nor Out-String in your code:
Format-* cmdlets output objects whose sole purpose is to provide formatting instructions to PowerShell's for-display output-formatting system. In short: only ever use Format-* cmdlets to format data for display, never for subsequent programmatic processing - see this answer for more information.
Out-String is capable of interpreting these formatting instructions, i.e. it does produce data - in the form of a single, multi-line string by default - that is the string representation of what would print to the display.
As such, the resulting string contains a representation for the human observer, not a structured text format suitable for programmatic processing.
In your case, Format-Table is applied to a string, which is pointless, because strings always render as themselves, in full (-AutoSize has no effect); piping to Out-String then in effect returns the original string with an (undesired) newline appended.
Therefore, use a simple variable assignment to store the property value of interest in a separate variable:
$NextStepText = $NextStep.Operation