简体   繁体   中英

Passing variables to powershell from C# : Output file location variables

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 ie 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM