Question

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 
}

I wrote this function to get some details about specific disks. However, I have to run them remotely and in a multi-domain environment. We have different usernames for computers in different OU's. I wanted the script to be able to take the username from the computername itself. The usernames are in this format ---- "name"+ "first 3 letters of the computername" which is the OU name. I am able to get the -Join method to work normally. However, it doesn't work if the variable is a parameter in a function. Here the username shows up as "ayan--join xeuts001[1..3]" when I want it to show up as "ayan-xeu"

Was it helpful?

Solution

What you have there is just a string that happens to contain a variable (which is expanded). Inside a string you are not in expression mode, so you cannot use operators. They just get embedded string content like you see there. What you want is probably:

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

But that isn't correct, as it will yield oob for a computer name Foobar. If you want the first three letters, you'd need

$a = -join $Computername[0..2]

or even simpler (and easier to read, and faster):

$a = $Computername.Substring(0, 3)

P.S.: I also took the liberty of reformatting your original code, it was a horrible mess to read.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top