Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.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
Powershell -参数的变量上的联接运算符_Powershell_Powershell 3.0_Powershell Remoting - Fatal编程技术网

Powershell -参数的变量上的联接运算符

Powershell -参数的变量上的联接运算符,powershell,powershell-3.0,powershell-remoting,Powershell,Powershell 3.0,Powershell Remoting,我编写此函数是为了获得有关特定磁盘的一些详细信息。但是,我必须在多域环境中远程运行它们。我们在不同的OU中有不同的计算机用户名。我希望脚本能够从computername本身获取用户名。用户名的格式为“名称”+“计算机名”的前3个字母,这是OU名称。我能够使-Join方法正常工作。但是,如果变量是函数中的参数,则它不起作用。这里,当我希望用户名显示为“ayan-join xeuts001[1..3]”时,用户名显示为“ayan xeu”您所拥有的只是一个包含变量的字符串(已展开)。在字符串中,您不

我编写此函数是为了获得有关特定磁盘的一些详细信息。但是,我必须在多域环境中远程运行它们。我们在不同的OU中有不同的计算机用户名。我希望脚本能够从computername本身获取用户名。用户名的格式为“名称”+“计算机名”的前3个字母,这是OU名称。我能够使
-Join
方法正常工作。但是,如果变量是函数中的参数,则它不起作用。这里,当我希望用户名显示为
“ayan-join xeuts001[1..3]”时,用户名显示为
“ayan xeu”
您所拥有的只是一个包含变量的字符串(已展开)。在字符串中,您不处于表达式模式,因此不能使用运算符。它们只是像你看到的那样嵌入字符串内容。你想要的可能是:

function Get-Diskinfo {
    param(
        [string[]] $Computername = 'XEUTS001',
        [string[]] $drive = 'c:'
    )

    $a = "-join $Computername[1..3]" 

    Get-WmiObject Win32_LogicalDisk `
            -Filter "DeviceID = '$drive'" `
            -ComputerName $Computername `
            -Credential (Get-Credential -Credential ayan-$a) |
        Select-Object `
            @{n='Size'; e={$_.size / 1gb -as [int]}},
            @{n='free';e={$_.freespace / 1gb -as [int]}},
            @{n='% free';e={$_.freespace / $_.size *100 -as [int]}} |
        Format-Table -AutoSize 
}
但这是不对的,因为它将为计算机名
Foobar
生成
oob
。如果你想要前三个字母,你需要

$a = -join $Computername[1..3]
或者更简单(更容易阅读,更快):


附言:我还冒昧地重新格式化了你的原始代码,读起来真是一团糟。

谢谢你的格式化,@Joey。子字符串选项优于“-join”。在“$a | gm”中查找方法列表时,我没有找到它,但是“$a=-join$Computername[1..3]”如果在脚本之外进行测试,则会产生预期的输出。我只是无法让它在脚本中工作。。。。。再次感谢..另外,“-Credential(Get Credential-Credential ayan-$a)”…可以工作,但是“-Credential(Get Credential-Credential ayan-$Computername.Substring(0,3))”…不
Get Credential ayan-$($Computername.Substring(0,3))
可以工作。请记住,cmdlet的参数在涉及变量和内容时基本上与双引号字符串相同(不完全相同,因为可以使用括号触发模式重新求值,但足够接近)。
$a = -join $Computername[0..2]
$a = $Computername.Substring(0, 3)