1

I want to run some commands to do Sysprep remotely through powershell.

So first I created a session using this:

$UserName = "IPAddress\username"
$Password = ConvertTo-SecureString "password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)
$s = New-PSSession -ComputerName IPAddress -Credential $psCred

Then assign the variables used in Sysprep:

$sysprep = 'C:\Windows\System32\Sysprep\Sysprep.exe'
$arg = '/generalize /oobe /shutdown /quiet'
$sysprep += " $arg"

And then finally run this:

Invoke-Command -Session $s -ScriptBlock {$sysprep}

When I run the last command, nothing happens actually.But in the script block, instead of $sysprep, if I give any other command like start/stop a service, it is giving some response. But SysPrep commands doesn't seem to work.Can anyone suggest what am I doing wrong.

CrazyCoder
  • 2,194
  • 10
  • 44
  • 91
  • If you use the SysPrep to generalize the VM, then the VM will shut down and can't be used. It becomes a generalized image. – Charles Xu Sep 03 '18 at 06:54
  • @CharlesXu-MSFT, yes. I need to generalize the Vm and create a Image of it. – CrazyCoder Sep 03 '18 at 07:00
  • I think you could use the vm extension to execute the SysPrep. And then follow this [link](https://learn.microsoft.com/en-us/azure/virtual-machines/windows/tutorial-custom-images#prepare-vm). – Charles Xu Sep 03 '18 at 07:09
  • @CharlesXu-MSFT , yes this is the link I'm following. but I want everything in scripts. – CrazyCoder Sep 03 '18 at 07:32

1 Answers1

1

You are trying to call for scriptblock object to run while $sysprep is a string. You would want to use Start-Process cmdlet for this. Like so:

$sysprep = 'C:\Windows\System32\Sysprep\Sysprep.exe'
$arg = '/generalize /oobe /shutdown /quiet'
Invoke-Command -Session $s -ScriptBlock {param($sysprep,$arg) Start-Process -FilePath $sysprep -ArgumentList $arg} -ArgumentList $sysprep,$arg
Kirill Pashkov
  • 3,118
  • 1
  • 15
  • 20
  • Thanks for the reply. But when I run this , it is giving the following error: "Cannot validate argument on parameter 'FilePath'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.". I have run just $sysprep , it is giving value. But somehow it is not able to take that value in the whole command. – CrazyCoder Sep 03 '18 at 06:59
  • My bad. I forgot to include param for scriptblock. I have update my answer. – Kirill Pashkov Sep 03 '18 at 07:04