Passing parameters with spaces to SCCM Run PowerShell Script task

I am working on an OS deployment task sequence in SCCM 2012 R2 with several Run PowerShell Script tasks.  Most of them run fine, but I am having trouble with the one I need to pass parameters to.
The parameters I need to pass are:
-ComputerOU "ou=All Workstations,dc=contoso,dc=com" -GroupDN "cn=Group1,ou=All Groups,dc=contoso,dc=com"
I have that line (with actual DNs) entered in Parameters of the task.
But when the script runs on the target machine, the values of the parameters in the script are truncated at the spaces.  $ComputerOU is set to "ou=All" and $GroupDN is set to "cn=Group1,ou=all"
What syntax should I be using the Parameters field of the Task in order to properly pass PowerShell parameter string values that include spaces?
Tim Curwick
MadWithPowerShell.com

Thank you, TC, but I am not calling the parameters from within PowerShell.
The parameters are in the settings of a task sequence task to be used by the task to launch a script.  The syntax I am using would be correct for use within PowerShell or from a command line or batch script, but SCCM appears to be doing some parsing
before or while it is passing them to the script, possibly dropping the quotes which causes mishandling of the spaces in the string values.
Historically, it is always challenging to give one application parameters to pass to another application, and the required syntax can get quite tricky when the two application handle quotes or spaces differently, or when the parent application wants to parse
something intended to be passed on as is to the child application.
I'm sure someone has already figured out what the syntax needs to be for doing this with an SCCM 'Run PowerShell Script" task, it's just one of those issues that is hard to Google effectively.
Any other ideas?
Tim Curwick
MadWithPowerShell.com

Similar Messages

  • Run Powershell Script task sequence

    Hi,
    Anyone have good documentation on how to use the Run PowerShell Script task sequence ?
    Thanks

    If you are just interested in running a powershell command without creating a package, you can do this with the the Command line step by using this format in the command line:
    PowerShell -ExecutionPolicy bypass -Command "& {your powershell commands}"
    Here is an example of a multiline command to increase the agents cache size. Notice the ";"'s which are used to delineate a new line.
    PowerShell -ExecutionPolicy bypass -Command "& {$UIResourceM gr = New-Object -ComObject UIResource.UIResourceMgr;$Cache = $UIResourceMgr.GetC acheInfo();$Cache.TotalSize = "20480"}"

  • RWCLIENT issue when passing parameters with spaces

    AS 10.2.0.2 on Sun Solaris 10. We have reports that are scheduled and sum of the parameters have spaces in the value. For example parm1=I am with spaces. We would then generate a command line that shows the parameter like rwclient.sh server=rep_serv report=report1 parm1=I am with spaces. This errors with numerous messages. I tried surrounding the value in single quotes like this rwclient.sh server=rep_serv report=report1 parm1='I am with spaces'. When running the quoted command the report server shows the parameter as parm1='I' am with spaces. We have the parameter page of the report as the first page which allows us to see what was actually used as parameters. Of course the data in the database has no value that matches with the single quotes so no data. I need to be able to pass a value with spaces and it actually show as a parameter with spaces. We do not have this issue when we can run with forms built-ins as you actually build a parameter list to pass. Thanks in advance.
    Edited by: gdaustin1 on Jan 26, 2012 8:03 AM

    It's a bit of both I guess. On a command line a space is used to separate switches and variables. Like this demo.bat:
    @echo off
    echo %1Results in:
    C:\Temp>demo.bat Hello World
    Hello
    C:\Temp>demo.bat "Hello World"
    "Hello World"If you want to remove the double quotes, you have to change your source code to:
    @echo off
    echo %~1Now you get:
    C:\Temp>demo.bat "Hello World"
    Hello World

  • Passing parameters with spaces in Oracle reports

    I hav a system that passes a query string to a servlet and generates an Oracle Report. All of the varibles worked Ok as long as they don't have spaces in them. Whenever a parameter with spaces is encountered,it generates an error. i tried to enclose it in single or double quotes but it didn't work. I also tried to insert the Url Encode for spaces which is %20 but it also generated an error. pls help me on this one...

    I suppose you're working with GET instead of POST. Try to use the POST method; this gives you the possibility to work with a URL without parameters behind the question mark. This might be the solution to your problem.

  • Using shell pass parameters with space to Java

    Hi friends,
    I have a shell script accepting parameters as below
    #!/bin/sh
    #test.sh
    ./setEnv.sh
    java -classpath $CP com.rky.Main *$@*
    CP=
    If I run the script like this ./test.sh -annotation "This is a problem".
    If shell pass the parameters to Java, the parameter "This is a problem" will recognized as 4 parameters by java. That's not what I want . I still need java use it as a whole parameter.
    Do you have any easy ideas to resolve this problem out of my java code?
    Thank you.

    yes, from the bash manpage:
           @      Expands to the positional parameters, starting from  one.   When
                  the  expansion  occurs  within  double  quotes,  each  parameter
                  expands to a separate word.  That is, "$@" is equivalent to "$1"
                  "$2"  ...   If the double-quoted expansion occurs within a word,
                  the expansion of the first parameter is joined with  the  begin-
                  ning  part  of  the original word, and the expansion of the last
                  parameter is joined with the last part  of  the  original  word.
                  When  there  are no positional parameters, "$@" and $@ expand to
                  nothing (i.e., they are removed).(your manpage could be a little different because of versions, and I got this from the manpage of bash on a mac. but the main things should apply)

  • Passing arguments with spaces through to asc.jar

    According to the docs, we can pass arguments through to llc using -fllvm-llc-opt.  Additionally, with llc we can pass arguments through to asc.jar using -ascopt.  Let's say I want to define an AS3 variable in my flascc swf/swc.  asc.jar says that I can do this using "-config <ns::name=value>".
    So it seems like I should be able to do this:
    gcc ... -fllvm-llc-opt=-ascopt=-config CONFIG::RELEASE=true
    But this doesn't work, as the "-config" parameter takes its next argument via a space and not an equals, which throws the whole thing off.  gcc thinks its another argument.  Trying it with spaces like this:
    gcc ... "-fllvm-llc-opt=-ascopt=-config CONFIG::RELEASE=true"
    also doesn't work.  The toolchain outputs:
    Error:
    LLVM ERROR: Failed to run /usr/bin/java with args:
    -Xmx1500M -jar /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/asc2.jar -merge -md -abcfuture -AS3
    -import /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/builtin.abc -import /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/playerglobal.abc -import /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/BinaryData.abc -import /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/Exit.abc -import /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/LongJmp.abc -import /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/ISpecialFile.abc -import /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/IBackingStore.abc -import /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/InMemoryBackingStore.abc -import /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/IVFS.abc -import /Users/asimmons/FlasCC_1.0/sdk/usr/bin/../../usr/lib/CModule.abc
    -config CONFIG::RELEASE=false -d /var/folders/cn/hjz9nbt53bdfpn1rzn6wdb900000gr/T//ccQPoczK.lto.2.as /var/folders/cn/hjz9nbt53bdfpn1rzn6wdb900000gr/T//ccZDGxMF.lto.1.as -outdir . -out output
    As you can see, the "-config" command made it to asc.jar.  What I think is happening is that its being passed to asc.jar as one argument (not two).  For example, I can copy-paste this command into bash and it will work-- just not when done from gcc.
    So: how do I pass arguments with spaces through to asc.jar?

    I believe you should be able to do this by splitting it across two fllvm-llc-opt flags:
    gcc ... -fllvm-llc-opt=-ascopt=-config -fllvm-llc-opt=-ascopt=CONFIG::release=true
    The Makefile in the 12_Stage3D sample that ships with the FlasCC SDK demonstrates this.

  • Passing parameter with space?

    How does java pass parameter value with spaces? e.g. url?param1=value with space .
    Is there any built in method like PHP's addslashes?
    Thanks.

    URLEncoder.encode("value with
    space","UTF-8")Also the core JSTL tag c:url will encode parameters with spaces, and of course there's the crude way of just using the + sign.

  • Call Paje jsp passing parameters with method post

    How can I call a jsp page with outputlink, passing parameters with method post ?
    Ex: I need that the word "?pNumMensagem=#{currentRow["NumMensagem"]}" not was exposed when a call P0077_2.jsp.
    <h:outputLink binding="#{P0077.hyperlink1}" id="hyperlink1" target="t1" value = "#{facesContext.externalContext.requestContextPath}/faces/P0077_2.jsp?pNumMensagem=#{currentRow["NumMensagem"]}">
    <h:outputText binding="#{P0077.outputText14}" id="outputText14" value="#{currentRow['NumMensagem']}"/>
    </h:outputLink>
    Thanks.
    Heitor.

    Any body have an idea ?

  • Issue with running powershell script in pssessions

    Hi Everyone,
    I am trying to run powershell script from remote machine using below commands
    C:\Users\user>"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
    -command "$s= New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
    http://Exchservername/PowerShell/ -Authentication Kerberos ; Import-PSsession $s; "C:\Failback.ps1"
    and Below is the failback.ps1.
    $mbxs = Get-MailboxDatabase | Sort Name
    ForEach($mbx in $mbxs)
    $MBdb=$mbx.Name $ServerHosting=$mbx.Server.Name
    if($mbx.activationPreference.value -eq 1)
    If ($ServerHosting -ne $ActivationPreference.Key.Name) 
    Move-ActiveMailboxDatabase $MBdb -ActivateOnServer $ActivationPreference.Key.Name -confirm:$False 
    Below is what i am getting.

    What is your question?  Are you pointing out the yellow text?  This is normal, and appears every time EMS is opened.
    I should also point out that Microsoft provides a script to re-balance databases, if that's what you're trying to accomplish:
    You can use the RedistributeActiveDatabases.ps1 script to balance the active mailbox databases copies across a DAG. This script moves databases between their copies in an attempt to have an equal number of mounted databases on each server in DAG. If required,
    the script also attempts to balance active databases across sites.
    https://technet.microsoft.com/en-us/library/dd335158(v=exchg.141).aspx
    Mike Crowley | MVP
    My Blog --
    Baseline Technologies

  • Running powershell script with customer parameters as a scheduled task

    tfl wrote:I guess I don't get why you are wanting thisMy regular tasks run,. and take data from data files. Want your batch to get processed today? Then add it to the queue file by 5:00 PM.. The task runs at 5:01 and works with whatever data is available. And if the file is empty, nothing happens each night. If you want to pass parameters like this, then why bother with a scheduled task? You'd need to remove the old one and add the new one each time. Which is extra work and complexity, especially if the task at hand is in any way 'dangerous' if run twice with the same data (ie you forget to change the task or remove it).I'm using a scheduled task to trigger the script, I'm using the "on event" trigger and then calling the script as an action. The method I was using before (calling via a bat file with the event Id hard coded into that"...

    Hi all,Having one of those hair pulling issues where something should work but for some reason its blindly refusing not to!I've created this script that is a bit of an extension to the email on eventID for task scheduled. It basically pulls out the various information from the actual event and fires off an email to our alerting team to investigate etc.That all works great, but what I'm now trying to do is get it to accept a custom parameter so the actual event ID its looking for doesn't have to be hard coded and can be passed to it via the commandline etc. I've got it all setup and work great but for the life of me can't get it to work correctly when set as a scheduled task. This is what the command basically looks like:powershell -executionpolicy bypass -command "& 'pathtofile\script.ps1' -evtid 8004"The latter part is the customer...
    This topic first appeared in the Spiceworks Community

  • SCCM 2012 application run Powershell script and return codes

    Hi,
    I created an new application (imported as MSI) in SCCM 2012R2. After import I changed the deployment type installation program to run a Powershell script: powershell.exe -ExecutionPolicy Unrestricted -File "Install FactSet 2013 5I.ps1
    My goal is to close some processes before installing the MSI. This works. But on a failure the application program also return code 0 (AppEnforce.log). Is it possible to pass the MSI return codes to SCCM.
    Maybe anyone had the same or idea's to solve this? Thanks in advance.
    Regards,
    Peter
    Powershell script code:
    $ExitCode=0
    Function
    Stop-RunningApplication{
    Param(
    [parameter(Mandatory
    =$true)]
    [string]$ProcessName#
    Specify process names separated by commas
    # Split multiple processes on a comma and join with the regex operator '|' to perform "or" match against
    multiple applications
    $processName=$processName-split(",")
    -join("|")
    $process=Get-Process|Where{
    $_.ProcessName
    -match$processName}
    |Stop-Process-Force
    #Stop running processes
    Stop-RunningApplication
    -ProcessName"excel,outlook,fdsw32,marquee,POWERPNT,WINWORD"
    #Install FactSet 2013 5I
    $ExitCode
    =(Start-Process".\FactSet_Setup_2013_5I_x644.msi"'/qn
    FACTSET_CLOSE_PROCESSES=1 /l*v C:\Temp\InstFac20135I.log'-Wait-Passthru).ExitCode
    Environment]::Exit($ExitCode)
    Peter vd Bosch

    It's really hard to tell from the code above because of the way it's listed, but are sure that even executes? I see at least one stray curly brace and a stray square bracket.
    For the Start-Process cmdlet, have you tried without the -passthru parameter?
    Also, using the actual parameters will make the code much more readable instead of relying on position.
    Jason | http://blog.configmgrftw.com | @jasonsandys

  • SCCM 2012 PowerShell script gets progressively slower with each machine added to a collection

    Firstly, I hope this question firs in this forum.
    I have a PowerShell script that I created the imports a CSV file and adds the machine names to a collection as a direct membership. There are 5000 machines total in the list. When the script first starts, the average per machine is just a few tenths of a
    second. Once it reaches about 10% the average is up to almost 4 seconds and that time is getting larger with each machine. I tried using the CMDLets for SCCM but they were even slower than the WMI seemed to be.
    What is the reason for this increase?
    Is there anything I can do to not have this happen?
    My script:
    $ErrorActionPreference= 'continue'
    $FilesInFolder = Get-ChildItem $PSScriptRoot
    $CSVFiles = $FilesInFolder | where {$_.extension -eq ".csv"}
    $SiteCode = "US1"
    Function AddToCollection-WithWMI
    ForEach ($File in $CSVFiles)
    $CollectionStart = Get-Date
    $CollectionName = $File.Name.TrimEnd(".csv")
    $PClist = Import-CSV $File.FullName
    Write-Host "Populating Collection: " $CollectionName
    $i = 1
    $PCRollingTime = New-Object System.TimeSpan
    ForEach($PC in $PClist)
    $PCStart = Get-Date
    $ResourceName = $PC.SerialNumber
    Write-Host $i "of" $PClist.Count
    $ResourceQuery = Get-WmiObject -Namespace "Root\SMS\Site_US1" -Class SMS_R_SYSTEM -Filter "Name = '$ResourceName'"
    $CollectionQuery = Get-WmiObject -Namespace "Root\SMS\Site_US1" -Class SMS_Collection -Filter "Name = '$CollectionName' and CollectionType='2'"
    $CollectionQuery.Get()
    IF($ResourceQuery -ne $null)
    #Create new direct membership rule
    $NewRule = ([WMIClass]"\\Localhost\root\SMS\Site_US1:SMS_CollectionRuleDirect").CreateInstance()
    $NewRule.ResourceClassName = "SMS_R_System"
    $NewRule.ResourceID = $ResourceQuery.ResourceID
    $NewRule.Rulename = $ResourceQuery.Name
    #Commit changes
    $CollectionQuery.CollectionRules += $NewRule.psobject.baseobject
    $CollectionQuery.Put() | Out-Null
    $NewRule = $null
    ELSE
    Write-Host "No Device ID found for: " $PC.SerialNumber
    $CollectionQuery = $null
    $ResourceQuery = $null
    $PCFinish = Get-Date
    $TimeSpan = New-TimeSpan -Start $PCStart -End $PCFinish
    $PCRollingTime = $TimeSpan + $PCRollingTime
    If(($i % 25) -eq 0)
    $CurrentAvgPerPC = $PCRollingTime.TotalSeconds / $i
    Write-Host "The current average is" $CurrentAvgPerPC "seconds."
    $SecondsToETA = ($CurrentAvgPerPC * ($PClist.Count - $i))
    $ETA = Get-Date
    $ETA = $ETA.AddSeconds($SecondsToETA)
    Write-Host "The Estimated time of complete is" $ETA
    If(($i % 250) -eq 0)
    $PCRollingTime
    $i++
    $CollectionQuery = Get-WmiObject -Namespace "Root\SMS\Site_US1" -Class SMS_Collection -Filter "Name = '$CollectionName' and CollectionType='2'"
    $CollectionQuery.Get()
    #Initiate the collection evaluator
    $CollectionQuery.RequestRefresh()
    $CollectionFinish = Get-Date
    AddToCollection-WithWMI

    I haven't checked the complete code, but it doesn't look very efficient. For example I would take the collection query out the loop for all the pcs, simply because it's always the same and would save you about 4999 queries.
    My Blog: http://www.petervanderwoude.nl/
    Follow me on twitter: pvanderwoude
    ^^ This 
    Additionally, you could likely replace most of the WMI calls you do with the built in SCCM PowerShell cmdlets.  The two lines below will check to see if a Device Object for a specific PC exists and if it does, adds it to your collection
    $PCID = Get-CMDevice -Name $PC.SerialNumber
    if ($PCID -ne $null) {
    Add-CMDeviceCollectionDirectMembershipRule -CollectionName $CollectionName -ResourceId $PCID
    If you want to check to see if the collection exists before trying to add devices to it, you can use the Get-CMDeviceCollection cmdlet.
    Get-CMDeviceCollection -Name $CollectionName
    Moo.

  • Run PowerShell script from C# writing to input pipe

    Hello,
    I am trying to run a PowerShell script from C# (I have no control over what's in the script). The script may have a prompt like "Press enter to continue". So my goal is:
    1. Get text output from the script (easy, many examples available)
    3. If output contains "Press enter to continue", write a blank line to the running script's pipe to make it finish its job and quit
    4. If output does contain that prompt, just let it exit by itself without sending any input
    Note that commands in this PS script also try to get at script's file path, so I can't read script from file and pass it as text. It has to be executed as a script so it knows where it's located.
    I have done this with .exes and batch files before. All you do in that case is process.StandardInput.WriteLine() which "types" enter into the input stream of script you are trying to control. But this does not work with Power Shell. How do I do this?
    I have tried using PS object model like so:
    using (Pipeline pipeline = runspace.CreatePipeline())
    Command command = new Command(scriptPS, true, true);
       pipeline.Commands.Add(command);
       pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
       pipeline.Input.Write("\n");
       Collection<PSObject> psresults = pipeline.Invoke();   //...
    But I get an error because the script prompts:
    "A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related
    commands from command types that do not support user interaction, such as Windows PowerShell workflows."
    I also tried using Process, and running PowerShell with -File switch to execute the script, then write to StandardInput with C#. I get no errors then, but the input is ignored and doesn't make it to PowerShell.
    Please help!

    No man, what kind of answer is that? You should have left it unanswered rather than waste people's time like this. I already seen those links before I posted my question. They address the issue of specifying script parameters, but not
    writing to the input pipe.
    Fortunately I did figure this out by writing a custom script host for PowerShell. Anyone interested can read about this in detail on MSDN (fortunately simple material with samples you can copy paste as I did, so this solution takes little time to implement).
    Implement PSHost interface. Nothing special here, just paste directly from MSDN sample and modify their SetShouldExit function definition to contain just a "return;". Here's the relevant link:
    http://msdn.microsoft.com/en-us/library/windows/desktop/ee706559(v=vs.85).aspx
    Implement PSHostUserInterface interface. This is the ticket to solving this problem
    (see below). Here's the MSDN link:
    http://msdn.microsoft.com/en-us/library/windows/desktop/ee706584(v=vs.85).aspx
    Implement PSHostRawUserInterface. This may not be required (not sure) but I did anyway. Nearly a direct paste from MSDN:
    http://msdn.microsoft.com/en-us/library/windows/desktop/ee706601(v=vs.85).aspx
    So, there are two PSHostUserInterface function implementations that are of particular interest. First is Prompt (read header comment to see why):
    /// <summary>
    /// When script attempts to get user input, we override it and give it input programmatically,
    /// by looking up within promptInput's dictionary<string,string> or lineInput array.
    /// PromptInput dictionary is mapped by input prompt (for example, return "" in response to "Press ENTER to continue")
    /// LineInput is a regular array, and each time the script wants to prompt for input we return the next line in that array;
    /// this works much like piping inputs from a regular text file in DOS command line.
    /// </summary>
    /// <param name="caption">The caption or title of the prompt.</param>
    /// <param name="message">The text of the prompt.</param>
    /// <param name="descriptions">A collection of FieldDescription objects that
    /// describe each field of the prompt.</param>
    /// <returns>Throws a NotImplementedException exception.</returns>
    public override Dictionary<string, PSObject> Prompt(string caption, string message, System.Collections.ObjectModel.Collection<FieldDescription> descriptions)
    Dictionary<string, PSObject> ret = new Dictionary<string, PSObject>();
    foreach (FieldDescription desc in descriptions)
    if (this.promptInput.Count != 0)
    ret[desc.Name] = new PSObject(this.promptInput[desc.Name] + "\r\n");
    else if (this.lineInput != null && this.currentLineInput >= 0 && this.currentLineInput < this.lineInput.Length)
    ret[desc.Name] = new PSObject(this.lineInput[this.currentLineInput++] + "\r\n");
    else
    if (desc.DefaultValue == null)
    ret[desc.Name] = new PSObject("\r\n");
    else
    ret[desc.Name] = new PSObject(desc.DefaultValue);
    return ret;
    Next is PromptForChoice. Here I opted to always return the default choice, but you could rewrite it to read from somewhere to "simulate" reading from input pipe just like the function above:
    public override int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection<ChoiceDescription> choices, int defaultChoice)
            return defaultChoice;
    Last but not least, here's a ReadLine implementation (again read header comment):
    /// <summary>
    /// If the LineInput is set, "read" the next line from line input string array, incrementing line pointer/// </summary>
    /// <returns>The characters that are entered by the user.</returns>
    public override string ReadLine()
    if (this.lineInput != null && this.currentLineInput >= 0 && this.currentLineInput < this.lineInput.Length)
    return this.lineInput[this.currentLineInput++];
    else
    return Console.ReadLine();
    Both are exposed as properties:
    /// <summary>
    /// Gets or sets the input pipe override
    /// </summary>
    public string Input
    get
    return string.Join("\n", this.lineInput);
    set
    if (value != null)
    this.lineInput = value.Split('\n');
    this.currentLineInput = 0;
    else
    this.lineInput = null;
    /// <summary>
    /// Gets or sets input pipe override for named prompts
    /// </summary>
    public Dictionary<string, string> PromptInput
    get
    return this.promptInput;
    set
    this.promptInput = value;
    And finally, here's how the whole shebang is used:
    /// <summary>
    /// Runs a powershell script, with input pipe arguments
    /// </summary>
    /// <param name="script">Path of the script to execute, or script text</param>
    /// <param name="inline">Whether or not to execute script text directly, or execute script from path</param>
    /// <param name="unrestricted">Whether or not to set unrestricted execution policy</param>
    /// <param name="parameters">Parameters to pass to the script command line</param>
    /// <param name="inputOverride">Input to pass into the script's input pipe</param>
    /// <param name="inputOverrideName">Input to pass into the script's input pipe, to each prompt by label</param>
    /// <returns>Output lines</returns>
    public static string PowerShell(string script, bool inline, bool unrestricted = false, Dictionary<string, string> parameters = null, string inputOverride = null, Dictionary<string, string> inputOverrideByName = null)
    string output = null;
    ScriptHost host = new ScriptHost();
    (host.UI as ScriptHostUserInterface).Input = inputOverride;
    (host.UI as ScriptHostUserInterface).PromptInput = inputOverrideByName;
    using (Runspace runspace = RunspaceFactory.CreateRunspace(host))
    runspace.Open();
    if (unrestricted)
    RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
    runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
    using (Pipeline pipeline = runspace.CreatePipeline())
    if (inline)
    pipeline.Commands.AddScript(script);
    else
    Command command = new Command(script, true, true);
    foreach (KeyValuePair<string, string> param in parameters)
    command.Parameters.Add(param.Key, param.Value);
    pipeline.Commands.Add(command);
    pipeline.Commands.Add("Out-String");
    pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
    Collection<PSObject> psresults = pipeline.Invoke();
    var sb = new StringBuilder();
    foreach (PSObject obj in psresults)
    sb.AppendLine(obj.ToString());
    output = sb.ToString();
    pipeline.Dispose();
    runspace.Close();
    return (host.UI as ScriptHostUserInterface).Output + "\r\n" + output;
    As you can see, I also did some magic with the .Output property. That just accumulates lines of text output by the script in every WriteXXX function implemented in your custom PSHostUserInterface. The end result of all this, is that if you have a script
    that has prompts, choices or reads from standard input, you can execute the script within the context of your custom script host written as above, to control precisely what strings are passed to it in response to prompts.
     

  • Need to run powershell script in a bat file

    I have a ps1 file with the following:
    Get-ADUser -Filter * -SearchBase "ou=<HOSPOU>,ou=Domain Users and Groups,dc=<hospdomain>,dc=local" -Properties Description,EmailAddress| Select-Object -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\<server>\home2$\information
    services\IS STAFF\Documentation\AD Info\smcusers.csv";
    I have a bat file:
    @ECHO OFF
    SET ThisScriptsDirectory=%~dp0
    SET PowerShellScriptPath=%ThisScriptsDirectory%smcusers.ps1
    %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command import-module ActiveDirectory "%PowerShellScriptPath%";
    But while it launches powershell with the AD module, It apparently cannot read the ps1 file.
    I get:
    H:\>C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command i
    mport-module ActiveDirectory "H:\smcusers.ps1";
    Import-Module : A positional parameter cannot be found that accepts argument 'H
    :\smcusers.ps1'.
    At line:1 char:14
    + import-module <<<<  ActiveDirectory H:\smcusers.ps1;
        + CategoryInfo          : InvalidArgument: (:) [Import-Module], ParameterB
       indingException
        + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
       .Commands.ImportModuleCommand
    I have tried to modify the parameters 
    %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command import-module ActiveDirectory -File "%PowerShellScriptPath%";
    Still no luck.
    I need to be able to run this as a scheduled task.
    Karon W

    Apparently I don't know where to put everything.
    I have a single line:
    %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-module ActiveDirectory; -Command {Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress|Select-Object
    -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\svr-resource2\home2$\information services\IS STAFF\Documentation\AD Info\smcusers.csv"}
    This is the response:
    H:\>C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-mod
    ule ActiveDirectory; -Command {Get-ADUser -Filter * -SearchBase "ou=Shannon Memo
    rial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Descripti
    on,EmailAddress  | Select-Object -Property Name,SamAccountName,Description,Email
    Address  | Export-Csv "\\svr-resource2\home2$\information services\IS STAFF\Docu
    mentation\AD Info\smcusers.csv"}
    'Select-Object' is not recognized as an internal or external command,
    operable program or batch file.
    I modified to 2 lines:
    %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-module ActiveDirectory;
    Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress|Select-Object -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\svr-resource2\home2$\information
    services\IS STAFF\Documentation\AD Info\smcusers.csv"
    This is the response:
    H:\>C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-mod
    ule ActiveDirectory;
    PS H:\> exit ************I had to type*****************
    H:\>Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Gr
    oups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress  | Select-O
    bject -Property Name,SamAccountName,Description,EmailAddress  | Export-Csv "\\sv
    r-resource2\home2$\information services\IS STAFF\Documentation\AD Info\smcusers.
    csv"
    'Get-ADUser' is not recognized as an internal or external command,
    operable program or batch file.
    If I paste the command in before I type exit, it works. 
    If I paste:
    %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-module ActiveDirectory;
    I am put in the ad powereshell
    Then I paste:
    Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress|Select-Object -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\svr-resource2\home2$\information
    services\IS STAFF\Documentation\AD Info\smcusers.csv"
    and I get the expected output.
    What do I need to have in the bat file so the 2nd line of the script will run? and where does it go?
    Karon W

  • Get-Item: Cannot find path ' ' because it does not exist. While running Powershell script.

    I am trying to run a PowerShell script to upload files into a SharePoint site in an Azure environment...the script works fine on my local machine, but every time I run it in Azure (remotely), I get errors. Here is what my simple script looks like...
    if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
    Write-Host "Loading Sharepoint Module "
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
    Add-PSSnapin -Name Microsoft.SharePoint.PowerShell
    if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell) -eq $null )
    Write-Host "Failed to load sharepoint snap-in. Could not proceed further, Aborting ..."
    Exit
    #Script settings
    $webUrl = "http://sampleWebUrl"
    $docLibraryName = "My Documents"
    $docLibraryUrlName = "My%20Documents"
    $localFolderPath = get-childitem "C:\Upload\Test Upload\My Documents\" -recurse
    $contentType = "ContenttType1"
    #Open web and library
    $web = Get-SPWeb $webUrl
    write-host "Web:" $web
    $docLibrary = $web.Lists[$docLibraryName]
    write-host "docLibrary:" $docLibrary
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
    write-host "files:" $files
    If ($contentType = "ContenttType1")
    #Open file
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
    # Gather the file name
    $FileName = $File.Name
    #remove file extension
    $NewName = [IO.Path]::GetFileNameWithoutExtension($FileName)
    #split the file name by the "-" character
    $FileNameArray = $NewName.split("_")
    $check = $FileNameArray.Length
    #Add file
    $folder = $web.getfolder($docLibrary.rootFolder.URL)
    write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
    $spItem = $spFile.Item
    write-host "Success"
    write-host "SP File:" $spFile
    write-host "SP Item" $spItem
    #populate columns
    $spItem["Column1"] = $FileNameArray[0]
    $spItem["Column2"] = $FileNameArray[1]
    $spItem.Update()
    $fileStream.Close();
    Again, I can run this on my local machine and it works just fine, but when I attempt to run it on the Azure environment I get this error...
    Get-Item : Cannot find path 'C:\powershellscripts\12653_B7045.PDF' because it does not exist.
    At C:\PowerShellScripts\Upload-FilesIntoSharePointTester.ps1:32 char:42
    +     $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
    +                                          ~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (C:\powershellscripts\12653_B7045.PDF:String) [Get-Item], ItemNotFoundException
        + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
    What strikes me first is the fact that the file its looking for is in the "C:\Upload\Test Upload\My Documents\" directory, but the error keeps saying "C:\powershellscripts\" which is where my script resides and not the files I want to
    upload into SharePoint. When I step through the code, all the variables are holding the correct values. The $localFolderPath shows the name of files that I am attempting to upload, so it recognizes them. But once I step through this particular line of code,
    the error occurs...
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
    Is this an error caused because I am remoting into the Azure environment? Has anyone dealt with this issue before? I would really appreciate the help. Thanks
    Update: quick thing I noticed is that these two lines of code are returning null values. Again, is this handled differently in Azure or remotely? I ask cause this is the way I know how to do this, locally.
    $docLibrary = $web.Lists[$docLibraryName]
    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()

    "...square brackets are wildcard characters in Windows PowerShell..."
    When you use cd without a parameter it uses the -Path parameter. In this case you'll have to escape the square brackets so they are not considered wildcards. Each of the commands in the first example does the exact same thing.
    cd 'Learn PowerShell `[Do Whatever`]'
    cd -Path 'Learn PowerShell `[Do Whatever`]'
    cd (or Set-Location) also has a literal path parameter (-LiteralPath) that does not require using an escape character (`) before each of the brackets. Hope this helps.
    cd -LiteralPath 'Learn PowerShell [Do Whatever]'

Maybe you are looking for

  • How to make a payment

    how do i make a payment

  • Msgs getting stucked in inbound queue

    Hi All, I am doing a jdbc- xi - ABAP proxy scenario. Data is coming into the R/3 via proxy but getting stucked up in inbound queue. When I go to the queue I can find entries with msg transaction recorded. When I manually execute the entry from the qu

  • Differences between Calendar and Reminders

    Hi, anybody can give help and let me know the differences between Calendar and Reminders? I found the Calendar got all functions of the Reminders. If I want to mark an appointment, which one I should choose? Calendar or Reminders?

  • Can Verizon add the pay date to the e-mail that is sent for billing reminder.

    Can Verizon add the pay date to the e-mail that is sent for billing reminder. Then you would have to sign on to look that up.   Your current bill   for your account ending in 4609-00001 is now available online in My Verizon   Total Balance Due:   $26

  • Signal and slot for java

    Hi all, I have implemented Qt's signal and slot here: http://sourceforge.net/projects/javasignalslot/ In case you are wondering what's "Qt's signal and slot", please read http://doc.trolltech.com/3.1/signalsandslots.html My version uses String as sig