Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Powershell字符串拆分离散_String_Powershell_Split_Powershell 2.0 - Fatal编程技术网

String Powershell字符串拆分离散

String Powershell字符串拆分离散,string,powershell,split,powershell-2.0,String,Powershell,Split,Powershell 2.0,我试图通过调用$varname.split(“,”)在PowerShell中拆分字符串。当我在PowerShell控制台中时,这可以正常工作,但当我直接调用脚本时则不行 从命令提示符:powershell。\scriptname.ps1 Method invocation failed because [System.Object[]] doesn't contain a method named 'split'. At C:\scriptname.ps1:92 char:30 +

我试图通过调用$varname.split(“,”)在PowerShell中拆分字符串。当我在PowerShell控制台中时,这可以正常工作,但当我直接调用脚本时则不行

从命令提示符:
powershell。\scriptname.ps1

Method invocation failed because [System.Object[]] doesn't contain a method named 'split'.
At C:\scriptname.ps1:92 char:30
+         reboot $varname.split <<<< (',')
    + CategoryInfo          : InvalidOperation: (split:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
Powershell提示符:

PS C:\> .\test.ps1 asdf fdsa
asdf
System.String
fdsa
System.String

PS C:\> .\test.ps1 "asdf,fdas"
asdf,fdas
System.String

PS C:\> .\test.ps1 "asdf","fdas"
asdf fdas
System.Object[]

PS C:\> .\test.ps1 asdf,fdas
asdf fdas
System.Object[]
命令提示:

C:\>powershell .\test.ps1 asdf fdsa
asdf
System.String
fdsa
System.String

C:\>powershell .\test.ps1 "asdf,fdas"
asdf fdas
System.Object[]

C:\>powershell .\test.ps1 "asdf","asdfa"
asdf asdfa
System.Object[]

C:\>powershell .\test.ps1 asdf,fdas
asdf fdas
System.Object[]

注意它处理带引号字符串的方式(test#2)之间的差异。为什么会这样?有什么办法可以解决这个问题吗?

无论出于什么原因,$varname在脚本中运行时包含一个数组。而且数组上没有拆分方法。能否显示确定分配给$varname的值的脚本?顺便说一句,如果数组包含要拆分的字符串,请尝试此
$varname[0]。拆分(“,”)

通过验证指定的参数是否为字符串,我可以解决问题。如果它已经是一个数组,那么它只是传递给函数。这是这样检查的:

if($servers -is [system.string]){
        $servers = $servers.split(',')
}

我已经添加了脚本和测试用例。思想?
C:\>powershell .\test.ps1 asdf fdsa
asdf
System.String
fdsa
System.String

C:\>powershell .\test.ps1 "asdf,fdas"
asdf fdas
System.Object[]

C:\>powershell .\test.ps1 "asdf","asdfa"
asdf asdfa
System.Object[]

C:\>powershell .\test.ps1 asdf,fdas
asdf fdas
System.Object[]
if($servers -is [system.string]){
        $servers = $servers.split(',')
}