Automation.runspaces 名前空間を使用すると、多くの問題が発生します。私は学生で、大学で働いています。私は大学のコンピューターと大学のドメインを使用しています。簡単に言えば、ランスペースの使用を放棄し、C# で powershell を開いてスクリプトを実行するだけです。それはうまくいかなかったので、いくつかのcmdスクリプトを書きました。動作する例を次に示します。
Powershell スクリプト:
Macアドレスに名前を変更
$OS = Get-WmiObject Win32_OperatingSystem
$NIC = Get-WmiObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq “TRUE”}
$PC = Get-WmiObject -class Win32_ComputerSystem
if($NIC.MacAddress -eq $null)
{
Write-Host "No Network Connection! The PC will not be renamed until the network is enabled"
}
else
{
$MacAddress = $NIC.MacAddress
$NewPCName = "PC-" + $MacAddress.Substring(0) -replace ':'
$PC.Rename($NewPCName)
Write-Host -ForegroundColor Green "New PC Name"
$NewPCName
}
write-Host "The PC has been renamed and will restart in 5 seconds."
start-sleep -s 5
restart-computer
上記のスクリプトをpowershellで実行すると機能します。Process.Start(powershell.exe, "C:\myscript"); を使用する場合 c# では実行されません。実行ポリシーを設定しても役に立ちません。したがって、次のようにcmdスクリプトを使用します。
cmd スクリプト:
powershell -noexit -executionpolicy unrestricted "C:\myscript.ps1"
そして実行します。
今、私は次のものを持っています:
Powershell スクリプト:
Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -name AutoAdminLogon -value 0 write-host "Changing Registry" Start-Sleep -s 10
cmd スクリプト:
powershell -noexit -executionpolicy unrestricted "C:\Windows\ITS\ChangeRegistry.ps1"
私のWindowsフォームプログラムでは、cmdスクリプトを呼び出すボタンクリックイベントがあります。動作しているように見え、何もクラッシュせず、cmd は正常に実行され、ホストへの書き込みが行われ、10 秒間スリープします。ただし、レジストリ キーは変更されません。しかし、PowerShell の名前変更スクリプトと cmd の最初の例は、Windows フォームのボタンをクリックするだけで完全に機能します。だから私はそれを理解していません。