PowerShell tips for using the-F method to bring data into the _powershell

Source: Internet
Author: User

Strings enclosed in double quotes can use variables directly, which is a common technique, such as code:

$name = $host. The Name 
"Your host is called $name."

But there are limits to this technique. If you want to display the object's properties instead of the variable itself, for example, this will fail:

Ps> "Your host is called $host. Name. "
Your host is called System.Management.Automation.Internal.Host.InternalHost.Name.

This is because PS only solves the variable itself (such as $host) and does not support its properties.

At the same time you can't control the format of numbers, execute the following code, and the results appear to have a number of digits:

# Get available spaces in bytes for c:drive 
$freeSpace = ([WMI] ' win32_logicaldisk.deviceid= ' C: '). FreeSpace 
 
# Convert to MB 
$freeSpaceMB = $freeSpace/1mb 
 
# output 
"Your c:drive has $freeSpaceMB MB SPAC E available. "

Here is a-F method to solve these problems at the same time. Just place it on the left side of the template text, and its value will be brought in correctly:

# Insert any data into the text template 
' Your host is called {0}. '-f $host. Name 
 
# Calculate free spaces on c:in MB 
$freeSpace = ([WMI] ' win32_logicaldisk.deviceid= ' C: '). FreeSpace 
$freeSpaceMB = $freeSpace/1mb 

# Output with just one digit after the comma 
' Your c:drive has {0:n1 MB space available. ' F $freeSpaceMB

Now, you see, using-F gives you two advantages: the bracketed placeholder indicates the starting position of the entry parameter, and it also accepts formatting. "N1" represents the retention of 1 decimal places. Can change it to meet your needs.

Supports all PS versions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.