I have a powershell function that calls a C# function app to enroll a device in Autopilot. I can't get it to work. I'm quite sure the problem lies with the hardware identifier binary blob. I tried every string format but I always get the same error
Here's how the hardware identifier is retreived in powershell
$devDetail = (Get-CimInstance -CimSession $session -Namespace root/cimv2/mdm/dmmap -Class MDM_DevDetail_Ext01 -Filter "InstanceID='Ext' AND ParentID='./DevDetail'")
if ($devDetail -and (-not $Force))
{
$hash = $devDetail.DeviceHardwareData
}
then the hash is sent in the body of a HTTP call along with some other info
Here's the relevant part of the C# function
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
string HI = data?.hardwareIdentifier;
var NouvelEquipement = new ImportedWindowsAutopilotDeviceIdentity {
GroupTag = req.Query["GroupTag"],
HardwareIdentifier = System.Text.Encoding.Unicode.GetBytes(HI),
SerialNumber = req.Query["SerialNumber"],
State = new ImportedWindowsAutopilotDeviceIdentityState {
DeviceImportStatus = ImportedWindowsAutopilotDeviceIdentityImportStatus.Pending,
DeviceErrorCode = 0,
}
};
var retour = await graphClient.DeviceManagement.ImportedWindowsAutopilotDeviceIdentities
.Request()
.AddAsync(NouvelEquipement);
I get the following error which isn't helpful.
2022-12-23T18:07:27.944 [Error] Executed 'AjoutEquipement' (Failed, Id=xxxxxxx, Duration=4062ms)Code: InternalErrorMessage: {"_version": 3,"Message": "An error has occurred - Operation ID (for customer support): 00000000-0000-0000-0000-000000000000 - Activity ID: xxxxxxxxxx - Url: https://fef.msua04.manage.microsoft.com/DeviceEnrollmentFE_2212/StatelessDeviceEnrollmentFEService/deviceManagement/importedWindowsAutopilotDeviceIdentities/microsoft.management.services.api.import?api-version=2021-01-22","CustomApiErrorPhrase": "","RetryAfter": null,"ErrorSourceService": "","HttpHeaders": "{}"}Inner error:AdditionalData:date: 2022-12-23T18:07:27request-id: xxxxxxxclient-request-id: xxxxxxxxxxxClientRequestId: xxxxxxxxxxx
I tried to convert the hardware Identifier string in every conceivable way to a byte array to no avail.
The problem is so obvious now that I solved it ...
The powershell line
$hash = $devDetail.DeviceHardwareData
already provide a base64 encoded string of the hardware signature. So the only changes needed in the C# function were
byte[] HI = data?.hardwareIdentifier; //instead of string HI = data?.hardwareIdentifier; json provides direct conversion of base64 to byte array
HardwareIdentifier = HI, // instead of System.Text.Encoding.Unicode.GetBytes(HI),
Related
I am using Azure Information Protection Unified Labeling client to label emails. We are still using PGP in our environment and emails classified strictly confidential must be PGP encrypted.
When the email is sent, I try to find out, how the email is classified and trigger PGP encryption, when the classification is strictly confidential. This is done in an Outlook VSTO c# Add-in.
To find out the classification, I read the email header property "msip_labels" which is set by AIP and contains all necessary information. I am using the following procedure to read the headers. The code is far away from being perfect. I am just figuring out, how to get the value.:
private void GetHeaders()
{
var mail = (Outlook.MailItem)Application.ActiveInspector().CurrentItem;
var propertyAccessor = mail.PropertyAccessor;
try
{
var custom = propertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/string/{00020386-0000-0000-C000-000000000046}/msip_labels");
}
catch(Exception ex)
{
var message = ex.Message;
}
}
I am able to read properties, set by another tool, but the AIP property is multiline. When the code is executed, I get the Error: Typeconflict. (Exception of HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
Is there a way, to read multivalue properties? Here is an example of the msip_labels property (GUIDs replaced with XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX):
msip_labels: MSIP_Label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_Enabled=true;
MSIP_Label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_SetDate=2019-11-14T07:16:38Z;
MSIP_Label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_Method=Privileged;
MSIP_Label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_Name=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX;
MSIP_Label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_SiteId=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX;
MSIP_Label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_ActionId=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX;
MSIP_Label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_ContentBits=1
msip_label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_enabled: true
msip_label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_setdate: 2019-11-14T07:16:48Z
msip_label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_method: Privileged
msip_label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_name:
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
msip_label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_siteid:
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
msip_label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_actionid:
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
msip_label_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_contentbits: 0
Finally I have figured out, how to create the property schema string, so it returns the right data type. Helpful for finding out the datatype was analyzing the item using Outlook Spy. The correct line of code with the right Schema String for querying msip_labels is:
var mSIPLabels = propertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/string/{00020386-0000-0000-C000-000000000046}/msip_labels/0x0000001F") as string;
after the property name, I had to pass the type descriptor 0x0000001F
And additional to this:
How to set a MIP Lablel to (Outlook VSTO) MailItem
public void SetMIP_LabelPublic(MailItem newMailItem)
{
var lblID = MipFileService.Label_Standard_Id; // <== your label ID
var tenantId = MipSettings.TenantId; //<== azur information tenant (your company) id
var mipMethod = "Privileged";
var dd = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.CreateSpecificCulture("en-us"));
var mipPropertyText = $"MSIP_Label_{lblID}_Enabled=true; "
+ $"MSIP_Label_{lblID}_SetDate={dd}; "
+ $"MSIP_Label_{lblID}_Method={mipMethod}; "
+ $"MSIP_Label_{lblID}_SiteId={tenantId}; ";
newMailItem.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/string/{00020386-0000-0000-C000-000000000046}/msip_labels/0x0000001F", mipPropertyText);
}
I'm trying to generate a JWT token using Jose.JWT.encode(payload, secretKey, JwsAlgorithm.ES256, header) (see https://github.com/dvsekhvalnov/jose-jwt) to use with Apple's new token-based APNs system.
The JWT encode method requires the secretKey to be in CngKey format.
Here's my code converting the .p8 file from Apple to a CngKey object:
var privateKeyContent = System.IO.File.ReadAllText(authKeyPath);
var privateKey = privateKeyContent.Split('\n')[1];
//convert the private key to CngKey object and generate JWT
var secretKeyFile = Convert.FromBase64String(privateKey);
var secretKey = CngKey.Import(secretKeyFile, CngKeyBlobFormat.Pkcs8PrivateBlob);
However, on the last line, the following error is thrown.
System.Security.Cryptography.CryptographicException was unhandled by user code
HResult=-2146885630
Message=An error occurred during encode or decode operation.
Source=System.Core
StackTrace:
at System.Security.Cryptography.NCryptNative.ImportKey(SafeNCryptProviderHandle provider, Byte[] keyBlob, String format)
at System.Security.Cryptography.CngKey.Import(Byte[] keyBlob, String curveName, CngKeyBlobFormat format, CngProvider provider)
at System.Security.Cryptography.CngKey.Import(Byte[] keyBlob, CngKeyBlobFormat format)
at tokenauthapi.App_Start.TokenInitSendMessage.<send>d__0.MoveNext() in C:\token-push-prototype\token-auth-api\token-auth-api\App_Start\TokenInitSendMessage.cs:line 31
InnerException:
The input isn't in the wrong format as there's a separate error for that (that appears when I change the blob type).
This code is running in a .NET WebApi v4.6.
I've searched high and low but haven't been able to decipher what this error is referring to. Any help would be greatly appreciated. Thank you.
The security key (p8) provided by Apple for DeviceCheck also contained newlines. I used the following to get a valid CngKey:
var privateKeyContent = File.ReadAllText("pathToApplePrivateKey.p8");
var privateKeyList = privateKeyContent.Split('\n').ToList();
var privateKey = privateKeyList.Where((s, i) => i != 0 && i != privateKeyList.Count - 1)
.Aggregate((agg, s) => agg + s);
CngKey key = CngKey.Import(Convert.FromBase64String(privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob);
Turns out the .p8 file I was using had newlines in the middle of it for some reason. Possible that notepad added it (and saved it?). I was splitting by newlines to get the private key and therefore it was truncating the key. Once I removed the newlines it worked fine.
If you get the error occurred during encode or decode operation error, check whether your .p8 (or other) private key is malformed and is the right length.
I met the same issue. I use this:
var privateKey = privateKeyContent.Split('\n')[1];
Then I analyze token file downloaded from Apple. I found there are more \n in the file. I am not sure where this format is different or apple changed.
Then I use the following codes to load the token, works.
Actually, we can directly use this token string.
var privateKeyContent = System.IO.File.ReadAllText(authKeyPath);
var privateKeyList = privateKeyContent.Split('\n');
int upperIndex = privateKeyList.Length;
StringBuilder sb = new StringBuilder();
for(int i= 1; i< upperIndex - 1; i++ )
{
sb.Append(privateKeyList[i]);
Debug.WriteLine(privateKeyList[i]);
}
I am trying to connect to a MS SQL database through Unity. However, when I try to open a connection, I get an IOException: Connection lost.
I have imported System.Data.dll from Unity\Editor\Data\Mono\lib\mono\2.0. I am using the following code:
using UnityEngine;
using System.Collections;
using System.Data.Sql;
using System.Data.SqlClient;
public class SQL_Controller : MonoBehaviour {
string conString = "Server=myaddress.com,port;" +
"Database=databasename;" +
"User ID=username;" +
"Password=password;";
public string GetStringFromSQL()
{
LoadConfig();
string result = "";
SqlConnection connection = new SqlConnection(conString);
connection.Open();
Debug.Log(connection.State);
SqlCommand Command = connection.CreateCommand();
Command.CommandText = "select * from Artykuly2";
SqlDataReader ThisReader = Command.ExecuteReader();
while (ThisReader.Read())
{
result = ThisReader.GetString(0);
}
ThisReader.Close();
connection.Close();
return result;
}
}
This is the error I get:
IOException: Connection lost
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacketHeader ()
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacket ()
Mono.Data.Tds.Protocol.TdsComm.GetByte ()
Mono.Data.Tds.Protocol.Tds.ProcessSubPacket ()
Mono.Data.Tds.Protocol.Tds.NextResult ()
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Rethrow as TdsInternalException: Server closed the connection.
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Mono.Data.Tds.Protocol.Tds70.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
Mono.Data.Tds.Protocol.Tds80.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
Please disregard any security risks with this approach, I NEED to do this for testing, security will come later.
Thank you for your time.
Please disregard any security risks with this approach
Do not do it like this. It doesn't matter if security will come before or after. You will end of re-writing the whole code because the password is hard-coded in your application which can be decompiled and retrieved easily. Do the connection the correct way now so that you won't have to re-write the whole application.
Run your database command on your server with php, perl or whatever language you are comfortable with but this should be done on the server.
From Unity, use the WWW or UnityWebRequest class to communicate with that script and then, you will be able to send and receive information from Unity to the server. There are many examples out there. Even with this, you still need to implement your own security but this is much more better than what you have now.
You can also receive data multiple with json.
Below is a complete example from this Unity wiki. It shows how to interact with a database in Unity using php on the server side and Unity + C# on the client side.
Server Side:
Add score with PDO:
<?php
// Configuration
$hostname = 'localhot';
$username = 'yourusername';
$password = 'yourpassword';
$database = 'yourdatabase';
$secretKey = "mySecretKey"; // Change this value to match the value stored in the client javascript below
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
} catch(PDOException $e) {
echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
$realHash = md5($_GET['name'] . $_GET['score'] . $secretKey);
if($realHash == $hash) {
$sth = $dbh->prepare('INSERT INTO scores VALUES (null, :name, :score)');
try {
$sth->execute($_GET);
} catch(Exception $e) {
echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
}
?>
Retrieve score with PDO:
<?php
// Configuration
$hostname = 'localhost';
$username = 'yourusername';
$password = 'yourpassword';
$database = 'yourdatabase';
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
} catch(PDOException $e) {
echo '<h1>An error has occurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
$sth = $dbh->query('SELECT * FROM scores ORDER BY score DESC LIMIT 5');
$sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $sth->fetchAll();
if(count($result) > 0) {
foreach($result as $r) {
echo $r['name'], "\t", $r['score'], "\n";
}
}
?>
Enable cross domain policy on the server:
This file should be named "crossdomain.xml" and placed in the root of your web server. Unity requires that websites you want to access via a WWW Request have a cross domain policy.
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>
Client/Unity Side:
The client code from Unity connects to the server, interacts with PDO and adds or retrieves score depending on which function is called. This client code is slightly modified to compile with the latest Unity version.
private string secretKey = "mySecretKey"; // Edit this value and make sure it's the same as the one stored on the server
public string addScoreURL = "http://localhost/unity_test/addscore.php?"; //be sure to add a ? to your url
public string highscoreURL = "http://localhost/unity_test/display.php";
//Text to display the result on
public Text statusText;
void Start()
{
StartCoroutine(GetScores());
}
// remember to use StartCoroutine when calling this function!
IEnumerator PostScores(string name, int score)
{
//This connects to a server side php script that will add the name and score to a MySQL DB.
// Supply it with a string representing the players name and the players score.
string hash = Md5Sum(name + score + secretKey);
string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash;
// Post the URL to the site and create a download object to get the result.
WWW hs_post = new WWW(post_url);
yield return hs_post; // Wait until the download is done
if (hs_post.error != null)
{
print("There was an error posting the high score: " + hs_post.error);
}
}
// Get the scores from the MySQL DB to display in a GUIText.
// remember to use StartCoroutine when calling this function!
IEnumerator GetScores()
{
statusText.text = "Loading Scores";
WWW hs_get = new WWW(highscoreURL);
yield return hs_get;
if (hs_get.error != null)
{
print("There was an error getting the high score: " + hs_get.error);
}
else
{
statusText.text = hs_get.text; // this is a GUIText that will display the scores in game.
}
}
public string Md5Sum(string strToEncrypt)
{
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
// encrypt bytes
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
// Convert the encrypted bytes back to a string (base 16)
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
This is just an example on how to properly do this. If you need to implement session feature and care about security, look into the OAuth 2.0 protocol. There should be existing libraries that will help get started with the OAuth protocol.
An alternative would be to create your own dedicated server in a command prompt to do your communication and connecting it to unity to Handel multiplayer and SQL communication. This way you can stick with it all being created in one language. But a pretty steep learning curve.
Unity is game engine.
so That's right what the answer says.
but, Some domains need to connect database directly.
You shouldn't do that access database directly in game domain.
Anyway, The problem is caused by NON-ENGLISH computer name.
I faced sort of following errors at before project.
IOException: Connection lost
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacketHeader ()
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacket ()
Mono.Data.Tds.Protocol.TdsComm.GetByte ()
Mono.Data.Tds.Protocol.Tds.ProcessSubPacket ()
Mono.Data.Tds.Protocol.Tds.NextResult ()
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Rethrow as TdsInternalException: Server closed the connection.
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Mono.Data.Tds.Protocol.Tds70.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
Mono.Data.Tds.Protocol.Tds80.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
And after changing computer name as ENGLISH, It works.
I don't know how it's going. But It works.
Mono's System.Data.dll has some issues in P.C has NON-ENGLISH Computer name.
So, at least Unity project.
You should tell your customer Do not set their computer name as NON-ENGLISH.
I don't know people in mono knows these issue or not.
---------- It's OK in after 2018 version ----------
Api Compatibility Level > .Net 4.x
You can connect database in Non-english computer name machine.
I am using RNCryptor in Swift and C#.NET . I need a cross platform AES encryption and because of this, I am using RNCryptor.
When I encrypt some plain text in Swift,I can decrypt it in Swift correctly without any error. But when I encrypt some text in C# and then I want to decrypt it in Swift,I got an error " The operation couldn’t be completed. (RNCryptorError error 2.)"
My code in C# :
public static string EncryptQRCode(string qrCodeString){
var qrEncryptor = new Encryptor ();
return qrEncryptor.Encrypt (qrCodeString, "password");
}
public static string DecryptQRCode(string qrEncryptedString){
var qrDecryptor = new Decryptor();
return qrDecryptor.Decrypt (qrEncryptedString, "password");
}
My Code in Swift:
func Encrypt(msg:String, pwd:String) -> String{
let data = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let chiper = RNCryptor.encryptData(data!, password: pwd)
let base = chiper.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let stringBase = String(data: base, encoding: NSUTF8StringEncoding)
return stringBase!
}
func Decrypt(msg:String, pwd:String) -> String{
let encodedData:NSData = NSData(base64EncodedString: msg, options: NSDataBase64DecodingOptions(rawValue: 0))!
do{
let decryptedData = try RNCryptor.decryptData(encodedData, password: pwd)
let decrypytedString = String(data: text, encoding: NSUTF8StringEncoding)
return decryptedString!
}
catch let error as NSError{
print(error.localizedDescription)
print(error.localizedDescription)
}
return "AN ERROR OCCURED"
}
For example:
"ABC", with password "behdad" in C#, Encryptor returned:
"AgHfT2VvVOorlux0Ms47K46fG5lQOP2YhYWq2KeIKh+MisCDqZfrLF+KsJyBR2EBNC3wQpaKev0X4+9uuC5vliVoHkLsEi6ZI7ZIZ8qVUEkYGQ=="
When I decrypt it in C#, it returned "ABC".
But when I pass this Base64Encoded string to my Swift Decryptor function,it returned:
RNCryptorError error 2.
For Example:
qrCodeString = "ABC".
public static string EncryptQRCode returns =
"AgF6P5Ya0SifSymd3LqKdH+kGMCFobiziUhwwB6/lfZgAA9N+F5h350MyigoKo9qgUpMXX3x9FxZXwUOJODL4is3R62EGvZWdJBzjSNCef7Ouw=="
The "msg" is returned data from EncryptQRCode(The Base64 Encoded String).
pwd = "password"
encoded data = <02017a3f 961ad128 9f4b299d dcba8a74 7fa418c0 85a1b8b3 894870c0 1ebf95f6 60000f4d f85e61df 9d0cca28 282a8f6a 814a4c5d 7df1f45c 595f050e 24e0cbe2 2b3747ad 841af656 7490738d 234279fe cebb>
decryptedString and decryptedData do not have values due to the error occurred.
RNCryptorError error 2
UnknownHeader = 2
Unrecognized data format. Usually this means the data is corrupt.
This means that the data passed is not in the correct format.
The best programming advice I ever got was one night in the computer room when I asked Rick Cullman for help and he said: "Read the documentation."
That is why I suggested displaying the inputs and outputs, you will catch that.
There are many places where hexadecimal is need to see what is happening and to debug.
Opened an issue in RNCryptor Swift to add the error codes to the documentation.
In C# when you want to encrypt the text,you have to use Schema.V3 for encryption. Decryptor in Swift cannot identify the Schema Version of Base 64 encoded string.
string encrypted = encryptor.Encrypt (YOUR_PLAIN_TEXT, YOUR_PASSWORD,Schema.V3);
I have recently began using C# to invoke powershell scripts, with some success :)
$spWeb = Get-SPWeb -Identity http://127.0.0.1
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
$spWeb.Lists.Add($args, "", $listTemplate) > $myDirectory
$spWeb.Lists.Add returns a SharePoint GUID.
Question:
I simply wish to pass in the directory/filename in which the GUID will
be written. How could that be done?
I have posted on the MSDN forums here: http://goo.gl/5p0oz but have continued my search on stackoverflow due to a seemingly dead end thread. This post is a cumulative gathering of the information found through MSDN responses.
You can try using the Set-Content cmdlet instead, like this. You need to pass the $myFile as a string and Set-Content will do the rest for you -
Inside your script i.e. MyScript.ps1 here, you will have this piece of code -
param([string]$parameter, [string]$myFile)
try
{
$spWeb = Get-SPWeb -Identity http://127.0.0.1
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
$guid = $spWeb.Lists.Add($parameter, "", $listTemplate)
$guid | Set-Content $myFile
}
catch
{
throw ("Failed. The error was: '{0}'." -f $_ )
}
How to Run:
Open Powershell Prompt and type this
.\MyScript.ps1 "someparam1" "D:\Output.txt"
C# Bit -
private PowerShell _ps;
_ps = PowerShell.Create();
var parameter = new List<string>
{
parameter,
myFile
};
var sr = new StreamReader(#"C:\MyScript.ps1");
_ps.AddScript(sr.ReadToEnd()).AddParameters(parameter);
_ps.Invoke();