PowerShell console output symbol + function parameter type specify + text content read

Source: Internet
Author: User
Tags file copy function definition

There is several ways:

Write-host:write directly to the console, not included in function/cmdlet output. Allows foreground and background colour to BES set.

Write-debug:write directly to the console, if $DebugPreference set to Continue or Stop.

Write-verbose:write directly to the console, if $VerbosePreference set to Continue or Stop.

The latter is intended for extra optional information, and write-debug for debugging (so would seem to fit in this case).

Additional:in PSH2 (at least) scripts using cmdlet binding would automatically get the-verbose and-debug switch paramete RS, locally enabling write-verbose and write-debug (i.e. overriding the preference variables) as compiled cmdlets and Prov Iders do.

Or, open the built-in application "Charactermap" on your system to select a symbol that you want to display on the console. The following example is the way to make the ToolTip information on the PowerShell console more bizarre:


function prompt
{

$specialChar 1 = [char]0x25ba

Write-host ' PS '-nonewline
Write-host $specialChar 1-foregroundcolor Green-nonewline
‘ ‘

$host. Ui. Rawui.windowtitle = Get-location
}

Http://www.pstips.net/using-symbols-in-console-output.html

Parameter 4 of the PowerShell handler function

Parameters for PowerShell handler functions425 March, 2012 in PowerShell tagged PowerShell tutorials/functions/Parametersby Mooser Lee This article index[Hide]
    • 1$args Universal Parameters
      • 1.1 when no parameter is called:
      • 1.2 A parameter call:
      • When more than 1.3 parameters are called:
      • 1.4 Setting parameter names
      • 1.5 Defining default values for parameters
    • 2 using strongly typed parameters
      • 2.1 Limit number Types
    • 3 Restricting date types
    • 4Switch parameters

The PowerShell function can accept parameters and process the parameters. The parameters of a function have 3 properties:

    1. Arbitrary arguments: The internal variable $args the parameter accepted when the function is called, $args is an array type.
    2. Named arguments: Each parameter of the function can be assigned a name that specifies the corresponding parameter by name when it is called.
    3. Predefined parameters: The function can specify a default value when defining a parameter, and the default value is maintained if the value of the parameter is not specifically specified when called.
$args Universal Parameters

The simplest thing to do with a function definition parameter is to use the built-in parameter of $args. It can identify any parameter. This is especially true for functions that are optional.

1234567891011 function sayHello{    if($args.Count -eq 0)    {        "No argument!"    }    else    {        $args foreach {"Hello,$($_)"}    }}
When no parameter is called:
12 PS C:Powershell> sayHelloNo argument!
A parameter call:
12 PS C:Powershell> sayHello LiLiHello,LiLi
When multiple parameters are called:
1234 PS C:Powershell> sayHello LiLi Lucy TomHello,LiLiHello,LucyHello,Tom

Because $arg is an array, you can use it to sum it up.

12345678 functionAdd{$sum=0$args foreach{$sum=$sum+$_}$sum}Add 10 7 3 100#120
Setting parameter names
123456789 functionStringContact($str1,$str2){    return $str1+$str2} StringContact moss flyStringContact -str1 word -str2pressmossflywordpress
Define default values for parameters
123456 functionstringContact($str1="moss",$str2="fly"){    return$str1+$str2}stringContact Good LuckstringContact
Using strongly typed parameters

The previous example found that passing the user's parameters to the function seemed confusing. The culprit is the PowerShell parameter interpreter, which can automatically process and assign parameters to functions.
The parameter interpreter for the function is arrogant, and it doesn't care about the information you provide. It only roughly splits the parameters and maximizes automatic type conversions. In fact, this type of conversion is often not perfect. Therefore, it is advisable to have strong typing restrictions on parameters in advance.

Limit number Types
12345 functionsubtract([int]$value1,[int]$value2){    return$value1-$value2}subtract moss fly

When the above function executes, an exception is thrown:
Subtract: Could not handle parameter conversion to parameter "value1". The value "Moss" cannot be converted to type ' System.Int32 '. Error: "The input string is not properly formatted. ”

Because the subtract parameter defines a strong type, the type of the parameter may cause the result of the function's processing. For example, call the above function
Subtract 8.1 7.9
Result is 0
But if you define the parameters of the above function as double type,

123456 functionsubtract([double]$value1,[double]$value2){    return$value1-$value2}subtract 8.1  7.9#输出 0.199999999999999
Restricting date types

The function's parameter interpreter automatically attempts to convert the string to a date type, or throws an exception if the conversion fails.

12345678 functionDayOfWeek([datetime]$date){    return$date.DayOfWeek}DayofWeek ‘1927-8-1‘#MondayDayofWeek 2008-8-1#Friday

DayOfWeek: Could not handle parameter conversion for parameter ' date '. The value "Someday" cannot be converted to type ' System.DateTime '. Error: "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0. ”
DayofWeek Someday

Switch parameter

The simplest parameter type of the PowerShell function is a Boolean type, and the Switch keyword can be used in addition to the bool type.
The following function reverses the string, but can be controlled by the $try parameter, if no value of $try is specified, the default value is $ false

123456789101112131415161718 functiontryReverse( [switch]$try [string]$source ){    [string]$target=""    if($try)    {        for[int]$i $source.length -1; $i -ge 0 ;$i--)        {            $target += $source[$i]        }        return $target    }    return $source}tryReverse -source www.mossfly.comtryReverse -try $true -source www.mossfly.com# www.mossfly.com# moc.ylfssom.www
This article link: http://www.pstips.net/powershell-passing-arguments-to-functions.html

It's also interesting to get the first n rows of a file. It can be done with a PowerShell. Examples are as follows:


Copy the code code as follows:


Get-content D:\1.txt-totalcount 100 | Set-content Top100.txt

Description: Here's set-content top100.txt is to put the result of a previous statement, write a new file--top100.txt

If this time, you want to get the 100th line of the file, you would not think to do a very complex loop? If so, that means you have a good programming literacy. But PowerShell told you not to be so troublesome. Examples are as follows:


Copy the code code as follows:

(get-content D:\1.txt-TotalCount 100) [-1]

Description: What! What did you see? If you simply look at () [-1], is that not like an array? 1 represents the last array element, which represents the last line of the first 100 rows, is that the 100th row?!

Finally, this command returns an array of objects that can be traversed with foreach-object (the alias is%). Very convenient, you should have seen the "sun" in front of the example!

-----------------------Note that reading only one line of text will take the row as a single string------------------

(PowerShell) file operations

(PowerShell) file operations

    • Get current PS1 file ' s parent path
$x = Split-path-parent $MyInvocation. mycommand.definition
    • Create a folder if it does not exist.
$myNewFolder = $x + "Mytestfolder\" if (! ( Test-path $myNewFolder)) {new-item-path $x-name mytestfolder-type Directory}
    • Open a XML file, and get what we want.
[string] $xmlDocPath = "F:/testdata/testxml.xml" [string] $nodeName = "Property" $xmlDoc = New-object " System.Xml.XmlDocument "$xmlDoc. Load ($xmlDocPath) $nodelist = $xmlDoc. getElementsByTagName ($nodeName); foreach ($  Node in $nodelist) {# Use Attributes would throw error. # $namestr = $node. Attributes[0]. INNERXML #Write-host "$namestr" $namestr = $node. GetAttribute ("Value") write-host "$namestr" $childnodes = $node.  ChildNodes; foreach ($childnode in $childnodes) {$textstr = $childnode. Innerxml.tostring () write-host "$textstr"}}

XML file

<?xml version= "1.0" encoding= "gb2312"? ><root><property Name = "First" value = "value" ><GUID> Xxoxx</guid><tel>123456</tel><start>5.95</start></property><property Name = "Second" ><guid>xxoxx</guid><tel>123456</tel><start>5.95</start>a </Property></Root>

    • Get special file from a directory, and copy them into local folder
$fileName = "test123" $fileList = Get-childitem-path $LogServer-filter "$fileName *" foreach ($file in $fileList) {Source = $ logserver+ $file copy-item $source $targetFolderWrite-host "$file". is copied. "}

Get all folder sizes under the specified folder

$rootDirectory = "D:\TFS"  $colItems = (Get-childitem $rootDirectory  | Where-object {$_. Psiscontainer-eq $True} | Sort-object) foreach ($i in $colItems)    {        $subFolderItems = (get-childitem $i. Fullname-recurse | Measure-object-property length-sum)        $i. FullName + "--" + "{0:n2}"-F ($subFolderItems. sum/1mb) + "MB"    

PowerShell console output symbol + function parameter type specify + text content read

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.