今天我们来看看PowerShell中的$OFS变量。说起$OFS,我们首先要知道的是在一门语言中都会有一些自动变量,这在PowerShell中自然也一样,在PowerShell中包含了许多自动变量,我们可以通过使用Get-Variable cmdlet来查看当前PowerShell中的自变量,如下:
PS C:\Users\Administrator> Get-Variable
Name Value
---- -----
$ gv
? True
^ gv
a a
args {}
b 6/11/2016 7:50:07 AM
ConfirmPreference High
ConsoleFileName
DebugPreference SilentlyContinue
Error {This command cannot find a matching alias because an alias with the name 'get-proces...
ErrorActionPreference Continue
ErrorView NormalView
ExecutionContext System.Management.Automation.EngineIntrinsics
false False
FormatEnumerationLimit 4
HOME C:\Users\Administrator
Host System.Management.Automation.Internal.Host.InternalHost
InformationPreference Continue
input System.Collections.ArrayList+ArrayListEnumeratorSimple
LASTEXITCODE 0
MaximumAliasCount 4096
MaximumDriveCount 4096
MaximumErrorCount 256
MaximumFunctionCount 4096
MaximumHistoryCount 4096
MaximumVariableCount 4096
MyInvocation System.Management.Automation.InvocationInfo
NestedPromptLevel 0
null
OFS +
OutputEncoding System.Text.ASCIIEncoding
PID 3304
PROFILE C:\Users\Administrator\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
ProgressPreference Continue
PSBoundParameters {}
PSCommandPath
PSCulture en-US
PSDefaultParameterValues {}
PSEmailServer
PSHOME C:\Windows\System32\WindowsPowerShell\v1.0
PSScriptRoot
PSSessionApplicationName wsman
PSSessionConfigurationName http://schemas.microsoft.com/powershell/Microsoft.PowerShell
PSSessionOption System.Management.Automation.Remoting.PSSessionOption
PSUICulture en-US
PSVersionTable {PSVersion, WSManStackVersion, SerializationVersion, CLRVersion...}
PWD C:\Users\Administrator
ShellId Microsoft.PowerShell
StackTrace at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandN...
true True
VerbosePreference SilentlyContinue
WarningPreference Continue
WhatIfPreference False
如你所看到的,PowerShell中的自变量非常的多,这里我们就不一一说明它们的作用了,今天我们主要想看的是$OFS这个变量的作用。
首先要说明的是$OFS是一个存储了一个字符串的特殊的变量,你可以用$OFS来作为字段的分隔符来输出,也就是说当你把一个数组转化成字符串的时候可以用这个变量来做分割输出。一般在默认情况下$OFS变量不包含任何值,你可以通过传统赋值的方式给$OFS赋值,那么接下来我们来看看怎么操作$OFS:
首先我们定义了一个str字符串数组,它包含1,2,3,4,5,6 一共六个元素。
PS C:\Users\Administrator> $str = 1,2,3,4,5,6
PS C:\Users\Administrator> $str
1
2
3
4
5
6
接着我们直接给$OFS赋值,这里我们紧接着用分号分隔,继续把我们之前定义的str变量强制申明为string类型,这个时候你就会发现每一个元素被我们所定义的分隔符所插入,并紧挨着元素分开了。
PS C:\Users\Administrator> $OFS = ">>";[string]$str
1>>2>>3>>4>>5>>6
</pre><p></p><p>当然我们也可以分开写,只要定义好了$OFS变量值后,你接下来的操作都会影响每一个字符串数组元素,而这些元素间隔都会被插入$OFS变量的值。</p><p><pre name="code" class="plain">PS C:\Users\Administrator> $OFS = "+"
PS C:\Users\Administrator> [String]$str
1+2+3+4+5+6