how to use powershell object properties directly without typecasting and spliting?
I have created a small script to transfer value of Active directory pc attribute called pssfulllocation from one pc to anoter pc..
To achieve this I have to use typecasting + splitting..
Here is the script which works
$oldpc=read-host "Enter old pc name"
$newpc=read-host "Enter new pc name"
$my=Get-ADComputer -Identity $oldpc -Properties * | select pssfulllocation
$itemcast=[string]$my
$b = $itemcast.Split("=")[1]
$c=$b.Split("}")[0]
Set-ADComputer -identity $newpc -Replace @{pSSFullLocation="$c"}
and the output will nicely do the intended job.. in this manner.. and this is the desired result..
But if i don't use typecasting + splitting as per the below script--
$oldpc=read-host "Enter old pc name"
$newpc=read-host "Enter new pc name"
$my=Get-ADComputer -Identity $oldpc -Properties * | select pssfulllocation
Set-ADComputer -identity $newpc -Replace @{pSSFullLocation="$my"}
the out put is below.. which is not what i want..
In a nutshell if i don't use typecasting + splitting output will be added as @{pSSFullLocation=C/BRU/B/0/ADM/1 but it should only be added as C/BRU/B/0/ADM/1 as per this:
I feel typecasting + splitting should be a workaround and not the proper method.. Any other powershell way to achieve this without using typecasting + splitting ?
Don't do this:
$my=Get-ADComputer -Identity $oldpc -Properties * | select pssfulllocation
You don't Select-Object
to access an attribute's value. Note the -Object
, not -Attribute
, in the cmdlet name. Instead, collect the object returned by Get-AdComputer
then use the attribute directly.
$my = Get-ADComputer -Identity $oldpc -Properties *
$psfl = $my.pSSFullLocation
Set-ADComputer -identity $newpc -Replace @{pSSFullLocation="$psfl"}
Or even this could do the job "-expandproperty"
$oldpc=read-host "Enter old pc name"
$newpc=read-host "Enter new pc name"
$my=Get-ADComputer -Identity $oldpc -Properties * | select -expandproperty pssfulllocation
Set-ADComputer -identity $newpc -Replace @{pSSFullLocation="$my"}