2016-09-22 65 views
0

我正在嘗試使用powershell調用遠程批處理腳本。使用特定憑證調用遠程命令/腳本

下面是一些示例代碼:

Invoke-Command -ComputerName 127.0.0.1 {C:\myfile.bat} 

myfile.bat包含此:

echo %USERNAME% 
copy \\10.10.10.10\sample c:\toMe 

當我在cmd窗口本地調用myFile.bat,一切都很好。我的用戶名是預期的。然而,當我使用PowerShell中運行調用命令,它給了我這個錯誤,而用戶名仍然是正確的:

Access is denied. 

這裏是我到目前爲止已經試過。

$password = ConvertTo-SecureString "MyPassword" -AsPlainText -Force 
$username = "Domain\Username" 
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password 
Invoke-Command -ComputerName 127.0.0.1 {myfile.bat} -credential $cred 

但是,雖然這相當於相同的用戶名,它仍然給我同樣的錯誤。

然後我試圖創建一個PSDrive來,並執行命令,以及:

New-PSDrive -Name X -PSProvider FileSystem -Root \\10.10.10.10\sample 
Invoke-Command -ComputerName 127.0.0.1 {myfile.bat} 
Remove-PSDrive X 

但我也得到了同樣的錯誤。我現在完全難住了。在不更改批處理腳本的情況下,我可以在PowerShell中執行哪些操作以滿足此要求?

回答

0

這個工作適合你嗎?

$password='[email protected]'|convertto-securestring -asplaintext -force; 
$cred=new-object -typename system.management.automation.pscredential('Domain\Username',$password); 
Invoke-Command -computer 127.0.0.1 {c:\myfile.bat} -credential $cred; 

$password='[email protected]'|convertto-securestring -asplaintext -force; 
$cred=new-object -typename system.management.automation.pscredential('Domain\Username',$password); 
$s = New-PSSession -computer "127.0.0.1" -credential $cred; 
Invoke-Command -Session $s -ScriptBlock { cmd /c "c:\myfile.bat" }; 
Remove-PSSession $s; 

也,你可以測試改變domain\usernameusername