Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

How to run a multiline Powershell script inside of c#?

I'd like to run this Powershell script inside of c# using the format below. Do I use -scriptblock or powershell.addscript("") or ? It seems like I'm making this harder than it should be.

Is there a preferred or standardized way to run larger precanned scripts inside of c#?

        PowerShell powershell = PowerShell.Create(RunspaceMode.NewRunspace);
        PSCommand command = new PSCommand();
        Collection<PSObject> psSessions = null;

        command.AddCommand("Get-PSSession");
        command.AddCommand("Remove-PSSession");

        powershell.Commands = command;
        psSessions = powershell.Invoke();

        command = new PSCommand();

        command.AddCommand("New-PSSession");
        command.AddParameter("AllowRedirection", true);
        command.AddParameter("Authentication", "Kerberos");
        command.AddParameter("ConfigurationName", "Microsoft.Exchange");
        command.AddParameter("ConnectionUri", pconnectionURI);
        command.AddParameter("Credential", Credential);

        powershell.Commands = command;
        psSessions = powershell.Invoke();

This is the multi line Powershell script below

try{
Get-Process -ProcessName Teams | Stop-Process -Force
Start-Sleep -Seconds 3
Write-Host "Teams Process Sucessfully Stopped" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Clearing Teams Disk Cache" -ForegroundColor Yellow
try{
Get-ChildItem -Path $env:APPDATA"Microsofteamsapplication cachecache" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA"Microsofteamslob_storage" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA"Microsofteamsdatabases" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA"Microsofteamscache" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA"Microsofteamsgpucache" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA"MicrosofteamsIndexeddb" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA"MicrosofteamsLocal Storage" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:APPDATA"Microsofteamsmp" | Remove-Item -Confirm:$false
Write-Host "Teams Disk Cache Cleaned" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Stopping Chrome Process" -ForegroundColor Yellow
try{
Get-Process -ProcessName Chrome| Stop-Process -Force
Start-Sleep -Seconds 3
Write-Host "Chrome Process Sucessfully Stopped" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Clearing Chrome Cache" -ForegroundColor Yellow
try{
Get-ChildItem -Path $env:LOCALAPPDATA"GoogleChromeUser DataDefaultCache" | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:LOCALAPPDATA"GoogleChromeUser DataDefaultCookies" -File | Remove-Item -Confirm:$false
Get-ChildItem -Path $env:LOCALAPPDATA"GoogleChromeUser DataDefaultWeb Data" -File | Remove-Item -Confirm:$false
Write-Host "Chrome Cleaned" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Stopping IE Process" -ForegroundColor Yellow
try{
Get-Process -ProcessName MicrosoftEdge | Stop-Process -Force
Get-Process -ProcessName IExplore | Stop-Process -Force
Write-Host "Internet Explorer and Edge Processes Sucessfully Stopped" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Clearing IE Cache" -ForegroundColor Yellow
try{
RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 8
RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 2
Write-Host "IE and Edge Cleaned" -ForegroundColor Green
}catch{
echo $_
}
Write-Host "Cleanup Complete... Launching Teams" -ForegroundColor Green
Start-Process -FilePath $env:LOCALAPPDATAMicrosoftTeamscurrentTeams.exe
Stop-Process -Id $PID
}else{
Stop-Process -Id $PID
}

Edit 1/27/21 9am

I'm able to get this to work, I will try and figure out how to pass the credentials externally rather than hard coding them and try a larger and more complicated script now as well.

string script = @"$computerName = 'xxxx';
$user = 'xxxxxxxx'; 
$pw = ConvertTo-SecureString -String 'xxxx' -AsPlainText -Force; 
$creds = new-object -typename System.Management.Automation.PSCredential -ArgumentList $user, $pw; 
Invoke-Command -ComputerName $computerName {get-childitem -path 'c:'} -Credential $creds";

Edit 1/27/21 11am The below works and will return the result of get-childitem with one issue, I'm getting an error message in addition to the folder results of. What's the fix for this error message?

"The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input."

// Credential is a c# object of System.Management.Automation.PSCredential
powershell.AddCommand("Set-Variable");
powershell.AddParameter("Name", "extCreds");
powershell.AddParameter("Value", Credential);
powershell.AddCommand("Set-Variable");
powershell.AddParameter("Name", "comp");
powershell.AddParameter("Value", "xxxx");

string script = @"$test1 = 'test1';
                            $test2 = 'test2';
                            $test3 = 'test3';
                            Invoke-Command -ComputerName $comp {get-childitem -path 'c:'} -Credential $extCreds"; 
powershell.AddScript(script);
            psSessions = powershell.Invoke();
question from:https://stackoverflow.com/questions/65908689/how-to-run-a-multiline-powershell-script-inside-of-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...