Explore all Automation open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Automation

puppeteer

13.6.0

playwright

v1.21.1

headless-recorder

v1.1.0

forever

4.0.0

awx

20.1.0

Popular Libraries in Automation

puppeteer

by puppeteer doticontypescriptdoticon

star image 77484 doticonApache-2.0

Headless Chrome Node.js API

playwright

by microsoft doticontypescriptdoticon

star image 36789 doticonApache-2.0

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

headless-recorder

by checkly doticonjavascriptdoticon

star image 14029 doticonMIT

Chrome extension that records your browser interactions and generates a Playwright or Puppeteer script.

forever

by foreversd doticonjavascriptdoticon

star image 13329 doticonMIT

A simple CLI tool for ensuring that a given script runs continuously (i.e. forever)

fabric

by fabric doticonpythondoticon

star image 13313 doticonBSD-2-Clause

Simple, Pythonic remote execution and deployment.

chromeless

by prisma-archive doticontypescriptdoticon

star image 13250 doticonMIT

🖥 Chrome automation made simple. Runs locally or headless on AWS Lambda.

awx

by ansible doticonpythondoticon

star image 10864 doticonNOASSERTION

AWX Project

robotjs

by octalmage doticoncdoticon

star image 10438 doticonMIT

Node.js Desktop Automation.

Auto.js

by hyb1996 doticonjavadoticon

star image 10414 doticonMPL-2.0

A UiAutomator on android, does not need root access(安卓平台上的JavaScript自动化工具)

Trending New libraries in Automation

pyppeteer

by pyppeteer doticonpythondoticon

star image 2004 doticonNOASSERTION

Headless chrome/chromium automation library (unofficial port of puppeteer)

kit

by johnlindquist doticontypescriptdoticon

star image 1467 doticonMIT

Script Kit. Automate Anything.

Readarr

by Readarr doticoncsharpdoticon

star image 1453 doticonGPL-3.0

Book Manager and Automation (Sonarr for Ebooks)

puppeteer-webperf

by addyosmani doticonjavascriptdoticon

star image 1444 doticonApache-2.0

Automating Web Performance testing with Puppeteer 🎪

playwright-dotnet

by microsoft doticonjavascriptdoticon

star image 1421 doticonMIT

.NET version of the Playwright testing and automation library.

hent-AI

by natethegreate doticonpythondoticon

star image 1185 doticonMIT

Automation of censor bar detection

Shuffle

by frikky doticonjavascriptdoticon

star image 693 doticonAGPL-3.0

Shuffle: A general purpose security automation platform. Our focus is on collaboration and resource sharing.

playwright-sharp

by microsoft doticoncsharpdoticon

star image 684 doticonMIT

.NET version of the Playwright testing and automation library.

peeky

by Akryum doticontypescriptdoticon

star image 602 doticonMIT

A fast and fun test runner for Vite & Node 🐈️ Powered by Vite ⚡️

Top Authors in Automation

1

CiscoDevNet

17 Libraries

star icon314

2

brucemcpherson

16 Libraries

star icon78

3

PacktPublishing

14 Libraries

star icon355

4

microsoft

12 Libraries

star icon39314

5

google

12 Libraries

star icon1660

6

ksator

11 Libraries

star icon264

7

TheDMSGroup

10 Libraries

star icon236

8

ansible-collections

9 Libraries

star icon707

9

jenkinsci

8 Libraries

star icon165

10

mozilla

8 Libraries

star icon145

1

17 Libraries

star icon314

2

16 Libraries

star icon78

3

14 Libraries

star icon355

4

12 Libraries

star icon39314

5

12 Libraries

star icon1660

6

11 Libraries

star icon264

7

10 Libraries

star icon236

8

9 Libraries

star icon707

9

8 Libraries

star icon165

10

8 Libraries

star icon145

Trending Kits in Automation

JavaScript automation libraries help you to automate actions in your browsers. These libraries are very useful for testing web applications. We can run JavaScript automation using any of the Selenium drivers like ChromeDriver, GeckoDriver, InternetExplorerDriver, etc. One reason for the popularity of JavaScript-based web application frameworks is that most web applications have JavaScript components and it's going to be easier to automate such web applications with JavaScript. Developers tend to use some of the following open source libraries: Detox - tests your mobile app while it’s running in a real device/simulator, interacting with it just like a real user; Shipit - Shipit is an automation engine and a deployment tool. Shipit provides a good alternative to Capistrano or other build tools. It is easy to deploy or automate simple tasks on your remote servers. The entire list of Javascript automation open source libraries is provided below.

Ruby is an object-oriented programming language. It is known for its easy readability and reduced lines of code. It also offers a dynamic and rich set of features that make it extremely versatile and flexible. Ruby has been a go-to language for test automation engineers. Ruby automation libraries are gaining popularity over the years as this language has wide support to most modern browsers and operating systems, making it an ideal choice for developing automated scripts. A few of the most popular open source libraries for developers are: Fastlane - The easiest way to automate building and releasing your iOS and Android apps, Capistrano - Remote multi-server automation tool that gives you a cap tool to perform your deployments from the comfort of your command line, Linode - Ruby wrapper for the Linode automation API. The following is a comprehensive list of best Ruby automation open source libraries.

Since its creation in 2008, the Go programming language has taken the world by storm. It's loved by millions of developers, and is the go-to language for many major applications. Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction. In addition to the basic procedural programming features of C (static variables, pointers), Go also provides features for concurrent programming such as goroutines (lightweight threads) and channels. If you're one of the people who's in love with Go, you probably know that automation is always a valuable tool in your arsenal. You may be wondering "Why do I need an automation library?" The answer is simple: it can save you a ton of time and effort! Popular open source libraries include: RobotGo - Go Native crossplatform GUI automation, Atlantis - A self-hosted golang application that listens for Terraform pull request events via webhooks, Comply - a SOC2-focused compliance automation tool. Here are some of the best Go automation libraries to check out.

When it comes to web development, we can’t deny the importance of PHP. While HTML and CSS are used for creating the structure and style of a website, PHP is used for building the backend of a website or web app. There are various reasons why it is still one of the most preferred languages for web development. It has an easy learning curve, which makes it ideal for beginners who want to learn to code. It also offers many frameworks that can be used for building websites or web apps from scratch. PHP is among the best automation libraries for web developers. It has a vast array of automation tools and frameworks that help developers develop websites that are fast, secure, and easy to maintain. Some of the most widely used open source libraries among developers include: PHP_CodeSniffer - tokenizes PHP files and detects violations, WordOps - Install and manage a high-performance WordPress stack with a few keystrokes, Grawler - tool written in PHP which comes with a web interface. The entire list of open source libraries are provided below.

C Automation libraries are the best and easiest way to handle all kinds of automation. No matter what kind of tasks you need to do, there is always a solution for it. C is a high-level programming language that can be used in various applications from embedded systems to supercomputers, making it one of the most versatile languages on the planet. Now, talking about C-based automation, it’s flexible and easy to use. The language is used widely by developers all around the globe. Not only in developing software but also in hardware coding. Some of the most popular among developers are: CrazyEye - OpenSource IT Automation Software, Libmodbus - libmodbus is a free software library to send/receive data with a device that respects the Modbus protocol. This library can use a serial port or an Ethernet connection. We have listed the best C Automation Libraries for all types of automation tasks available out there. If you don't know which library you should use or which one will suit your needs, this kit will help you select the right option for you.

C# is one of the most popular programming languages in the entire world and boasts a massive ecosystem of libraries and frameworks. It's also one of the best languages to use for testing automation projects, owing to its ability to interact with all kinds of different software and systems (including Windows applications). We can use automation libraries that allow us to perform repetitive tasks automatically. Some of the most widely used C# Automation open source libraries among developers include: Cake - Cake (C# Make) is a build automation system with a C# DSL to do things like compiling code, copy files/folders, running unit tests, compress files and build NuGet packages; FlubuCore - cross platform build and deployment automation system. You can define your build and deployment scripts in C# using an intuitive fluent interface. The entire list of C# Automation open source libraries are provided below.

Java remains one of the most popular and widely used programming languages out there. It is a versatile language that can be used in a multitude of environments, from enterprise server-side applications to Android apps. Every job is being automated these days. Java Automation libraries are used to test Java programs without manually executing the tests. In addition to speeding up the testing process, this allows programmers to automate much of their testing, which improves accuracy and lets developers move on to new projects sooner. There are many frameworks that make Java development easier. Due to its advanced functionalities, Selenium is one of the most used Python Automation library. This is an open-source tool that allows developers to create automated tests for web applications. It was designed with automation in mind and supports multiple browsers, including Internet Explorer and Firefox. The Selenium suite includes components like WebDriver, which can be used to automate interactions with pages; Selendroid, which provides a framework for testing native Android apps; and Selenium Grid, which allows teams to collaborate on test execution by running tests simultaneously across different machines or browsers using distributed remote control nodes (such as those provided by Sauce Labs). The following is a comprehensive list of the best Java Automation open source libraries.

C++ automation libraries are a great way to save time and effort while developing a mobile application. Automation libraries allow developers to create and automate processes that are repetitive or tedious. This not only saves the developer time, but it also leaves room for other essential tasks to be done instead of spending time on processes that can be automated. With the growing demand for mobile apps, developers are looking for ways to use automation in their workflow. Some of the most widely used open source libraries among developers include: CPP-Reflection - C++ Reflection Parser / Runtime Skeleton, BAS -Browser Automation Studio can automate everything that Chrome can, wxAutoExcel - wxWidgets library attempting for Excel automation, RPA_CPP - C++ Robotic Process Automation. The following is a comprehensive list of best C++ automation open source libraries.

Here are the top C# Web Automation Frameworks or Libraries that offer tools and APIs for automating web browser actions like navigating between pages, filling out forms, scraping data from web pages, and clicking buttons. These libraries use programming languages to interact with web browsers to execute automation tasks.  


Web Automation libraries are commonly used for website scraping, data extraction, and testing. We can also use these for automating repetitive tasks which involve web applications. By using these libraries, developers can save time and effort by automating tasks requiring manual interactions with web browsers.  


We have handpicked the top Web Automation libraries for your next project below. 

RestSharp: 

  • Is an open source library for making HTTP requests and handling RESTful APIs in C# applications. 
  • It simplifies communication with web services and APIs by offering an intuitive and easy-to-use interface. 
  • Supports different data formats like JSON, form-urlencoded data, and XML, which can handle authentication mechanisms.  

AngleSharp: 

  • Is an open source library for manipulating, rendering, and parsing HTML and XML documents in C# applications.  
  • Is a flexible and powerful library that offers a comprehensive set of APIs for working with XML and HTML content.  
  • Is built on top of the .NET standard applications like Xamarin, Unity, and ASP.NET Core. 

cake: 

  • Is an open source build automation tool and scripting language for .NET applications.  
  • Allows developers to write build scripts with the help of simple and intuitive C# syntax and makes it easy to automate different build and deployment tasks.  
  • Can execute build tasks parallelly, making the building process quicker and more efficient.  

html-agility-pack: 

  • Is an open source library for parsing HTML documents in .NET applications. 
  • Provides various APIs for working with HTML documents, allowing developers to manipulate and extract data from the HTML pages easily. 
  • Offers a comprehensive set of APIs for working on HTML pages widely used for web automation, scraping, and other parsing HTML pages. 

Readarr: 

  • Is an open source library that offers a comprehensive set of tools for managing and organizing e-books in C# applications.  
  • Offers a web-based user interface allowing users to add or manage e-books quickly.  
  • It integrates with popular e-book sources like Project Gutenberg and Calibre. 

FlaUI: 

  • Is an open source library for automating Windows user interface using the Microsoft UI Automation API.  
  • Provides various APIs for interacting with UI elements, allowing developers to automate UI testing and other UI-related tasks.  
  • Offers a simple and intuitive API for interacting with UI elements, making it easy to write UI automation scripts in C# applications. 

AssetGraph: 

  • Offers a visual editor and various APIs for creating complex asset pipelines, allowing developers to easily manage dependencies between assets and automating complex asset process tasks.  
  • Allows developers to create a graph of asset processing nodes, where every node will represent a specific asset processing task.  
  • Is a powerful tool for managing asset pipelines in Unity, which game developers and other Unity developers use for streamlining and improving the workflow. 

buildtool: 

  • Is a Unity utility that automates the process of generating builds.  
  • Easily kick off batch builds for all or a certain subset of your build configurations.  
  • Offers features like version number generation and options for more expanded build capabilities like creating zip files, building AssetBundles, and automated file copying or moving. 

FlubuCore: 

  • Is an open source library used to build and automate .NET projects written in C#. 
  • Offers a fluent interface for defining build scripts, allowing developers to automate complex tasks easily. 
  • Support various build tasks like running tests, compiling code, deploying applications, etc. 

taskt: 

  • Is an open source library for Robotic Process Automation, enabling users to automate repetitive tasks on their computers.  
  • Provides various tools and functions for automating tasks like web automation, user interface automation, file operations, and data manipulation. 
  • Is a powerful tool for automating repetitive tasks and streamlining workflows to increase efficiency and productivity. 

Trending Discussions on Automation

In JavaScript, can you reference a method/function name within that method/function?

fastlane: [!] Google Api Error: Invalid request - Package not found: com.example.todo

ExportAsFixedFormat's IgnorePrintAreas parameter seems not to have effect

Script calls other script as .ps1 but not as a .exe using ps2exe

Optionally static class method for interface compatibility

Automatic merging of Dependabot generated Pull Request with codeowners file and branch protection rule?

Powershell package missing/not working on release

Has Variant behavior changed in Delphi 11?

New-CimSession without elevation by providing admin credentials on Windows 10?

Diagnostic setting not included in Azure Portal ARM template export

QUESTION

In JavaScript, can you reference a method/function name within that method/function?

Asked 2022-Mar-28 at 10:35

I am building an automation framework in JavaScript for WebdriverIO.

The "out-of-the-box" error messages aren't too helpful and I would like to add the class name and method name as part of a prefix to the error message which is thrown when the method/function fails.

I have managed to call the class name with ClassName.name

However, I have not found a solution to reference the method name without using some hardcoded value.

Below is a summary of the changes I would like to make.

Before:

1setElementValue(element, value){
2    try{
3        this.waitForElementAndScroll(element);
4        $(element).setValue(value);
5    }
6    catch(error){
7        throw `${BasePage.name}.setElementValue: ${error.message}`;
8    }
9}
10

After:

1setElementValue(element, value){
2    try{
3        this.waitForElementAndScroll(element);
4        $(element).setValue(value);
5    }
6    catch(error){
7        throw `${BasePage.name}.setElementValue: ${error.message}`;
8    }
9}
10setElementValue(element, value){
11    try{
12        this.waitForElementAndScroll(element);
13        $(element).setValue(value);
14    }
15    catch(error){
16        throw `${BasePage.name}.${setElementValue.name}: ${error.message}`;
17    }
18}
19

Where ${setElementValue.name} is the method of referencing the name of the method/function.

Many thanks in advance!

I have tried the following with no success:

method.name //ReferenceError: method is not defined

(method).name //ReferenceError: method is not defined

Function.name //Returns "Function"

Function.value //Returns "undefined"

constructor.name //Returns "Object"

setElementValue.name //ReferenceError: setElementValue is not defined

ANSWER

Answered 2022-Mar-28 at 10:35

I found this (very obvious) solution to work for me:

1setElementValue(element, value){
2    try{
3        this.waitForElementAndScroll(element);
4        $(element).setValue(value);
5    }
6    catch(error){
7        throw `${BasePage.name}.setElementValue: ${error.message}`;
8    }
9}
10setElementValue(element, value){
11    try{
12        this.waitForElementAndScroll(element);
13        $(element).setValue(value);
14    }
15    catch(error){
16        throw `${BasePage.name}.${setElementValue.name}: ${error.message}`;
17    }
18}
19this.setElementValue.name
20

where the thrown error message is:

1setElementValue(element, value){
2    try{
3        this.waitForElementAndScroll(element);
4        $(element).setValue(value);
5    }
6    catch(error){
7        throw `${BasePage.name}.setElementValue: ${error.message}`;
8    }
9}
10setElementValue(element, value){
11    try{
12        this.waitForElementAndScroll(element);
13        $(element).setValue(value);
14    }
15    catch(error){
16        throw `${BasePage.name}.${setElementValue.name}: ${error.message}`;
17    }
18}
19this.setElementValue.name
20throw `${BasePage.name}.${this.setElementValue.name}: ${error.message}`;
21

which outputs the following error log when the method fails:

1setElementValue(element, value){
2    try{
3        this.waitForElementAndScroll(element);
4        $(element).setValue(value);
5    }
6    catch(error){
7        throw `${BasePage.name}.setElementValue: ${error.message}`;
8    }
9}
10setElementValue(element, value){
11    try{
12        this.waitForElementAndScroll(element);
13        $(element).setValue(value);
14    }
15    catch(error){
16        throw `${BasePage.name}.${setElementValue.name}: ${error.message}`;
17    }
18}
19this.setElementValue.name
20throw `${BasePage.name}.${this.setElementValue.name}: ${error.message}`;
21`BasePage.setElementValue: element ("#submit-button") still not displayed after 500ms`
22

Source https://stackoverflow.com/questions/71600843

QUESTION

fastlane: [!] Google Api Error: Invalid request - Package not found: com.example.todo

Asked 2022-Mar-20 at 02:27

I am using React-native for my app. I have named my name reactamplify. I want to deploy my app to Google play-store. For automation deployment I am using first time fastlane. I found this documentation, follow the steps and give API grant access. In my React native app, I navigate to android folder then run this command fastlane init. Give json_key_file path my downloaded auth json file. But I got confused about package name. I search my app name in vscode com.reactamplify replace them into com.example.todo. Then run android folder fastlane supply init, I am getting this error: [!] Google Api Error: Invalid request - Package not found: com.example.todo. I really don't know how to fix it :(. Really lost TBH.

When I run fastlane supply. I got this image

enter image description here

PS: It would be awesome if someone gives me example with images

ANSWER

Answered 2021-Oct-29 at 04:46

I found the reason. I need to upload at least one build to google Play store app manually. That’s why I got package name error.

Source https://stackoverflow.com/questions/69073389

QUESTION

ExportAsFixedFormat's IgnorePrintAreas parameter seems not to have effect

Asked 2022-Mar-10 at 07:43

In a Delphi application I am using since years the following code to export xlxs to pdf:

1function TExportTool.ExportExcelToPDF(aFileName, aNewFileName: String): Boolean;
2// reference : http://embarcadero.newsgroups.archived.at/public.delphi.oleautomation/200811/081103142.html
3// unluckily the link above is dead
4{- Sheet is counted from 1 and upwards !! }
5Var
6  App,oWB,oSheet : OleVariant;
7begin
8  Result := False;
9  App:= CreateOleObject('Excel.Application');
10  Try
11    App.Visible:= 0;
12    oWb := App.WorkBooks.Open(ExpandUNCFileName(afilename),1);  // Open read only
13    Try
14     oSheet := oWB.ActiveSheet;
15     oSheet.ExportAsFixedFormat(0,  //xlTypePDF is constant 0
16                            aNewFileName,
17                            EmptyParam, 
18                            EmptyParam, 
19                            EmptyParam, // this should be IgnorePrintAreas
20                            EmptyParam,
21                            EmptyParam,
22                            EmptyParam,
23                            EmptyParam
24                            );
25    Finally
26    End;
27    Result := True;
28  Finally
29    App.Quit;
30    App:= UnAssigned;
31  End;
32end;
33
34// IMPROVED WORKING CODE FOLLOWS
35
36function TExportTool.ExportExcelToPDF(aFileName, aNewFileName: String): Boolean;
37// reference : http://embarcadero.newsgroups.archived.at/public.delphi.oleautomation/200811/081103142.html
38{- Sheet is counted from 1 and upwards !! }
39
40procedure RestoreOriginalPrintArea (oSheet: OleVariant);
41// Excel loses print area settings in non-English version of application when file is opened using automation:
42// https://stackoverflow.com/questions/71379893/exportasfixedformats-ignoreprintareas-parameter-seems-not-to-have-effect
43var
44  i:Integer;
45begin
46  for  i:= 1 to oSheet.Names.Count do
47  begin
48   if VarToStr(oSheet.Names.Item(i).Name).EndsWith('!Print_Area') then
49   begin
50     oSheet.PageSetup.PrintArea:='Print_area';
51     Break;
52   end;
53  end;
54end;
55
56Var
57  App,oWB,oSheet : OleVariant;
58  i:Integer;
59begin
60  Result := False;
61  App:= CreateOleObject('Excel.Application');
62  Try
63    App.Visible:= 0;
64    oWb := App.WorkBooks.Open(ExpandUNCFileName(afilename),1);  // Open read only
65    Try
66     oSheet := oWB.ActiveSheet;
67     RestoreOriginalPrintArea(oSheet);  // workaround
68     oSheet.ExportAsFixedFormat(0,  //xlTypePDF is constant 0
69                            aNewFileName,
70                            0, // standard quality = 0, Max quality = 1
71                            false, //include doc properties
72                            false, //ignore print area
73                            EmptyParam,
74                            EmptyParam,
75                            EmptyParam,
76                            EmptyParam
77                            );
78    Finally
79    End;
80    Result := True;
81  Finally
82    oWB.Close(false); // better to close the WorkBook too
83    App.Quit;
84    App:= UnAssigned;
85  End;
86end;
87

Now i realized that the pdf created with this code behave like when saving to pdf from Excel using the option "Ignore Print areas" (it is one of the options of the export to pdf from Excel feature).

So I decided to "uncheck" that checkbox also from code and I studied the parameters of ExportAsFixedFormat (reference here).

The fifth parameter is IgnorePrintAreas, so I was assuming that passing False to it, the print areas would have been ignored.

I tried several common sense solution, including:

  • passing only that parameter (passing either True or False )
  • passing all the first 5 parameters (just in case they are mandatory at runtime)

but no result: the pdf created by my application still "ignores the print areas".

Does anyone has a suggestion or has experience on this specific subject to give me a pointer to fix this issue?

Thanks.

UPDATE

Thanks to the useful accepted answer I appended to the code above the solution for reference, notice two things:

  1. the RestoreOriginalPrintArea procedure that contains the workaround
  2. the call to oWB.Close(false) at the end

ANSWER

Answered 2022-Mar-10 at 06:48

Root cause of error:

Excel loses print area settings in non-English version of application when file is opened using automation.

Why this is happening:

When you define print area in a sheet, Excel internally creates a named range. It has two properties defining its name:

  1. Name this property is always of the form WorksheetsName!Print_Area (if the sheet's name contains some special characters it is also enclosed in single quotes).
  2. NameLocal has similar structure, but the second part is translated into the language of the application.

This is what it looks like when you open the file in Excel and inspect these properties in VBA, but when you open the same file using automation (for example using the code in question), then NameLocal is no longer translated. This bug causes the named range to not be recognized correctly as print area. oSheet.PageSetup.PrintArea returns an empty string.

Workaround:

Restore original print area after opening the file using:

oSheet.PageSetup.PrintArea:='Print_Area';

This line of code will throw an exception when there was no print area defined in sheet, so there are two options:

  1. Place the line inside try..except block.
  2. Iterate the Names collection and look for a Name ending with !Print_Area, for example:
1function TExportTool.ExportExcelToPDF(aFileName, aNewFileName: String): Boolean;
2// reference : http://embarcadero.newsgroups.archived.at/public.delphi.oleautomation/200811/081103142.html
3// unluckily the link above is dead
4{- Sheet is counted from 1 and upwards !! }
5Var
6  App,oWB,oSheet : OleVariant;
7begin
8  Result := False;
9  App:= CreateOleObject('Excel.Application');
10  Try
11    App.Visible:= 0;
12    oWb := App.WorkBooks.Open(ExpandUNCFileName(afilename),1);  // Open read only
13    Try
14     oSheet := oWB.ActiveSheet;
15     oSheet.ExportAsFixedFormat(0,  //xlTypePDF is constant 0
16                            aNewFileName,
17                            EmptyParam, 
18                            EmptyParam, 
19                            EmptyParam, // this should be IgnorePrintAreas
20                            EmptyParam,
21                            EmptyParam,
22                            EmptyParam,
23                            EmptyParam
24                            );
25    Finally
26    End;
27    Result := True;
28  Finally
29    App.Quit;
30    App:= UnAssigned;
31  End;
32end;
33
34// IMPROVED WORKING CODE FOLLOWS
35
36function TExportTool.ExportExcelToPDF(aFileName, aNewFileName: String): Boolean;
37// reference : http://embarcadero.newsgroups.archived.at/public.delphi.oleautomation/200811/081103142.html
38{- Sheet is counted from 1 and upwards !! }
39
40procedure RestoreOriginalPrintArea (oSheet: OleVariant);
41// Excel loses print area settings in non-English version of application when file is opened using automation:
42// https://stackoverflow.com/questions/71379893/exportasfixedformats-ignoreprintareas-parameter-seems-not-to-have-effect
43var
44  i:Integer;
45begin
46  for  i:= 1 to oSheet.Names.Count do
47  begin
48   if VarToStr(oSheet.Names.Item(i).Name).EndsWith('!Print_Area') then
49   begin
50     oSheet.PageSetup.PrintArea:='Print_area';
51     Break;
52   end;
53  end;
54end;
55
56Var
57  App,oWB,oSheet : OleVariant;
58  i:Integer;
59begin
60  Result := False;
61  App:= CreateOleObject('Excel.Application');
62  Try
63    App.Visible:= 0;
64    oWb := App.WorkBooks.Open(ExpandUNCFileName(afilename),1);  // Open read only
65    Try
66     oSheet := oWB.ActiveSheet;
67     RestoreOriginalPrintArea(oSheet);  // workaround
68     oSheet.ExportAsFixedFormat(0,  //xlTypePDF is constant 0
69                            aNewFileName,
70                            0, // standard quality = 0, Max quality = 1
71                            false, //include doc properties
72                            false, //ignore print area
73                            EmptyParam,
74                            EmptyParam,
75                            EmptyParam,
76                            EmptyParam
77                            );
78    Finally
79    End;
80    Result := True;
81  Finally
82    oWB.Close(false); // better to close the WorkBook too
83    App.Quit;
84    App:= UnAssigned;
85  End;
86end;
87var i:Integer;
88for  i:= 1 to oSheet.Names.Count do
89begin
90  if  VarToStr(oSheet.Names.Item(i).Name).EndsWith('!Print_Area') then
91  begin
92    oSheet.PageSetup.PrintArea:='Print_area';
93    Break;
94  end;
95end;
96

Other important change:

Because the file could have been modified you also need to add:

oWB.Close(false); //do not save changes

before closing the application, otherwise each call to this function would result in another Excel process still running invisible.

Source https://stackoverflow.com/questions/71379893

QUESTION

Script calls other script as .ps1 but not as a .exe using ps2exe

Asked 2022-Feb-15 at 16:13
1$password = ConvertTo-SecureString “Password+++” -AsPlainText -Force
2$Cred = New-Object System.Management.Automation.PSCredential ("Admin", $password)
3$FileLocale = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
4Write-Output $FileLocale
5$AntFile = "$FileLocale\StartApps.ps1"
6Write-Output $AntFile
7Start-Process PowerShell.exe -ArgumentList "-command &$AntFile -UserCredential $Cred"  
8

Hi, that code works in .ps1, I call the other script, and he makes his job. But when I transform it in .exe with the help of ps2exe, he doesn't do his job anymore. As admin or not. It's not the first time I use that start-process, but it's the first time I use a variable as a target for the command. Do anyone know what go wrong between the ps1 and exe ?

Thanks

ANSWER

Answered 2022-Feb-15 at 16:13

While an executable compiled with ps2exe uses a .ps1 file as input, at runtime no actual .ps1 file is involved, which is why PowerShell's command-reflection variables cannot tell you anything about a running script file.

When running an actual .ps1 file, you'd use the following about_Automatic_Variables:

  • $PSCommandPath contains the the executing script file's full file path.

  • $PSScriptRoot contains the script file's full directory path (i.e. the full path of the directory in which the script file is located).

In a ps2exe-compiled executable (.exe), where these variables have no values, you can use the following instead:

  • [Environment]::GetCommandLineArgs()[0] contains the executable file's full file path.

  • Split-Path -LiteralPath ([Environment]::GetCommandLineArgs()[0]) contains the executable file's full directory path.


Applied to your code - assuming that a separate StartApp.ps1 file is present alongside your .exe file:[1]

1$password = ConvertTo-SecureString “Password+++” -AsPlainText -Force
2$Cred = New-Object System.Management.Automation.PSCredential ("Admin", $password)
3$FileLocale = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
4Write-Output $FileLocale
5$AntFile = "$FileLocale\StartApps.ps1"
6Write-Output $AntFile
7Start-Process PowerShell.exe -ArgumentList "-command &$AntFile -UserCredential $Cred"  
8$FileLocale = Split-Path -LiteralPath ([Environment]::GetCommandLineArgs()[0])
9$AntFile = Join-Path $FileLocale StartApps.ps1
10

If you want to make your code work in both invocation scenarios - the original .ps1 file directly as well as the compiled .exe file - use the following:

1$password = ConvertTo-SecureString “Password+++” -AsPlainText -Force
2$Cred = New-Object System.Management.Automation.PSCredential ("Admin", $password)
3$FileLocale = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
4Write-Output $FileLocale
5$AntFile = "$FileLocale\StartApps.ps1"
6Write-Output $AntFile
7Start-Process PowerShell.exe -ArgumentList "-command &$AntFile -UserCredential $Cred"  
8$FileLocale = Split-Path -LiteralPath ([Environment]::GetCommandLineArgs()[0])
9$AntFile = Join-Path $FileLocale StartApps.ps1
10$FileLocale = 
11  if ($PSScriptRoot) { $PSScriptRoot }
12  else { Split-Path -LiteralPath ([Environment]::GetCommandLineArgs()[0]) }
13
14$AntFile = Join-Path $FileLocale StartApps.ps1
15

[1] Note that at runtime no information is available about where the original .ps1 file that served as compile-time input was originally located - only that file's content becomes part of the .exe file.

Source https://stackoverflow.com/questions/71127896

QUESTION

Optionally static class method for interface compatibility

Asked 2022-Jan-24 at 04:33

I've defined a custom ValidateSet parameter attribute like so:

1Class MyValidValuesAttribute : System.Management.Automation.IValidateSetValuesGenerator {
2    [string[]] GetValidValues() { return [string[]]'MyValidValueA','MyValidValueB' }
3}
4

I'd like to avoid having to instantiate the class just to return the set of valid values.

I'd simply call [MyValidValuesAttribute]::GetValidValues() instead of the two-line

1Class MyValidValuesAttribute : System.Management.Automation.IValidateSetValuesGenerator {
2    [string[]] GetValidValues() { return [string[]]'MyValidValueA','MyValidValueB' }
3}
4$X = [MyValidValuesAttribute]::new()
5$Y = $X.GetValidValues()
6

but that method must not be static or the class will not implement the interface.

Is there any way to make a method work the same way regardless of whether the class has been instantiated under the same name? I know I could just implement GetValidValues_Static; wondering if a more elegant solution exists.

ANSWER

Answered 2022-Jan-24 at 04:33

As Santiago Squarzon points out, you don't usually need to instantiate an IValidateSetValuesGenerator-implementing class yourself: PowerShell does it for you when you use such a class in a [ValidateSet()] attribute in order to decorate a parameter in a function's or script's parameter-declaration block (param(...)), so as to constrain the arguments passed to that parameter to the set of values returned from the specified class' .GetValidValues() instance method.

Note: The IValidateSetValuesGenerator interface requires PowerShell (Core) v6+; for solutions that also work in Windows PowerShell, see this blog post that Santiago found.


If you do need to instantiate such a class explicitly:

instead of the two-line

You can use a single(-line) expression:

1Class MyValidValuesAttribute : System.Management.Automation.IValidateSetValuesGenerator {
2    [string[]] GetValidValues() { return [string[]]'MyValidValueA','MyValidValueB' }
3}
4$X = [MyValidValuesAttribute]::new()
5$Y = $X.GetValidValues()
6[MyValidValuesAttribute]::new().GetValidValues()
7

I know I could just implement GetValidValues_Static; wondering if a more elegant solution exists.

If you do need to keep the invocation ceremony to a minimum, you can declare a static property as follows, which then allows you to call [MyValidValuesAttribute]::ValidValues:

1Class MyValidValuesAttribute : System.Management.Automation.IValidateSetValuesGenerator {
2    [string[]] GetValidValues() { return [string[]]'MyValidValueA','MyValidValueB' }
3}
4$X = [MyValidValuesAttribute]::new()
5$Y = $X.GetValidValues()
6[MyValidValuesAttribute]::new().GetValidValues()
7Class MyValidValuesAttribute : System.Management.Automation.IValidateSetValuesGenerator {
8  static [string[]] $ValidValues = [MyValidValuesAttribute]::new().GetValidValues()
9  [string[]] GetValidValues() { return [string[]] ('MyValidValueA','MyValidValueB') }
10}
11

Caveat: Since the static ValidValues property is only initialized once, the above assumes that that the set of valid values is static, which may be at odds with the intentionally dynamic nature of the IValidateSetValuesGenerator interface.

  • In fact, the dynamic nature is the reason that the interface defines .GetValidValues() as an instance method - situationally, a different set of valid values may be returned; otherwise, you could simply use the [ValidateSet()] attribute with a static list of values, such as [ValidateSet('MyValidValueA', 'MyValidValueB')]

As of v7.2.1, PowerShell doesn't support property getters that are called on each invocation - see GitHub issue #2219.

Source https://stackoverflow.com/questions/70828007

QUESTION

Automatic merging of Dependabot generated Pull Request with codeowners file and branch protection rule?

Asked 2022-Jan-20 at 09:46
1    name: Dependabot auto-approve
2    on: pull_request_target
3    
4    permissions:
5      contents: write
6      pull-requests: write
7    
8    jobs:
9      dependabot:
10        runs-on: ubuntu-latest
11        if: ${{ github.actor == 'dependabot[bot]' }}
12        steps:
13
14          - name: Approve a PR
15            run: gh pr review --approve "$PR_URL"
16            env:
17              PR_URL: ${{github.event.pull_request.html_url}}
18              GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
19
20          - name: Enable auto-merge for Dependabot PRs
21            run: gh pr merge --auto --merge "$PR_URL"
22            env:
23              PR_URL: ${{github.event.pull_request.html_url}}
24              # The documentation incorrectly forgets `GITHUB_TOKEN` here.
25              GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
26

Above automation works, but I have a Branch protection rule that requires review from the Code Owners.

Is there a way to include github-actions to the CODEOWNERS file in order to make its approval counted?

ANSWER

Answered 2022-Jan-20 at 09:46

As of right now, a GitHub app cannot be added to CODEOWNERS as quoted here.

Thank you for being here! Currently, GitHub Apps can’t be used in CODEOWNERS – that’s not supported. It’s something the team is considering for the future, and I’ll be sure to add your use case to the internal feature request.

However, what you can do, is to use a GitHub personal access token generated by yourself as explained in the documentation here, then add it as a secret and use it in your workflow. See the GitHub Documentation .

The last step of your action would then reference your self-defined secret. In the below example, I assume it's called MYTOKEN

1    name: Dependabot auto-approve
2    on: pull_request_target
3    
4    permissions:
5      contents: write
6      pull-requests: write
7    
8    jobs:
9      dependabot:
10        runs-on: ubuntu-latest
11        if: ${{ github.actor == 'dependabot[bot]' }}
12        steps:
13
14          - name: Approve a PR
15            run: gh pr review --approve "$PR_URL"
16            env:
17              PR_URL: ${{github.event.pull_request.html_url}}
18              GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
19
20          - name: Enable auto-merge for Dependabot PRs
21            run: gh pr merge --auto --merge "$PR_URL"
22            env:
23              PR_URL: ${{github.event.pull_request.html_url}}
24              # The documentation incorrectly forgets `GITHUB_TOKEN` here.
25              GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
26          - name: Enable auto-merge for Dependabot PRs
27            run: gh pr merge --auto --merge "$PR_URL"
28            env:
29              PR_URL: ${{github.event.pull_request.html_url}}
30              # The documentation incorrectly forgets `GITHUB_TOKEN` here.
31              GITHUB_TOKEN: ${{secrets.MYTOKEN}}
32

With this approach, a merge would be done as your user, who is - I assume - part of the CODEOWNERS.

Source https://stackoverflow.com/questions/70664840

QUESTION

Powershell package missing/not working on release

Asked 2022-Jan-14 at 21:41

I have a console application project where i'm using the powershell SDK, it works perfectly fine in debug but on release, everything except powershell works.

The only settings i've found where it works is when releasing the project as framework dependent and portable. Or at least it works on my pc, on other computers it says the dotnet runtime is missing, even when installed via the link provided.

Using self contained, .net6-windows and win-x86 doesn't work. Not quite sure what could be wrong? I've tried cleaning the project, the solution, restarting visual studio and my PC. Everything works as expected in debug but when I publish, powershell just doesn't work.

1<Project Sdk="Microsoft.NET.Sdk.Worker">
2
3  <PropertyGroup>
4      <OutputType>Exe</OutputType>
5      <TargetFramework>net6.0-windows</TargetFramework>
6      <UseWindowsForms>true</UseWindowsForms>
7    <Nullable>enable</Nullable>
8    <ImplicitUsings>enable</ImplicitUsings>
9    <UserSecretsId>dotnet-SocketService-04A4D71F-C305-4A5B-BD0B-529C28B25DAD</UserSecretsId>
10    <PlatformTarget>AnyCPU</PlatformTarget>
11    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
12  </PropertyGroup>
13
14  <ItemGroup>
15    <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
16    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
17    <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.1" />
18    <PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.2" />
19    <PackageReference Include="System.Management" Version="6.0.0" />
20    <PackageReference Include="System.Management.Automation" Version="7.2.1" />
21  </ItemGroup>
22
23  <ItemGroup>
24    <Folder Include="Speedtest\" />
25  </ItemGroup>
26
27  <ItemGroup>
28    <None Update="Speedtest\speedtest.exe">
29      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
30    </None>
31  </ItemGroup>
32</Project>
33

Profile settings

enter image description here

EDIT:

I changed my powershell handler to use .EndInvoke(), now I finally get a proper error! I found an issue mentioning the error https://github.com/PowerShell/PowerShell/issues/7909 but installing Microsoft.Management.Infrastructure didn't resolve the issue, I installed version 2.0.0. If i try installing version 1 I get an error stating that the System.Management.Automation package requires a higher version (2.0.0)

1<Project Sdk="Microsoft.NET.Sdk.Worker">
2
3  <PropertyGroup>
4      <OutputType>Exe</OutputType>
5      <TargetFramework>net6.0-windows</TargetFramework>
6      <UseWindowsForms>true</UseWindowsForms>
7    <Nullable>enable</Nullable>
8    <ImplicitUsings>enable</ImplicitUsings>
9    <UserSecretsId>dotnet-SocketService-04A4D71F-C305-4A5B-BD0B-529C28B25DAD</UserSecretsId>
10    <PlatformTarget>AnyCPU</PlatformTarget>
11    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
12  </PropertyGroup>
13
14  <ItemGroup>
15    <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
16    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
17    <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.1" />
18    <PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.2" />
19    <PackageReference Include="System.Management" Version="6.0.0" />
20    <PackageReference Include="System.Management.Automation" Version="7.2.1" />
21  </ItemGroup>
22
23  <ItemGroup>
24    <Folder Include="Speedtest\" />
25  </ItemGroup>
26
27  <ItemGroup>
28    <None Update="Speedtest\speedtest.exe">
29      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
30    </None>
31  </ItemGroup>
32</Project>
33public static string CMD(string script)
34{
35    string errorMsg = "";
36    string output;
37
38  
39    ps.AddScript(script);
40
41    //Make sure return values are outputted to the stream captured by C#
42    ps.AddCommand("Out-String");
43
44    PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
45    ps.Streams.Error.DataAdded += (object sender, DataAddedEventArgs e) =>
46    { errorMsg = ((PSDataCollection<ErrorRecord>)sender)[e.Index].ToString(); };
47
48    IAsyncResult result = ps.BeginInvoke<PSObject, PSObject>(null, outputCollection);
49    ps.EndInvoke(result);
50
51    //while (!result.IsCompleted)
52    //    Thread.Sleep(300);
53
54    StringBuilder stringBuilder = new StringBuilder();
55    foreach (PSObject outputItem in outputCollection)
56    {
57        stringBuilder.AppendLine(outputItem.BaseObject.ToString());
58    }
59    output = stringBuilder.ToString();
60
61    //Clears commands added to runspace
62    ps.Commands.Clear();
63
64    if (!string.IsNullOrEmpty(errorMsg))
65        return string.Empty;
66
67    return output.Trim();
68}
69

Here is the error message

1<Project Sdk="Microsoft.NET.Sdk.Worker">
2
3  <PropertyGroup>
4      <OutputType>Exe</OutputType>
5      <TargetFramework>net6.0-windows</TargetFramework>
6      <UseWindowsForms>true</UseWindowsForms>
7    <Nullable>enable</Nullable>
8    <ImplicitUsings>enable</ImplicitUsings>
9    <UserSecretsId>dotnet-SocketService-04A4D71F-C305-4A5B-BD0B-529C28B25DAD</UserSecretsId>
10    <PlatformTarget>AnyCPU</PlatformTarget>
11    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
12  </PropertyGroup>
13
14  <ItemGroup>
15    <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
16    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
17    <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.1" />
18    <PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.2" />
19    <PackageReference Include="System.Management" Version="6.0.0" />
20    <PackageReference Include="System.Management.Automation" Version="7.2.1" />
21  </ItemGroup>
22
23  <ItemGroup>
24    <Folder Include="Speedtest\" />
25  </ItemGroup>
26
27  <ItemGroup>
28    <None Update="Speedtest\speedtest.exe">
29      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
30    </None>
31  </ItemGroup>
32</Project>
33public static string CMD(string script)
34{
35    string errorMsg = "";
36    string output;
37
38  
39    ps.AddScript(script);
40
41    //Make sure return values are outputted to the stream captured by C#
42    ps.AddCommand("Out-String");
43
44    PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
45    ps.Streams.Error.DataAdded += (object sender, DataAddedEventArgs e) =>
46    { errorMsg = ((PSDataCollection<ErrorRecord>)sender)[e.Index].ToString(); };
47
48    IAsyncResult result = ps.BeginInvoke<PSObject, PSObject>(null, outputCollection);
49    ps.EndInvoke(result);
50
51    //while (!result.IsCompleted)
52    //    Thread.Sleep(300);
53
54    StringBuilder stringBuilder = new StringBuilder();
55    foreach (PSObject outputItem in outputCollection)
56    {
57        stringBuilder.AppendLine(outputItem.BaseObject.ToString());
58    }
59    output = stringBuilder.ToString();
60
61    //Clears commands added to runspace
62    ps.Commands.Clear();
63
64    if (!string.IsNullOrEmpty(errorMsg))
65        return string.Empty;
66
67    return output.Trim();
68}
69Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Management.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Den angivne fil blev ikke fundet.
70File name: 'Microsoft.Management.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
71   at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
72   at System.Management.Automation.PowerShell.EndInvoke(IAsyncResult asyncResult)
73   at SocketService.PowerShellHandler.CMD(String script) in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Handlers\PowershellHandler.cs:line 35
74   at SocketService.Classes.SystemInfo..ctor() in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Classes\SystemInfo.cs:line 21
75   at SocketService.CommandHandler.Initialize() in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Handlers\CommandHandler.cs:line 31
76   at SocketService.SocketService..ctor() in C:\Users\Blue\source\repos\SocketClientProject\Clientside\SocketService.cs:line 27
77   at SocketService.WindowsBackgroundService.StartAsync(CancellationToken cancellationToken) in C:\Users\Blue\source\repos\SocketClientProject\Clientside\WindowsBackgroundService.cs:line 17
78   at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
79   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
80   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
81   at Program.<Main>$(String[] args) in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Program.cs:line 14
82   at Program.<Main>(String[] args)
83
84[process exited with code 3762504530]
85

Line 14 is me calling PowerShell.Create();

ANSWER

Answered 2022-Jan-14 at 20:16

Without showing actual code and giving a more descriptive detailing about what's going on aside from "it doesn't work" it's difficult to say exactly what is occurring here but I'll do my best.

Thankfully, according to Microsoft's documentation you most certainly can run the Powershell SDK in a self-contained .Net application.

A self-contained .NET application can use Microsoft.PowerShell.SDK to run arbitrary PowerShell functionality without depending on any external PowerShell installations or libraries.

This leads me to believe that you may not be having an issue with the SDK itself but rather with the compiler.

Single-File deployments

I noticed in your screenshot that you are attempting to perform a single-file deployment. You could potentially be having a few issues here. One is to ensure that you're not using an incompatible API. If you are calling any of these within your application, that could be a factor:

  • Assembly.CodeBase
  • Assembly.EscapedCodeBase
  • Assembly.GetFile
  • Assembly.GetFiles
  • Assembly.Location
  • AssemblyName.CodeBase
  • AssemblyName.EscapedCodeBase
  • Module.FullyQualifiedName
  • Module.Name

As none of these are compatible with single-file deployments.

Trimming

Another issue you may be experiencing is referred to as trimming. This is where the compiler will 'trim' unused assemblies from the project at compile time and tends to happen on release runs. While I believe this is off by default you can add the following to your .csproj file to ensure that trimming is disabled:

1<Project Sdk="Microsoft.NET.Sdk.Worker">
2
3  <PropertyGroup>
4      <OutputType>Exe</OutputType>
5      <TargetFramework>net6.0-windows</TargetFramework>
6      <UseWindowsForms>true</UseWindowsForms>
7    <Nullable>enable</Nullable>
8    <ImplicitUsings>enable</ImplicitUsings>
9    <UserSecretsId>dotnet-SocketService-04A4D71F-C305-4A5B-BD0B-529C28B25DAD</UserSecretsId>
10    <PlatformTarget>AnyCPU</PlatformTarget>
11    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
12  </PropertyGroup>
13
14  <ItemGroup>
15    <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
16    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
17    <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.1" />
18    <PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.2" />
19    <PackageReference Include="System.Management" Version="6.0.0" />
20    <PackageReference Include="System.Management.Automation" Version="7.2.1" />
21  </ItemGroup>
22
23  <ItemGroup>
24    <Folder Include="Speedtest\" />
25  </ItemGroup>
26
27  <ItemGroup>
28    <None Update="Speedtest\speedtest.exe">
29      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
30    </None>
31  </ItemGroup>
32</Project>
33public static string CMD(string script)
34{
35    string errorMsg = "";
36    string output;
37
38  
39    ps.AddScript(script);
40
41    //Make sure return values are outputted to the stream captured by C#
42    ps.AddCommand("Out-String");
43
44    PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
45    ps.Streams.Error.DataAdded += (object sender, DataAddedEventArgs e) =>
46    { errorMsg = ((PSDataCollection<ErrorRecord>)sender)[e.Index].ToString(); };
47
48    IAsyncResult result = ps.BeginInvoke<PSObject, PSObject>(null, outputCollection);
49    ps.EndInvoke(result);
50
51    //while (!result.IsCompleted)
52    //    Thread.Sleep(300);
53
54    StringBuilder stringBuilder = new StringBuilder();
55    foreach (PSObject outputItem in outputCollection)
56    {
57        stringBuilder.AppendLine(outputItem.BaseObject.ToString());
58    }
59    output = stringBuilder.ToString();
60
61    //Clears commands added to runspace
62    ps.Commands.Clear();
63
64    if (!string.IsNullOrEmpty(errorMsg))
65        return string.Empty;
66
67    return output.Trim();
68}
69Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Management.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Den angivne fil blev ikke fundet.
70File name: 'Microsoft.Management.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
71   at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
72   at System.Management.Automation.PowerShell.EndInvoke(IAsyncResult asyncResult)
73   at SocketService.PowerShellHandler.CMD(String script) in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Handlers\PowershellHandler.cs:line 35
74   at SocketService.Classes.SystemInfo..ctor() in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Classes\SystemInfo.cs:line 21
75   at SocketService.CommandHandler.Initialize() in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Handlers\CommandHandler.cs:line 31
76   at SocketService.SocketService..ctor() in C:\Users\Blue\source\repos\SocketClientProject\Clientside\SocketService.cs:line 27
77   at SocketService.WindowsBackgroundService.StartAsync(CancellationToken cancellationToken) in C:\Users\Blue\source\repos\SocketClientProject\Clientside\WindowsBackgroundService.cs:line 17
78   at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
79   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
80   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
81   at Program.<Main>$(String[] args) in C:\Users\Blue\source\repos\SocketClientProject\Clientside\Program.cs:line 14
82   at Program.<Main>(String[] args)
83
84[process exited with code 3762504530]
85<PropertyGroup>
86    <PublishTrimmed>false</PublishTrimmed>
87</PropertyGroup>
88

Optimizing

The JIT compiler tends to try to optimize code on release builds. When we run an application in debug mode the application is optimized for debugging the code. It tries to leave everything almost exactly as you wrote it with maybe some minor differences. When an application is run in release mode the actual code that is being run can be drastically different while maintianing the same logic. This is usually to try and make the final assembly as small and fast as possible. You can disable this optimization by the following steps:

  1. Right click on project
  2. Click "properties"
  3. Go to "Build"
  4. Under the section "general" deactivate "Optimize Code"

optimizecode

Other than the above mentioned possible causes I can't think of much more I can offer without seeing code, or error messages, or further details.

Source https://stackoverflow.com/questions/70643435

QUESTION

Has Variant behavior changed in Delphi 11?

Asked 2022-Jan-11 at 21:34

In Delphi 10.3, I had written some Excel automation code. I used variants. When the routine was finished, I cleared and freeAndNil the Variant...

1  VarClear(arrData);
2  FreeAndNil(arrData);
3

This compiled and ran fine. I have just upgraded to D11, i.e. Alexandria. This code now gives an error. ... Incompatible Type: TObject and Variant.

I rewrote this portion of code to be:

1  VarClear(arrData);
2  FreeAndNil(arrData);
3  VarClear(arrData);
4  arrData.Free;
5

This compiles, and at first glance, seems to run fine. Is this the proper way to clear/dispose of variants in Alexandria?

ANSWER

Answered 2022-Jan-11 at 19:50

Both of these code snippets are wrong. You don't call Free on a variant. You call Free on an object instance. Simply remove that line.

Source https://stackoverflow.com/questions/70672205

QUESTION

New-CimSession without elevation by providing admin credentials on Windows 10?

Asked 2021-Dec-31 at 13:43

I need to query some WMI values using PowerShell from Windows 10 devices. The script is executed in the context of a non-admin user by some software distribution tooling.

There is a local admin account, and for the current purpose (retrieving information before wiping the system) it wouldn't be a problem to put the password in the script. As automation is a hard requirement, there is no way to deal with UAC windows or the user to enter some credentials.

Is there any way to get

1$sess = New-CimSession -Credential $admincred
2

to work without running into Access is denied, because it isn't run in an elevated context? Can I somehow self-elevate it by just having the admin credentials?

[Edit]

The comments asked to provide more concrete information:

I want to onboard many unmanaged (i.e. no software distribution tool, no domain join) Windows 10 devices to Windows Autopilot.

  • The devices are not at a specific site.

  • The device vendor can't provide the information.

  • The users don't have administrative privileges

  • The users don't know the local admin password (I do)

  • Exposing the local admin password is less of a problem than the missing tech knowledge of the users (the password is considered legacy)

  • The firewall is preventing incoming traffic (no RDP, WinRM)

  • Code (Source):

    $devDetail = (Get-CimInstance -CimSession $session -Namespace root/cimv2/mdm/dmmap -Class MDM_DevDetail_Ext01 -Filter "InstanceID='Ext' AND ParentID='./DevDetail'")

It is too time consuming to get the information using manual remote sessions with a tool like Teamviewer. Getting the users to download a tool from the intranet and running it would be a way to go. So I created a standalone application that builds and runs a customized PowerShell script. What won't work is getting it to run in an elevated session. I always end up with Access denied.

ANSWER

Answered 2021-Dec-31 at 13:43

Can I somehow self-elevate it by just having the admin credentials?

No you cannot. UAC is designed to prevent exactly what you are trying to do. Related Q&A:

There may be many workarounds, but they all will have in common that you have to go to your machines (locally or remotely) at least once, gain administrative privileges and prepare something, e. g.:

  • A scheduled task that runs under your local administrator account or under SYSTEM and triggers the execution of your script
  • Disabling UAC (temporarily) (not recommended either way)
  • Installing any remote management software, services or accounts (with extra run as background job privilege)

Source https://stackoverflow.com/questions/70425086

QUESTION

Diagnostic setting not included in Azure Portal ARM template export

Asked 2021-Dec-17 at 08:39

I create a Diagnostic Settings for a KeyVault resource in Azure portal. DS properties are Metrics = AllMetrics and Destination is a predefined Log Analytics Workspace. When I do an export (Automation - Export Template) from Portal, nothing from the diagnostic setting is included in the generated ARM json. I've noticed the same behavior when resource is an App Service.

Is this by design? A bug? Any other way to get the ARM json for the diagnostic setting I've defined?

ANSWER

Answered 2021-Dec-17 at 08:39

I tried the same in my environment and seems we cannot export the diagnostics settings for any service like key vault, app service , storage account etc when we try to export the template for automation . But there are some sample Diagnostics settings Templates for few resources provided in Microsoft Documentation.

So , as per your settings it will something like below which I have tested by deploying :

1{
2        "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
3        "contentVersion": "1.0.0.0",
4        "parameters": {
5            "settingName": {
6                "type": "String",
7                "defaultValue": "testdsansuman"
8            },
9            "vaultName": {
10                "type": "String",
11                "defaultValue": "ansumantestkv1234"
12            },
13            "workspaceName": {
14                "type": "String",
15                "defaultValue": "ansumantestlog"    
16            } 
17        },
18        "resources": [
19            {
20              "type": "Microsoft.KeyVault/vaults/providers/diagnosticSettings",
21              "apiVersion": "2017-05-01-preview",
22              "name": "[concat(parameters('vaultName'), '/Microsoft.Insights/', parameters('settingName'))]",
23              "dependsOn": [],
24              "properties": {
25                "workspaceId": "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('WorkspaceName'))]",
26                
27                "metrics": [
28                  {
29                    "category": "AllMetrics",
30                    "enabled": true
31                  }
32                ]
33              }
34            }
35        ]
36    }
37

Output:

enter image description here

enter image description here

enter image description here

enter image description here

Source https://stackoverflow.com/questions/70200523

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Automation

Tutorials and Learning Resources are not available at this moment for Automation

Share this Page

share link

Get latest updates on Automation