简体   繁体   中英

How to get Text file values into an Invoke-VMScript command?

I am trying to create OU's within an newly created DC using Invoke-VMScript but I cannot get the OU values from a text file to push through to the VM. I also am not sure where to perform the breaks in the multiline script so it passes through to the VM correctly.

Sample of OU File:

Adm_Apps
Adm_Apps/Groups
Adm_Apps/Users
Adm_Apps/Users/Human Users
Adm_Apps/Users/Human Users/Internal
Adm_Apps/Users/Human Users/External
Adm_Apps/Users/Non-Human Users
Adm_Apps/Users/Non-Human Users/Internal
Adm_Apps/Users/Non-Human Users/External

Than the Script I am using:

$OUStructure = Get-Content "C:\Users\admr_mornevr\Documents\PowerShell\OdekSpace\Active Directory\OUs\OdekOUStructure.txt"

$CreateOUs = "`$MyDomain = Get-ADDomain | Select DistinguishedName;
`$connectionString = 'LDAP://' + `$MyDomain.DistinguishedName;
`$objDomain  = [ADSI]`$connectionString;

$OUStructure | Foreach-Object {
  `$domain = `$MyDomain.DistinguishedName
  `$newOU = ''
  `$ous = (Split-Path `$_ -Parent).Split('\')
  [array]::Reverse(`$ous)
  `$ous | Foreach-Object {
    if (`$_.Length -eq 0) {
      return
    }
    `$newOU = `$newOU + ',OU=' + `$_
  }
  `$nyOUNavn = Split-Path `$_ -Leaf
  `$newOU = 'OU=' + `$nyOUNavn + `$newOU

  `$objOU = `$objDomain.Create('OrganizationalUnit', `$newOU)
  `$objOU.SetInfo()
}"
Invoke-VMScript -ScriptType PowerShell -ScriptText $CreateOUs -VM $DCName -GuestCredentials $DomainCredential

I have modified the above code as follows:

$OUs = Import-Csv 'Path to CSV File'

$CreateOUs = "foreach ($OU in $OUs)
{
`$Name = `$(`$OU.Name)
`$Path = `$(`$OU.Path)
New-ADOrganizationalUnit -Name `$Name -Path `$Path
}"
Invoke-VMScript -ScriptType PowerShell -ScriptText $CreateOUs -VM $DCName -GuestCredentials $DomainCredential

So thanks to @Theo for pointing me in the right direction as well as LucD over on VMware Communities. The below code is what worked for me.

$OUs = Import-Csv 'C:\PathtoFile.csv' 

$CreateOUs = @'
New-ADOrganizationalUnit -Name $($Name) -Path $($Path)
'@

foreach ($OU in $OUs)
{
$Name = $($OU.Name)
$Path = $($OU.Path)
$ExecuteCmd = $ExecutionContext.InvokeCommand.ExpandString($CreateOUs) 
Invoke-VMScript -ScriptType Powershell -ScriptText $ExecuteCmd -VM $DCName -GuestCredential $DomainCredential
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM