I have created a C# function to execute a PowerShell script to download and unzip a file from a remote computer. It runs successfully, but nothing is downloaded.
Below is my current code:
public static string RemotePSExecution(string ipAddress, string username, string password, string psFilePath)
{
string result = string.Empty;
var securePassword = new SecureString();
foreach (Char c in password)
{
securePassword.AppendChar(c);
}
PSCredential creds = new PSCredential(username, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ComputerName = ipAddress;
connectionInfo.Credential = creds;
String psProg = File.ReadAllText(psFilePath);
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
ps.AddScript(psProg);
StringBuilder sb = new StringBuilder();
try
{
var results = ps.Invoke();
foreach (var x in results)
{
sb.AppendLine(x.ToString());
}
result = sb.ToString().Trim();
}
catch (Exception e)
{
throw new Exception("Error occurred in PowerShell script", e.InnerException);
}
}
runspace.Close();
return result;
}
And my PowerShell script:
$url = "https://<internal website>/xp.zip"
$zipFile = "Downloads\xp.zip"
$targetDir = "Downloads\UnZipFiles\"
Invoke-WebRequest -Uri $url -OutFile $zipFile
Expand-Archive $zipFile -DestinationPath $targetDir -Force
If I run the PowerShell script directly on the remote VM, then the file is downloaded and unzipped successfully. But if I run the script using C# then nothing is downloaded.
Another thing, the C# function works for the below PowerShell script:
(Get-Service -DisplayName "*Service").Status
Does anyone know what's wrong with my code?
CodePudding user response:
Try specifying an absolute path instead of relative for zipfile and targetdir in the PS file. Your file probably gets downloaded in some temp or appdata folder.
CodePudding user response:
You are right. The file is downloaded and unzipped as expected after I specified an absolute path for zipfile and targetdir in the PS file. Thanks a lot, @Gaël James. I really appreciate your help.
Here is my updated PS file:
$url = "https://<internal website>/xp.zip"
$zipFile = "C:\Users\<current user>\Downloads\xp.zip"
$targetDir = "C:\Users\<current user>\Downloads\UnZipFiles\"
Invoke-WebRequest -Uri $url -OutFile $zipFile
Expand-Archive $zipFile -DestinationPath $targetDir -Force