Hello Anant
The issue is that the PowerShell script is trying to execute dsregcmd as a PowerShell command, which is not correct. dsregcmd is a standalone executable, not a PowerShell command.
To fix this, you can try the following:
- Use the
Start-Processcmdlet to rundsregcmdas a separate process:
$process = Start-Process -FilePath "$env:SystemRoot\System32\dsregcmd.exe" -ArgumentList @("/status") -Wait
$statusOutput = $process.StandardOutput.ReadToEnd()
This will execute dsregcmd and capture its output as a string.
- Use the
&operator to rundsregcmdas a command, but specify the full path to the executable:
$statusOutput = & "$env:SystemRoot\System32\dsregcmd.exe" /status
This should work as long as the dsregcmd executable is in the system32 directory.
As for alternatives to using dsregcmd, you can try using the Get-ADComputer cmdlet from the Active Directory PowerShell module to check the Azure AD join status:
import-module -name activedirectory
$computer = Get-ADComputer -Identity $env:COMPUTERNAME
if ($computer.AzuresDeviceJoined) {
# Run dsregcmd /leave to leave Azure AD
& "$env:SystemRoot\System32\dsregcmd.exe" /leave
}
This will require installing the Active Directory PowerShell module on your target machines.
As for running dsregcmd from PowerShell, you can try using the following commands:
& "$env:SystemRoot\System32\dsregcmd.exe" /status
& "$env:SystemRoot\System32\dsregcmd.exe" /leave
These commands should work as long as the dsregcmd executable is in the system32 directory.
I hope this helps! Let me know if you have any further questions.