2017-08-27 70 views
1

我是PowerShell和腳本編程的新手,遇到了一個奇怪的情況。嘗試刪除遠程虛擬服務時發生異常

我想創建一個腳本,將刪除正在運行的服務並安裝新的服務(也複製文件等)。

問題是當我運行命令與命令工作的腳本分開運行時,刪除服務的命令。 當我運行我的命令作爲腳本的一部分,我得到一個異常:

:異常調用「刪除」和「0」的說法(S):「遠程 過程調用失敗,沒有執行(從HRESULT異常: 0x800706BF)」

這是我單獨運行:

Connect-VIServer -Server "IP" -Protocol https -User "User" -Password "Password" 


$password = "Password" | ConvertTo-SecureString -asPlainText -Force 
$username = "User" 
$credential = New-Object System.Management.Automation.PSCredential($username,$password) 


(gwmi win32_service -ComputerName "IP" -Credential $credential -filter "name='Service Name'").delete() 

腳本時失敗我運行:

Connect-VIServer -Server IP -Protocol https -User "User" -Password "Password" 

$Template = Get-Template -Name "Template Name" 

Set-Template $Template -ToVM 

$VM = Get-VM -Name "Template Name" 

Start-VM $VM 

Start-Sleep -s 100 


#Creating PScredentials 
$password = "Password" | ConvertTo-SecureString -asPlainText -Force 
$username = "User" 
$credential = New-Object System.Management.Automation.PSCredential($username,$password) 

#Creating a New folder on vm 
$Create_New_Folder = 
{ 
New-Item -Path "Host Path" -ItemType directory 
} 
Invoke-Command -ComputerName "PC IP" -Credential $credential -ScriptBlock $Create_New_Folder 

#Copy File From Localhost To vm 
Get-Item "Host Folder" | Copy-VMGuestFile -Destination "VM LOcal Path" -VM "Template Name" -LocalToGuest -GuestUser "User" -GuestPassword "Password" -Force -Verbose 


#Deleting a service on remote vm 
(gwmi win32_service -ComputerName "IP" -Credential $credential -filter "name='Service Name'").delete() 

#Retart VM so the service will be removed 
Restart-VM "Template Name" -Confirm:$false 
+0

ComputerName「PC IP」和ComputerName「IP」之間有區別嗎? – Nikolaus

+0

這些只是我更改的名稱,以便上傳到這裏...在腳本中它的相同的IP。 – Udi

+0

您是否試圖將其與創建新文件夾一樣放入腳本塊? – Nikolaus

回答

0

不知道gwmi如何執行遠程處理。如果它使用DCOM或其他的東西,你可能需要額外的權限。您可以嘗試使用Invoke-Command刪除服務( - >您已經使用它來創建新文件夾)。例如:

Invoke-Command -ComputerName "PC IP" -Credential $credential -ScriptBlock { 
     (gwmi win32_service -filter "name='Service Name'").delete() 
    } 

使用Invoke-Command您使用的是更加「標準化」遠程處理機制。

希望有所幫助。

+0

是的,正如尼古拉斯和你所建議的一樣。它的作品謝謝:) – Udi

相關問題