I'm trying to display the results of the Powershell command "Test-NetConnection" in a Winforms textbox.
using (PowerShell ps = PowerShell.Create())
{
ps.Commands.AddScript("Test-NetConnection");
Collection<PSObject> result = ps.Invoke();
foreach (var outputObject in result)
{
connectionStatus.Text += outputObject.ToString();
}
}
when I run "Test-NetConnection" in Powershell it works and if I switch out ps.Commands.AddScript("Test-NetConnection"); for ps.Commands.AddScript("ipconfig /all"); it works but for some reason using the "Test-NetConnection" command displays nothing. What am I doing wrong?
try something like this :
using (PowerShell ps = PowerShell.Create())
{
ps.Commands.AddScript("Test-NetConnection");
Collection<PSObject> result = ps.Invoke();
int i = 0;
foreach (var outputObject in result)
{
connectionStatus.Text += string.Format("===>Row N°{0} :\r\nComputerName : {1}\r\nRemoteAddress : {2}\r\nInterfaceAlias : {3}\r\nSourceAddress : {4}\r\nPingSucceeded:{5}\r\n",
i++,
outputObject.Properties["ComputerName"].Value,
outputObject.Properties["RemoteAddress"].Value,
outputObject.Properties["InterfaceAlias"].Value,
outputObject.Properties["SourceAddress"].Value,
outputObject.Properties["PingSucceeded"].Value
);
}
}
Related
In Powershell, this command Get-AppxPackage *name* can show a package full details. Is it possible to use any Windows API to get that equivalent result?
I've seen this question and details of all Package Query APIs. But they all need full package names or a running package process handle. Those don't work with wildcard string.
For example, if I installed this package Microsoft.WindowsCalculator_8wekyb3d8bbwe I can get details with Get-AppxPackage *Calculator* command. It is possible with any Windows API? I want to avoid system() or CreateProcess() sort of things.
Thanks to #f6a4 answer. I took a reverse way to accomplish my goal. Here are my procedure:
I find an answer to find the DLL behind Get-AppxPacage cmdlet in Powershell. With this command (Get-Command Get-AppxPackage).dll, Powershell shows the DLL file path as follows:
C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.Windows.Appx.PackageManager.Commands\v4.0_10.0.0.0__31bf3856ad364e35\Microsoft.Windows.Appx.PackageManager.Commands.dll
Go to that path in File Explorer and open Microsoft.Windows.Appx.PackageManager.Commands.dll file in any .NET decompiler. Here I used dnSpy. The Get-AppxManifest command section has this C# code:
protected override void ProcessRecord()
{
AppxPackage appxPackage = this.packageManager.FindPackage(this.Package);
if (appxPackage != null)
{
string str;
if (appxPackage.IsBundle)
{
str = "\\AppxMetadata\\AppxBundleManifest.xml";
}
else
{
str = "\\AppxManifest.xml";
}
using (FileStream fileStream = new FileStream(appxPackage.InstallLocation + str, FileMode.Open, FileAccess.Read))
{
using (XmlReader xmlReader = XmlReader.Create(fileStream, new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Ignore
}))
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(xmlReader);
base.WriteObject(xmlDocument);
}
}
}
}
I converted that code a similar C code with Windows API. Here is the code snippet:
ExpandEnvironmentStringsW(L"%ProgramFiles%\\WindowsApps", Buffer, MAX_PATH);
swprintf(FirstFile, MAX_PATH, L"%ls\\*", Buffer);
hFile = FindFirstFileW(FirstFile, &fileInfo);
if (hFile != INVALID_HANDLE_VALUE) {
do {
if (wcsstr(fileInfo.cFileName, AppxName) != 0) {
memcpy(PackageName, fileInfo.cFileName, MAX_PATH);
}
} while (FindNextFileW(hFile, &fileInfo) != 0);
}
You could browse the app folder and grab the names from the xml manifest files. Admin rights are needed to get access to the app folder.
This example lists all apps with "xbox" in their name. The logic can be easily adapted to C# or another language.
$appNameFilter = '*xbox*'
[System.Collections.Generic.List[string]]$appList = #()
$apps = Get-ChildItem 'C:\Program Files\WindowsApps' -Recurse -Filter 'AppxManifest.xml'
foreach( $app in $apps ) {
$xml = [xml](Get-Content $app.FullName)
$appName = $xml.Package.Properties.DisplayName
if( $appName -like $appNameFilter -and !$appList.Contains( $appName )) {
$appList.Add( $appName )
}
}
$appList
I want to insert the below default values when i am running the service i got this below error any one please tell me how to resolve.
Runtime error in script ("Process: 'CustomPersonalGS Practice' ProcessItem: 'Initialize' Type: 'ITEM'" -1:-1).TypeError: Cannot read property "parameters" from null
//Initialise SQL Query List
tw.local.sqlQueries = new tw.object.listOf.SQLStatement();
tw.local.sql = "";
tw.local.customerPD = new tw.object.customerPD1BO();
tw.local.customerPD.customerPersonalDetailsList = new tw.object.listOf.customerSpecificPersonalDetailsListBO();
var custPersonalDetails = new tw.object.customerSpecificPersonalDetailsListBO();
custPersonalDetails.customerId = "8467";
custPersonalDetails.custPersonalDetailsId = "8";
custPersonalDetails.isBPMEnabled = true;
custPersonalDetails.isCCPEnabled = true;
custPersonalDetails.isCCPMandatory = true;
custPersonalDetails.isLatestVersion = true
tw.local.customerPD.customerPersonalDetailsList.insertIntoList(tw.local.customerPD.customerPersonalDetailsList.listLength, custPersonalDetails);
tw.local.sql = "INSERT INTO CUSTOMPERSONALDETAILSQUESTION(CUSTOMERID,CUSTPERSONLADETAILSID,ISBPMENABLED,ISCCPENABLED,ISCCPMANDATORY,ISLATESTVERSION) VALUES (?,?,?,?,?,?) ";
function addSQLStatement() {
tw.local.sqlQueries[tw.local.sqlQueries.listLength] = new tw.object.SQLStatement();
}
function addParam(value,type,mode) {
log.info("VALUE :" + value);
var newParam = new tw.object.SQLParameter();
newParam.value = value;
newParam.type = type;
newParam.mode = mode;
if( tw.local.sqlQueries == null){
tw.local.sqlQueries = new tw.object.listOf.SQLStatement();
}
if( tw.local.sqlQueries[tw.local.sqlQueries.listLength] == null ){
tw.local.sqlQueries.insertIntoList(tw.local.sqlQueries.listLength, new tw.object.SQLStatement());
}
if(tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters == null ){
tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters = new tw.object.listOf.SQLParameter();
}
var paramsLength = tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters.listLength;
tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters[paramsLength] = newParam;
}
for(var i=0;i<tw.local.customerPD.customerPersonalDetailsList.listLength;i++){
addSQLStatement(tw.local.sql);
addParam(tw.local.customerPD.customerPersonalDetailsList[i].customerId,"VARCHAR","IN");
addParam(tw.local.customerPD.customerPersonalDetailsList[i].custPersonalDetailsId,"VARCHAR","IN");
var yesNoFlag = "N";
if(tw.local.customerPD.customerPersonalDetailsList[i].isBPMEnabled){
yesNoFlag="Y";
addParam(yesNoFlag,"CHAR","IN");
}
yesNoFlag = "N";
if(tw.local.customerPD.customerPersonalDetailsList[i].isCCPEnabled){
yesNoFlag="Y";
addParam(yesNoFlag,"CHAR","IN");
}
yesNoFlag = "N";
if(tw.local.customerPD.customerPersonalDetailsList[i].isCCPMandatory){
yesNoFlag="Y";
addParam(yesNoFlag,"CHAR","IN");
}
yesNoFlag = "N";
if(tw.local.customerPD.customerPersonalDetailsList[i].isLatestVersion){
yesNoFlag="Y";
addParam(yesNoFlag,"CHAR","IN");
}
}
You didn't initialize the parameter list in your SQL as far as I can tell. That is on line 38 you call -
var paramsLength = tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters.listLength;
However when you create the entry in the tw.local.sqlQueries, you didn't initialize the parameter array. I'll also note that your addSQLStatement() function ignore the sql input (and that value is hard coded, so really you don't need to pass it in). I think if you change addSQLStatement to be something like -
function addSQLStatement(query) {
var targetQuery = new tw.object.SQLStatement();
targetQuery.sql = query;
tagetQuery.params = new tw.object.listOf.SQLParameter();
tw.local.sqlQueries[tw.local.sqlQueries.listLength] = targetQuery;
}
then your code will work. Additionally you could actually return targetQuery from this function and then pass it to the "addParams" method eliminating the need to find the last one in the array. Alternatively insert it in the beginning of the array instead and just update the 0th item instead of the last.
-AP
This comparison will never work properly. array[array.length] will always be null (line 35).
if (tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters == null ){
In addition, in the next lines, if you want to work with the last element of the list, you might want to use something like array[array.length - 1]. Personally, I'd use some temporary variable, do some stuff with it and insert it into the list at the end (similar to #Drux's answer).
So I have a program that sends emails. The user has a list of emails that cannot be sent to. These are in arrays and I need to use a if statement to determine if what the user entered in is in the array of emails. I tried the in function which didnt work but Im probably just using it wrong. I tried for loops and if statements inside. But that didnt work either. Here is a snapshot of the code Im using to help you get the idea of what im trying to do.
function test2(){
var safe = [1]
safe[1] = "lol"
safe[2] = "yay"
var entry = "lol"
Logger.log("entry: " + entry)
for(i = 0; i < safe.length; i++){
if(entry == safe[i]){
Logger.log("positive")
}else{
Logger.log("negative")
}
}
}
Here is what I tried with the in function to show you if I did it wrong
function test(){
var safe = [1]
safe[1] = "lol"
safe[2] = "yay"
var entry = "losl"
Logger.log("entry: " + entry)
if(entry in safe){
Logger.log("came positive")
}else{
Logger.log("came negative")
}
Logger.log(safe)
}
array.indexOf(element) > -1 usually does the trick for these situations!
To expand upon this:
if (array.indexOf(emailToSendTo) < 0) {
// send
}
Alternatively, check this cool thing out:
emailsToSend = emailsToSend.filter(function(x) {
// basically, this returns "yes" if it's not found in that other array.
return arrayOfBadEmails.indexOf(x) < 0;
})
What this does is it filters the list of emailsToSend, making sure that it's not a bad email. There's probably an even more elegant solution, but this is neat.
I'm using ObjectEvents to give ActivityPoints to current user based on fields user filled.
Now for example if user register and fill FirstName I will give 10 points to user.
The problem is that I'm handling ObjectEvents.Update.After and inside it I'm updating userSettings.This causes a unlimited loop and application stops working.
is there any work around?
this is the code block:
var className = e.Object.TypeInfo.ObjectClassName;
DataClassInfo dci = DataClassInfoProvider.GetDataClass(className);
if (dci != null)
{
var fi = new FormInfo(dci.ClassFormDefinition);
if (fi != null)
{
var stopProccess = true;
var fields = new List<FormFieldInfo>();
foreach (var changedColumn in e.Object.ChangedColumns())
{
var field = fi.GetFormField(changedColumn);
var activityPointMacro = ValidationHelper.GetString(field.Settings["ActivityPointMacro"], "");
if (!string.IsNullOrEmpty(activityPointMacro))
{
fields.Add(field);
stopProccess = false;
}
}
if (!stopProccess)
{
var contextResolver = CMSContext.CurrentResolver.CreateContextChild();
foreach (FormCategoryInfo info in fi.ItemsList.OfType<FormCategoryInfo>())
{
contextResolver.SetNamedSourceData(info.CategoryName, info);
}
EditingFormControl data = new EditingFormControl();
foreach (FormFieldInfo info2 in fi.ItemsList.OfType<FormFieldInfo>())
{
contextResolver.SetNamedSourceData(info2.Name, data);
}
foreach (var field in fields)
{
{
var activityPointMacro = ValidationHelper.GetString(field.Settings["ActivityPointMacro"], "");
var activityPoint =
ValidationHelper.GetInteger(contextResolver.ResolveMacros(activityPointMacro), 0);
CMSContext.CurrentUser.UserSettings.UserActivityPoints += activityPoint;
CMSContext.CurrentUser.UserSettings.Update();
}
}
}
}
}
If you just need to give points for user fields then you could just use ObjectEvents.Update.Before, check fields are not empty and assign points. But i can see from the code, you want to have something more complex bulit over macro expressions. So I have a few suggestions for you.
1) ObjectEvents.Update.Before instead of ObjectEvents.Update.After still may be a good idea. Ideally you set your additional values and all is set during one update.
2) Watch only the class names you need
3) Always prefer Provider.SetInfo methods over info.Update(). In case of user settings it's best to set whole user info, so UserInfoProvider.SetUserInfo. Provider methods may add some additional important logic.
4) The code seems like it'll add the points with every update of a user
5) if you are still running into a loop, you need to flag somehow, that some part of code should not be executed again. The best way is to use RequestStockHelper class - add a bool value with a specificname like "PointsProcessed".
I have a List of Codes (COD_XX) and I need to search each code in a text file, and get the index of the line where is located. The first caracter of the line contains the cod.
I've saved all the lines in a List
var fileLines = File.ReadAllLines(filePath);
List<string> fileItems = new List<string>(fileLines);
foreach (string param in lstCodes)
{
int idx = fileItems.FindIndex(m => m.Substring(0,6) == param)
}
But this expression is not working :( How should I writte it?
Thank you in advanced for your help.
Your code works fine if you put ; after fileItems.FindIndex(...)
But m.Substring(0,6) could throw an exception if m is shorter than 6.
You should use String.StartsWith method.
foreach (string param in lstCodes)
{
int idx = fileItems.FindIndex(m => m.StartsWith(param));
}