Returning Return in PowerShell

Hey all,
I'm trying to write a function in PowerShell where before running the onClick handler it does some basic error checking and if it finds an error to exit the onClickHandler. But it's not returning my return command like I'm used to in LUA.
So this is my onClick function:
$FindButtonClick = {
    If (!$InputBox.Text) { $inputBoxText = $Null }
    errorCheck $chosenIDType $inputBoxText $chosenDB $AuditDB.checked
    Get-AdPartition $chosenIDType $InputBox.Text $chosenDB -audit:$AuditDB.checked
Here is the errorCheck function that gets called
function global:errorCheck ($chosenIDType, $InputBox, $chosenDB, $AuditCB) {
    If ($chosenIDType -eq "Unchosen") {
        $errorMSG = "No Lookup Type Chosen.`nPlease choose a Lookup Type and try again."
        $errorReason = "NoIDError"
        $isError = $True
    } ElseIf ($InputBox -eq $Null) {
        $errorMSG = "No" + $chosenIDType +"entered.`nPlease enter an ID in the text box."
        $errorReason = "NoLookUpError"
        $isError = $True
    If ($isError) {
        errorNotice $errorMSG $errorReason #This function opens an error dialog
        return return
I'm trying to make it so that if $isError resolves to $True that it returns "return" so that the Get-AdPartition Cmdlet in my onClick doesn't run. The error I'm getting just tells me "return : The term 'return' is not recognized as the name
of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."
Any ideas?

Meh, works in LUA. I was starting to think that PS wouldn't return commands but wanted to verify. Thanks for the answer and thanks for being a jerk about it.
Don't get sore if I am a better jerk than you.
YOu definitely need a course in the fundamentals of Windows.  LUA has nothing to do with anything.  No language returbs a command including LUA.  InOPosweershell we canreturn code like this:
return { return }
On the recieveing end we would do this:
$(errorCheck).Invoke()
But this is totally bogus in any language.  Just test the result.  Functions should never
provoke code in another module.  It is unsafe and unnecessary although some lame language inventors who no longer exist have attempted to sell this snake oil.
Get with the program. Computer science has moved way beyond this tripe in the last 20years.  Stay away from the evangelists.  They will give you ulcers and take all of your money.
¯\_(ツ)_/¯

Similar Messages

  • Return powershell Function variable back to VBScript

    Hey Scripting Guy,
    I have a vbscript function that I use to call a Powershell Function. I need to return the powershell output back to the calling vbscript. I've tried different methods but I can only get return codes (either 1 or 0) back to the calling vbscript function and
    not the string value itself.
    Here is the code:
    vbscript-
    Function GetDomain(ByVal username As String) As String
    Dim strCmd, ReturnDomain As String
    Dim objshell
    strCmd = "C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -file c:\temp\Get-Infosec2.ps1" & "'" & username & "'"
    Set objshell = CreateObject("Wscript.shell")
    ReturnDomain = objshell.Run(strCmd)
    GetDomain = ReturnDomain
    Set objshell = Nothing
    End Function
    Powershell -
    Function
    Get-Infosec2{
    [cmdletbinding()]
    Param(
    [parameter()]
    [string]$name
    # Add the Quest ActiveRoles snapin for easier AD management; but first check if it's already loaded.
    $SnapIn
    =
    "Quest.ActiveRoles.ADManagement"
    If
    (Get-PSSnapin
    $SnapIn
    -ea
    "silentlycontinue") {
    write-Host
    "Quest ActiveRoles plugin already loaded. Continuing ..."
    elseIf (get-PSSnapin
    $SnapIn
    -registered
    -ea
    "silentlycontinue") {
    write-Warning
    "Quest ActiveRoles plugin registered but not loaded. Loading."
    Add-PSSnapin
    $SnapIn
    else {
    write-Host
    "PS Snapin
    $SnapInnot found."
    -foregroundcolor
    Red
    Write-host
    $ldapFilter
    $domainname
    =
    Get-QADUser
    -Identity
    $name
    -Properties
    dn   
    -SizeLimit

    |
    select-object
    dn
    $newstring
    =
    $domainname
    -split ("DC")
    $newstring1
    =
    $newstring[0]
    $newstring2
    =
    $newstring[1]
    $domainname
    =
    $newstring2.Substring(0,$newstring2.Length-1)
    $domainname
    =
    $domainname.Substring(1)
    $domainname
     The result that I am trying to achieve is getting the value of $domainname back to the calling vbscript function.
    Any Idea what I am doing wrong?

    Why don't you just use VB to get the domain.  You can get it directly.  No need for PowerShell.
    This is a scripting forum and you are codeing in VB not VBScript. You need to post your questions in the VB developers forum.
    In VB.Net you can just use the CurrentDomian static method of the DirectoryServices class.
    ¯\_(ツ)_/¯

  • Error Using New-WebServiceProxy cmdlet with SQL Agent Powershell Subsystem

    I created a powershell script to connect to SSRS via web service so I can cache reports in the database and expose them directly through our application. The script works fine when I run it through Powershell directly, but when I try running it through the
    SQL Agent Powershell subsystem I am getting a strange error:
    "A job step received an error at line 61 in a PowerShell script. The corresponding line is '$RS = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $reportServerURI -UseDefaultCredential  '. Correct the script and reschedule the job. The error
    information returned by PowerShell is: 'Could not load file or assembly 'file:///C:\WINDOWS\TEMP\yfqiivtg.dll' or one of its dependencies. The system cannot find the file specified.  '.  Process Exit Code -1.  The step failed."
    I am using SQL Server 2014, SSRS 2014, Windows 8.1. The only difference I can think of is that when I run Powershell from the OS, I am using v 4.0 whereas when I run it from SQL Agent it loads v 2.0. My understanding is that v 2.0 supports the New-WebServiceProxy
    cmdlet, so I'm not convinced the version discrepancy is the culprit. Any ideas what might be causing this?
    On a side note, is there a way to have SQL Agent use Powershell 4.0 for the subsystem? v 2.0 feels a little dated for SQL Server 2014.

    Hi WilliamW,
    When creating a PowerShell job step, there is only one security context available, which is the "SQL Server Agent Service Account." That means that if you intend to execute PowerShell scripts from SQL Agent Job steps, the SQL Server Agent
    service account must have appropriate permissions.
    According to your error message, I recommend to check if the SQL Server Agent service account has access to the folder where the scripts live, as well as the folder C:\WINDOWS\TEMP.
    In addition, when we execute a PowerShell job step in SQL Server, SQL Server Agent subsystem run the sqlps utility, and the sqlps utility launches PowerShell 2.0 and imports the sqlps module. If you need to run a PowerShell v4.0 script from a SQL Server
    Agent job, you can create a proxy account to run the agent job which contains PowerShell script. For more details, please review this similar blog:
    Run a PowerShell v3 Script From a SQL Server Agent Job.
    Thanks,
    Lydia Zhang

  • PowerShell Script to get Memory\Available MBytes

    I have a SQL Agent job with 3 separate Operating System Command Steps.
    PowerShell.exe Get-Date
    PowerShell.exe Get-Counter "\\mmserver\Memory\Pages/sec" | Format-table -auto
    PowerShell.exe Get-Counter "\\myserver\Memory\Available MBytes" | Format-Table -auto
    The first two steps work fine.  The third fails.  I have tried reformatting the counter name in any number of ways including escaping the backslashes, adding single quotes around various pieces, and I tried creating a string variable for the counter
    name.
    The failure message varies a little depending on what I change but basically it seems to be trying to interpret "MBytes" as a separate parameter.  For example:
    The error information returned by PowerShell is: 'Get-Counter : A positional parameter cannot be found that accepts argument 'MBy  '
    Followed immediately in the log file with a second error on the remainder of the command string.
    The error information returned by PowerShell is: 'tes'.  At line:1 char:12  + Get-Counter <<<< 
    \\myserver\Memory\Available MBytes      + CategoryInfo          : InvalidArgument: (:) [Get-Counter], ParameterBindingException    '
    Other errors indicate the name of the counter is wrong in someway.  For example, I found I had to include the server name even though the script is running locally and it works find from the ISE.
    I appreciate any assistance :)
    Ray

    Here's what worked for me from a command prompt, though I'm not sure why you were seeing that behavior when the value appeared to be quoted properly. Maybe cmd.exe and/or SQL Server was stripping the quotes before sending the string to PowerShell.exe:
    PowerShell.exe "Get-Counter '\\myserver\Memory\Available MBytes' | Format-Table -auto"

  • PowerShell - scripting - skip Encrypted\CLR Stored Procedures

    Hi all,
    Forgot where I got the code below from but, how would I skip Encrypted\CLR procedures because, I get error below...
    Message
    Executed as user: Loginname A job step received an error at line 81 in a PowerShell script. The corresponding line is '
    $MyScripter.Script($proc)|out-null'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Exception calling "Script" with "1" argument(s): "The StoredProcedure '[dbo].[myrpocname]'
    cannot be scripted as its data is not accessible."  '.  Process Exit Code -1.  The step failed.
    #STORED PROCEDURES
    if($procs -ne $null)
    foreach ($proc in $procs)
    #Assuming that all non-system stored procs have proper naming convention and don''t use prefixes like "sp_"
    if ( $proc.Name.IndexOf("sp_") -eq -1 -and $proc.Name.IndexOf("xp_") -eq -1 -and $proc.Name.IndexOf("dt_") -eq -1)
    $fileName = $proc.name
    "Scripting SP $fileName"
    $scriptfile = "$rootDrive\DatabaseScripts\$sqlDatabaseName\$strDate\StoredProcedures\$filename.sql"
    New-Item $rootDrive\DatabaseScripts -type directory -force | out-null
    New-Item $rootDrive\DatabaseScripts\$sqlDatabaseName -type directory -force | out-null
    New-Item $rootDrive\DatabaseScripts\$sqlDatabaseName\$strDate -type directory -force | out-null
    New-Item $rootDrive\DatabaseScripts\$sqlDatabaseName\$strDate\StoredProcedures -type directory -force | out-null
    # SetScriptOptions
    $MyScripter.Options.FileName = $scriptfile
    #AppendTofile has to be ''true'' in order that all the procs'' scripts will be appended at the end
    $MyScripter.Options.AppendToFile = "true"
    $MyScripter.Script($proc)|out-null
    Thanks
    gv
    Sword

    You can exclude encrypted stored procedure using $_.IsEncrypted member.
    $storedProcs = $db.StoredProcedures | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject -and  -not $_.IsEncrypted}
    $server = "localhost"
    $database = "PowerSQL"
    $output_path = "F:\PowerSQL\"
    $schema = "dbo"
    $storedProcs_path = "$output_path\StoredProcedure\"
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
    $srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $server
    $db = New-Object ("Microsoft.SqlServer.Management.SMO.Database")
    $tbl = New-Object ("Microsoft.SqlServer.Management.SMO.Table")
    $scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($server)
    # Get the database and table objects
    $db = $srv.Databases[$database]
    $storedProcs = $db.StoredProcedures | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject -and -not $_.IsEncrypted}
    # Set scripter options to ensure only data is scripted
    $scripter.Options.ScriptSchema = $true;
    $scripter.Options.ScriptData = $false;
    #Exclude GOs after every line
    $scripter.Options.NoCommandTerminator = $false;
    $scripter.Options.ToFileOnly = $true
    $scripter.Options.AllowSystemObjects = $false
    $scripter.Options.Permissions = $true
    $scripter.Options.DriAllConstraints = $true
    $scripter.Options.SchemaQualify = $true
    $scripter.Options.AnsiFile = $true
    $scripter.Options.EnforceScriptingOptions = $true
    function CopyObjectsToFiles($objects, $outDir) {
    if (-not (Test-Path $outDir)) {
    [System.IO.Directory]::CreateDirectory($outDir)
    foreach ($o in $objects) {
    if ($o -ne $null) {
    $schemaPrefix = ""
    if ($o.Schema -ne $null -and $o.Schema -ne "") {
    $schemaPrefix = $o.Schema + "."
    $scripter.Options.FileName = $outDir + $schemaPrefix + $o.Name + ".sql"
    Write-Host "Writing " $scripter.Options.FileName -ErrorAction silentlycontinue
    $scripter.EnumScript($o)
    # Output the scripts
    CopyObjectsToFiles $storedProcs $storedProcs_path
    Write-Host "Finished at" (Get-Date)
    -Prashanth

  • SQL Server upgradation Issue : 2012 to 2014. A job step received an error at line 1 in a PowerShell script. The corresponding line is 'set-executionpolicy RemoteSigned -scope process -Force'. Correct the script and reschedule the job.

    Message
    Executed as user: CORPTST\XXXXX. A job step received an error at line 1 in a PowerShell script. The corresponding line is 'set-executionpolicy RemoteSigned -scope process -Force'. Correct the script and reschedule the job. The error information returned
    by PowerShell is: 'Security error.  '.  Process Exit Code -1.  The step failed.
    I receive this error during the sql server job 'syspolicy_purge_history' execution  when sql server got upgraded form SQL Server 2008 to 2014.

    Hi Vishnu,
    According to the error message, it also occurs in SQL Server 2012.  Here is a feedback about the error in the link below.
    https://connect.microsoft.com/SQLServer/feedback/details/754063/sql-server-2012-syspolicy-purge-history-job-step-3-fails-with-security-error
    To resolve this issue, please change the value of the following registry key from ‘RemoteSigned’ to ‘Unrestricted’. For more details, you can review this similar
    blog.
    HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps120\ExecutionPolicy
    Thanks,
    Lydia Zhang

  • Fails when executing job called syspolicy_purge_history (SQL Server 2012)

    Hi friends i have the following  problem
    The job syspolicy_purge_history  of my database engine failed, specifically on the third step called "Erase Phantom System Health Records" that executes a powershell.  This is the sentence that executes (All job syspolicy_purge_history
    on any SQL 2012 has the same code):
    if ('$(ESCAPE_SQUOTE(INST))' -eq 'MSSQLSERVER') {$a = '\DEFAULT'} ELSE {$a = ''};
    (Get-Item SQLSERVER:\SQLPolicy\$(ESCAPE_NONE(SRVR))$a).EraseSystemHealthPhantomRecords()
    .  When i see the job history i get the following:
    Message
    Executed as user: NT Service\SQLSERVERAGENT. The job script encountered the following errors. These errors did not stop the script:  A job step received an error at line 1 in a PowerShell script. The corresponding line is 'import-module SQLPS  -DisableNameChecking'.
    Correct the script and reschedule the job. The error information returned by PowerShell is: 'The specified module 'SQLPS' was not loaded because no valid module file was found in any module directory.  '  A job step received an error at line 2 in
    a PowerShell script. The corresponding line is '(Get-Item SQLSERVER:\SQLPolicy\SRV01236$a).EraseSystemHealthPhantomRecords()'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Cannot find drive. A drive with the
    name 'SQLSERVER' does not exist.  '  A job step received an error at line 2 in a PowerShell script. The corresponding line is '(Get-Item SQLSERVER:\SQLPolicy\SRV01236$a).EraseSystemHealthPhantomRecords()'. Correct the script and reschedule the job.
    The error information returned by PowerShell is: 'You cannot call a method on a null-valued expression.  '.  Process Exit Code -1.  The step failed.
    Aditionally i tested putting the policies in powershell like unrestricted (like i see on a blog). but it didn't work.
    My SQL version is 2012 Standard SP1 X64
    Please help me with this
    Thanks for your help
    Greetings
    Aleds

    Thanks for your help princekumar8 and gona_david
    Hello Gona_david,  You are right, when i execute the powershell sentence Get-Module -ListAvailable
    the SQLPS module doesn't appear. 
    Look i have another SQL Server 2012 in another server, but this is patched on SP2 and the syspolicy_purge_history here runs OK.  Also when i execute the powershell, the SQLPS appears in the list.
    So, my question is: If i patch my server SQL Server 2012 with the error from SP1 to SP2, is Possible that the error will get away? In fact, Wouldn't be yet necessary runs the SQL install? 
    Basically what you recommend me in this case?
    Thanks in advance 
    Greetings 
    Aleds

  • Syspolicy_purge_history job getting failed (SQL Server 2012)

    Job Name  syspolicy_purge_history
    Step Name  Erase Phantom System Health Records.
    Duration  00:00:05
    Sql Severity 0
    Sql Message ID 0
    Operator Emailed 
    Operator Net sent 
    Operator Paged 
    Retries Attempted 0
    Error Message :-
    A job step received an error at line 1 in a PowerShell script. The corresponding line is 'import-module SQLPS  -DisableNameChecking'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'The following error occurred
    while loading the extended type data file:
    Microsoft.PowerShell, D:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules\SQLPS\sqlprovider.types.ps1xml : File skipped because of the following validation exception: AuthorizationManager check failed..

    Hi nap_bhatt,
    Based on your description, we need to verify that if you get the error while starting the syspolicy_purge_history job manually in SQL Server 2012. If so, which account do you use to log on to the SQL Server instance and run the job?
    According to the error message “AuthorizationManager check failed” , it indicates that your account has no permission to execute the PowerShell script in SQL Server Agent job. To troubleshoot this issue, please make sure that your account has permissions
    to the SQLPS folder and it has rights to execute the PowerShell script.
    In addition, please use the “Get-ExecutionPolicy” PowerShell command to check the current status of execution policy, if the execution policy is set to “Restricted”, try to set it to “RemoteSigned” or “Unrestricted”. Please note that you need to set this
    execution policy in both the Windows PowerShell  and the SQL PowerShell consoles.
    For more information about syspolicy_purge_history job in SQL Server 2012,  please review this similar blog:
    SQL job “syspolicy_purge_history” fails on SQL 2012 .
    Thanks,
    Lydia Zhang

  • Poweshell quick help needed

    earlier this job was running fine and all of sudden started failing on this step.
    this step was added to script out daily the jobs on my server and now after year successful run sudden started failing by below error:
    A job step received an error at line 22 in a PowerShell script. The corresponding line is '$job.Script() | Out-File -filepath $FileName'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'The given path's format
    is not supported.  '.  Process Exit Code -1.  The step failed.
    code i m using is as below,
    [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo') | Out-Null
    $serverInstance = "testserver"
    $server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $serverInstance
    $jobs = $server.JobServer.Jobs
    #$jobs = $server.JobServer.Jobs | where-object {$_.category -eq "[your category]"}
    if ($jobs -ne $null)
    $serverInstance = $serverInstance.Replace("\", "-")
    $AllJobs = "G:\jobs\log\SQLBackupJobs\" + $serverInstance + "_AllJobs.sql"
    $server.JobServer.Jobs | foreach {$_.Script()} | out-file -filepath $AllJobs
    ForEach ( $job in $jobs )
    $FileName = "d:\test\" + $serverInstance + "_" + $job.Name + ".sql"
    $job.Script() | Out-File -filepath $FileName

    The error information returned by PowerShell is: 'The given path's format is not supported.  '.
    $FileName = "d:\test\" + $serverInstance + "_" + $job.Name + ".sql"
    Then one of the job names contains a character which is not allowed for a file name, e.g. a slash, double point etc.
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • SQL Server 2012 syspolicy_purge_history fails step 3 "Erase Phantom System Health Records."

    I recently installed SQL Server 2012 Ent (x64). The install is a stand alone default instance.
    The syspolicy_purge_history job fails on step three with the following error:
    Executed as user: <DomainName>\sql_xxx_agt_svc. A job step received an error at line 1 in a PowerShell script. The corresponding line is 'set-executionpolicy RemoteSigned -scope process -Force'. Correct the script and reschedule the job. The error
    information returned by PowerShell is: 'Security error.  '.  Process Exit Code -1.  The step failed.
    Here is the code that is in the step:
    if ('$(ESCAPE_SQUOTE(INST))' -eq 'MSSQLSERVER') {$a = '\DEFAULT'} ELSE {$a = ''};
    (Get-Item SQLSERVER:\SQLPolicy\$(ESCAPE_NONE(SRVR))$a).EraseSystemHealthPhantomRecords()
    The domain user is the account that SQL Agent is running as.
    What permissions need to be granted to this account?
    Here is the link to the Connect post:
    https://connect.microsoft.com/SQLServer/feedback/details/754063/sql-server-2012-syspolicy-purge-history-job-step-3-fails-with-security-error

    I'm putting this in the connect post as well, but putting here in case somoene else comes across it.
    I was having the same problem with the syspolicy_purge_history job right after a standalone SQL 2012 (with SP1 and cu4,
    11.0.3368.0 (X64)) install that happened to be on a cluster but was not going to be a clustered instance. After trying all the different suggestions here around the ExecutionPolicy, I was still getting nowhere.
    Turns out, having a named isntance with a static port number and the SQL Browser service disabled was causing my problems. Apparently that was not allowing PowerShell to find the SQL instance. When I would navigate the SQLSERVER:\SQLPolicy folder
    in PowerShell (sqlps), I could get to the server root, but not the instance. If I even tried to list the subdirectories under the server folder, I would get an error:
    PS SQLSERVER:\> cd .\SQLPolicy\SRVR
    PS SQLSERVER:\SQLPolicy\SRVR> ls
    WARNING: 'INST' not available: Failed to connect to server. --> A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
    PS SQLSERVER:\SQLPolicy\SRVR> cd .\INST
    cd : Failed to connect to server .
    At line:1 char:3
    + cd <<<< .\INST
    + CategoryInfo : NotSpecified: (:) [Set-Location], ConnectionFailureException
    + FullyQualifiedErrorId : Microsoft.SqlServer.Management.Common.ConnectionFailureException,Microsoft.PowerShell.Commands.SetLocationCommand
    To solve this issue, I had to open SQL Server Configuration Manager and create an alias under the SQL Native Client 11.0 Configuration (I didn't need to set the 32-bit one):
    Alias
    [server name]\[instance name]
    Port
    [my static port]
    Protocol
    TCP/IP
    Server
    [server name]\[instance name]
    Once this was done, I was able to set the ExecutionPolicy registry settings, and the job completed. Here are my registry settings:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\ExecutionPolicy = Restricted
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps110\ExecutionPolicy = RemoteSigned
    From PowerShell (as Admin):
    PS C:\Windows\system32> Get-ExecutionPolicy -list
    Scope ExecutionPolicy
    MachinePolicy Undefined
    UserPolicy Undefined
    Process Undefined
    CurrentUser Undefined
    LocalMachine Restricted
    PS SQLSERVER:\> Get-ExecutionPolicy -list
    Scope ExecutionPolicy
    MachinePolicy Undefined
    UserPolicy Undefined
    Process RemoteSigned
    CurrentUser Undefined
    LocalMachine Restricted

  • Exchange Powershell return value from Get-command to variable.

    Hi
    I am trying to create a powershell-script for our monitoring-software.
    The script is supposed to establish a connection to our exchange-server mgmt-shell and execute this command:
    "Get-MailboxDatabaseCopyStatus"
    I have the connection in place, but am missing the knowledge of how to return the result of the command to my script, which I can then pass to our monitoring-software.
    (The script take 2 parameters - host and command eg. exch01.domain and Get-MailboxDatabaseCopyStatus).
    Current code:
    $statusAlive = "ScriptRes:Host is alive:"
    $statusDead = "ScriptRes:No answer:"
    $statusUnknown = "ScriptRes:Unknown:"
    $statusNotResolved = "ScriptRes:Unknown host:"
    $statusOk = "ScriptRes:Ok:"
    $statusBad = "ScriptRes:Bad:"
    $statusBadContents = "ScriptRes:Bad contents:"
    $pass = cat C:\securestring.txt | convertto-securestring
    $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "domain\administrator",$pass
    $host = $args[0]
    $command = $args[1]
    <#
    if (!$args[0]) {
    echo $statusUnknown"Host parameter is empty"
    exit
    if (!$args[1]) {
    echo $statusUnknown"Command parameter is empty"
    exit
    #>
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$host/powershell -Credential $cred
    Import-PSSession $session
    $command
    Remove-PSSession $session
    Now, how do I "catch" the value of the executed command and return it to a variable in the script?
    Best Regards,
    Soren

    Hmm.. doesnt seem to work quite right.
    I added "Echo $result" after "Remove-PSSession $session", but then I just get a bunch of information..
    Script tmp_c3a1c132-f4d9-4d61... {Get-IRMConfiguration, New-MailUser, Get-PublicFolderMigrationRequestSta...
    RunspaceId : 2d179364-2df3-483d-a192-f5f4ca9453bb
    Identity : DB02 - Specielle\EXCHANGE01
    Id : DB02 - Specielle\EXCHANGE01
    Name : DB02 - Specielle\EXCHANGE01
    DatabaseName : DB02 - Specielle
    Status : Mounted
    InstanceStartTime : 01-03-2014 03:35:07
    LastStatusTransitionTime :
    MailboxServer : EXCHANGE01
    ActiveDatabaseCopy : EXCHANGE01
    ActiveCopy : True
    ActivationPreference : 1
    StatusRetrievedTime : 11-03-2014 08:30:15
    WorkerProcessId : 8124
    ActivationSuspended : False
    ActionInitiator : Unknown
    ErrorMessage :
    ErrorEventId :
    ExtendedErrorInfo :
    SuspendComment :
    RequiredLogsPresent :
    SinglePageRestore : 0
    ContentIndexState : Healthy
    ContentIndexErrorMessage :
    ContentIndexVersion : 1
    ContentIndexBacklog : 0
    ContentIndexRetryQueueSize : 0
    ContentIndexMailboxesToCrawl :
    ContentIndexSeedingPercent :
    ContentIndexSeedingSource :
    CopyQueueLength : 0
    ReplayQueueLength : 0
    ReplaySuspended : False
    ResumeBlocked : False
    ReseedBlocked : False
    MinimumSupportedDatabaseSchemaVersion : 0.121
    MaximumSupportedDatabaseSchemaVersion : 0.125
    RequestedDatabaseSchemaVersion : 0.125
    LatestAvailableLogTime :
    LastCopyNotificationedLogTime :
    LastCopiedLogTime :
    LastInspectedLogTime :
    LastReplayedLogTime :
    LastLogGenerated : 0
    LastLogCopyNotified : 0
    LastLogCopied : 0
    LastLogInspected : 0
    LastLogReplayed : 0
    LowestLogPresent : 0
    LastLogInfoIsStale : False
    LastLogInfoFromCopierTime :
    LastLogInfoFromClusterTime :
    LastLogInfoFromClusterGen : 0
    LogsReplayedSinceInstanceStart : 0
    LogsCopiedSinceInstanceStart : 0
    LatestFullBackupTime :
    LatestIncrementalBackupTime :
    LatestDifferentialBackupTime :
    LatestCopyBackupTime :
    SnapshotBackup :
    SnapshotLatestFullBackup :
    SnapshotLatestIncrementalBackup :
    SnapshotLatestDifferentialBackup :
    SnapshotLatestCopyBackup :
    LogReplayQueueIncreasing : False
    LogCopyQueueIncreasing : False
    ReplayLagStatus :
    DatabaseSeedStatus :
    OutstandingDumpsterRequests : {}
    OutgoingConnections :
    IncomingLogCopyingNetwork :
    SeedingNetwork :
    DiskFreeSpacePercent : 50
    DiskFreeSpace : 20.02 GB (21,498,761,216 bytes)
    DiskTotalSpace : 40 GB (42,946,523,136 bytes)
    ExchangeVolumeMountPoint :
    DatabaseVolumeMountPoint : E:\
    DatabaseVolumeName : \\?\Volume{e6cb407f-e4f2-11e2-93eb-005056ae239d}\
    DatabasePathIsOnMountedFolder : False
    LogVolumeMountPoint : F:\
    LogVolumeName : \\?\Volume{e6cb4087-e4f2-11e2-93eb-005056ae239d}\
    LogPathIsOnMountedFolder : False
    LastDatabaseVolumeName :
    LastDatabaseVolumeNameTransitionTime :
    VolumeInfoError :
    IsValid : True
    ObjectState : Unchanged
    RunspaceId : 2d179364-2df3-483d-a192-f5f4ca9453bb
    Identity : DB01 - Standard\EXCHANGE01
    Id : DB01 - Standard\EXCHANGE01
    Name : DB01 - Standard\EXCHANGE01
    DatabaseName : DB01 - Standard
    Status : Mounted
    InstanceStartTime : 01-03-2014 03:35:07
    LastStatusTransitionTime :
    MailboxServer : EXCHANGE01
    ActiveDatabaseCopy : EXCHANGE01
    ActiveCopy : True
    ActivationPreference : 1
    StatusRetrievedTime : 11-03-2014 08:30:15
    WorkerProcessId : 8140
    ActivationSuspended : False
    ActionInitiator : Unknown
    ErrorMessage :
    ErrorEventId :
    ExtendedErrorInfo :
    SuspendComment :
    RequiredLogsPresent :
    SinglePageRestore : 0
    ContentIndexState : Healthy
    ContentIndexErrorMessage :
    ContentIndexVersion : 1
    ContentIndexBacklog : 3
    ContentIndexRetryQueueSize : 0
    ContentIndexMailboxesToCrawl :
    ContentIndexSeedingPercent :
    ContentIndexSeedingSource :
    CopyQueueLength : 0
    ReplayQueueLength : 0
    ReplaySuspended : False
    ResumeBlocked : False
    ReseedBlocked : False
    MinimumSupportedDatabaseSchemaVersion : 0.121
    MaximumSupportedDatabaseSchemaVersion : 0.125
    RequestedDatabaseSchemaVersion : 0.125
    LatestAvailableLogTime :
    LastCopyNotificationedLogTime :
    LastCopiedLogTime :
    LastInspectedLogTime :
    LastReplayedLogTime :
    LastLogGenerated : 0
    LastLogCopyNotified : 0
    LastLogCopied : 0
    LastLogInspected : 0
    LastLogReplayed : 0
    LowestLogPresent : 0
    LastLogInfoIsStale : False
    LastLogInfoFromCopierTime :
    LastLogInfoFromClusterTime :
    LastLogInfoFromClusterGen : 0
    LogsReplayedSinceInstanceStart : 0
    LogsCopiedSinceInstanceStart : 0
    LatestFullBackupTime :
    LatestIncrementalBackupTime :
    LatestDifferentialBackupTime :
    LatestCopyBackupTime :
    SnapshotBackup :
    SnapshotLatestFullBackup :
    SnapshotLatestIncrementalBackup :
    SnapshotLatestDifferentialBackup :
    SnapshotLatestCopyBackup :
    LogReplayQueueIncreasing : False
    LogCopyQueueIncreasing : False
    ReplayLagStatus :
    DatabaseSeedStatus :
    OutstandingDumpsterRequests : {}
    OutgoingConnections :
    IncomingLogCopyingNetwork :
    SeedingNetwork :
    DiskFreeSpacePercent : 50
    DiskFreeSpace : 20.02 GB (21,498,761,216 bytes)
    DiskTotalSpace : 40 GB (42,946,523,136 bytes)
    ExchangeVolumeMountPoint :
    DatabaseVolumeMountPoint : E:\
    DatabaseVolumeName : \\?\Volume{e6cb407f-e4f2-11e2-93eb-005056ae239d}\
    DatabasePathIsOnMountedFolder : False
    LogVolumeMountPoint : F:\
    LogVolumeName : \\?\Volume{e6cb4087-e4f2-11e2-93eb-005056ae239d}\
    LogPathIsOnMountedFolder : False
    LastDatabaseVolumeName :
    LastDatabaseVolumeNameTransitionTime :
    VolumeInfoError :
    IsValid : True
    ObjectState : Unchanged
    I am only interested in the 2 "ContentIndexState" - how can I pick these 2 out and put them into a variable?
    I though the command "Get-MailboxDatabaseCopyStatus" would only display these two, since it is what happens if I run the command inside PowerShell on the server itself.

  • Powershell Error for SharePoint Online -"The remote server returned an error: (407) Proxy Authentication Required."

    I am trying to call sharepoint online from powershell. Below is the code. I get 
    Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (407) Proxy Authentication Required."
    $loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
    $loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
    $webUrl = "ZZZZ"
    $username = "XXX"
    $password = "YYYY"
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl) 
    $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
    $web = $ctx.Web
    $lists = $web.Lists 
    $ctx.Load($lists)
    $ctx.ExecuteQuery()
    $lists| select -Property Title
    Raj-Shpt

    Hi,
    About how to access SharePoint online site using PowerShell, the blog below would be helpful:
    http://social.technet.microsoft.com/wiki/contents/articles/29518.csom-sharepoint-powershell-reference-and-example-codes.aspx
    Another two demos for your reference:
    http://www.hartsteve.com/2013/06/sharepoint-online-powershell/
    http://www.sharepointnutsandbolts.com/2013/12/Using-CSOM-in-PowerShell-scripts-with-Office365.html
    Thanks
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • TotalVHDCapacity attribute is returning zero in "Get-SCVMTemplate | select Name, TotalVhdCapacity" powershell command though the Vhd capacity is 20 gb in size, vmm 2012 r2

    Hi All,
    TotalVHDCapacity attribute is returning zero in "Get-SCVMTemplate | select Name, TotalVhdCapacity" powershell command though the template has Vhd capacity is 20 gb in size, vmm 2012 r2. I can create VM using this template too.
    For other templates it is returning correct value though.
    Can anyone help us understanding the root cause and the solution too.
    Thanks in advance.
    Debabrata

    I booted this drive from another computer (Asrock M3A770DE mobo) and works fine, speed with dd was ~100MB/s
    I also update bios on my first computer with Intel D945GSEJT (there is selected AHCI mode) still the same transfers with dd (~10Mb/s)
    I have no idea what to do with it now
    EDIT:
    More tests with other hdd (Samsung HD502IJ), dd on mounted NTFS partition:
    Intel D945GSEJT booted from Archlinux iso:
    hdparm: ~75 MB/s
    dd: ~10 MB/s
    Intel D945GSEJT booted from Archlinux iso, HDD connected to PCI SATA controller (Promise 378):
    hdparm: ~60 MB/s
    dd: ~10 MB/s
    Asrock M3A770DE booted from Archlinux iso:
    hdparm: ~87 MB/s
    dd: ~76 MB/s
    Asrock M3A770DE booted from Archlinux iso, HDD connected to PCI SATA controller (Promise 378):
    hdparm: ~81MB/s
    dd: ~76 MB/s
    What is broken on D945GSEJT?
    Last edited by miskoala (2012-03-30 13:47:23)

  • PowerShell command returned an exception. Unexpected token 's' in expression or statement

    Hi All,
    I am trying to Creating a VM based on a Template in VMM through Orchestrator Runbook using below URL;
    http://blogs.catapultsystems.com/lrayl/archive/2013/07/03/orchestrator-system-center-integrations-part-3-creating-a-vm-based-on-a-template-in-vmm.aspx
    Runbook:
    But at the Create VM from Template activity runbook will failed:
    Throwing below error in while running runbook in Error Summary text:
    PowerShell command returned an exception. Unexpected token 's' in expression or statement.
    Exception: InvalidOperationException
    Target site: PSRunspaceInvoker.HandleInvokeException
    Stack trace:
       at Microsoft.SystemCenter.Orchestrator.Integration.PowerShellConnector.PSRunspaceInvoker.HandleInvokeException(Exception ex, ILogger logger)
       at Microsoft.SystemCenter.Orchestrator.Integration.PowerShellConnector.PSRunspaceInvoker.Invoke(RunspaceInvoke runspace, String script, ILogger logger)
       at Microsoft.SystemCenter.Orchestrator.Integration.PowerShellConnector.PSScriptRunner.Execute(String script)
       at Microsoft.SystemCenter.Orchestrator.Integration.VMM2012Domain.VM.CloneFromTemplate(String vmmServer, ParameterList inputParameters)
       at Microsoft.SystemCenter.Orchestrator.Integration.VMM2012QIK.VM.CloneFromTemplate.DoExecute(IActivityRequest request, ILogger logger)
       at Microsoft.SystemCenter.Orchestrator.Integration.VMM2012QIK.ActivityBase`2.Execute(IActivityRequest request, IActivityResponse response)
    Both Orchestrator & SCVMM powershell are set on Unrestricted powershell.
    Kindly suggest any solution or work around for resolution.
    Thanks Rahul$

    This may be a bit late and perhaps not even relevant but I came across this post when trying to solve an issue I had with a powershell script in Orchestrator. Maybe it will help you, or maybe it will help someone else.
    I was trying to create a connector between SCOM and our ticketing system. I wanted to export alert descriptions and in the process of testing I came across an alert description that had multiple lines and all kinds of crazy formatting. When I tried to assign
    the Published Data to a varialbe in my powershell script i would get an error "Unexpected token [a partial alert description] in expression or statement.". After looking at the actual alert description data and seeing that i was only getting some of it
    and not all of it it dawned on me that i somehow needed to escape out of all the crazy quoting, carriage returns, and special characters. to do that i assigned the Published Data to a variable in my powershell script as follows:
    $Description = @"
    {Description from "Get Alert"}
    Apparently the @" "@ is called a here-string. Somewhat interesting. Hope it helps you or someone else!

  • Re : Powershell does NOT return errorcode to CMD file thats invoking PS

    Hello there,
    I am trying to return the exit code from PS back to CMD file that invokes the PS. Funny thing is PS does print exit code as 1 but CMD files still shows errorlevel as 0..... not sure what is causing it. The catch block in PS , I attempted to make generic
    and seems catch the exception correctly and is also printing the errorcode as 1 in PS. but upon exit 1 in PS , CMD file still shows %ERRORCODE% as 0 !
    Appreciate suggestions on this.
    CMD File
    :DBLOGIN
    CALL login.cmd username
    if %errorlevel% == 1 goto badend
    SET PWORD=%PASS_WORD%
    :ADLOGIN
    CALL AD_login.cmd %5
    if %errorlevel% == 1 goto badend
    SET AD_PWORD=%AD_PASS_WORD%
    SET PS_DIR=%1
    SET ROOT_DIR=%2
    SET UNAME=%3
    SET CONNSTR=%4
    SET ELE_UNAME=%5
    SET GROUPNAME=%6
    SET GROUPDOMAINNAME=%7
    SET DIR=%8
    d:
    cd %ROOT_DIR%
    %PS_DIR% -File "%ROOT_DIR%\adsync.ps1" %UNAME% %PWORD% %CONNSTR% %ELE_UNAME% %AD_PWORD% %GROUPNAME% %GROUPDOMAINNAME% %DIR% 2>&1 | more
    echo error level is %ERRORLEVEL%
    if %ERRORLEVEL% NEQ 0 GOTO badend
    GOTO ENDPROC
    :badend
    REM BAD END %ERRORLEVEL%
    @ECHO OFF & ECHO. & DATE /T & TIME /T & ECHO. & @ECHO ON
    exit /B 55
    :ENDPROC
    REM ACCEPTABLE RETURN CODE FOUND
    REM Error Level - %ERRORLEVEL%
    @ECHO OFF & ECHO. & DATE /T & TIME /T & ECHO. & @ECHO ON
    EXIT /B 0
    The powershell code is : 
    Import-Module ActiveDirectory
    $returncode =0;
    try
    $forestName = ([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()).Name
    $ADsPath = [ADSI]"GC://$forestName"
    $Search = New-Object System.DirectoryServices.DirectorySearcher($ADsPath)
    $OraClientDir=$args[7];
    echo $OraClientDir;
    [Reflection.Assembly]::LoadFile("$($OraClientDir)Oracle.DataAccess.dll")
    $DBUserName=$args[0];
    $DBPassword=$args[1];
    $DBSourceName=$args[2];
    $eleuser=$args[3];
    echo $eleuser;
    $elepword=ConvertTo-SecureString -String $args[4] -AsPlainText -Force;
    echo $elepword;
    $Credentials=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $eleuser,$elepword;
    echo $Credentials;
    $ADGroupName=$args[5];
    echo $ADGroupName;
    $ADGroupServerName=$args[6];
    echo $ADGroupServerName;
    $ADGroupServerString="$($ADGroupName) -server ""$($ADGroupServerName)""" ;
    echo $ADGroupServerString;
    Write-Host \n;
    echo " Start time is : $(Get-Date -format "yyyy:MM:dd hh:mm:ss:tt") ";
    $con=New-Object Oracle.DataAccess.Client.OracleConnection("Data Source=$DBSourceName;User Id=$DBUserName;Password=$DBPassword")
    $con.open()
    $cmd=$con.CreateCommand()
    $cmd.CommandText="SELECT blah blah SQL"
    $rdr=$cmd.ExecuteReader()
    $found= $false;
    $counter=0;
    $counterNew=0;
    $group=Get-ADGroup $ADGroupName -server $ADGroupServerName;
    $members = @()
    Get-ADGroupMember -Identity $group | Select-Object -ExpandProperty sAMAccountName |ForEach-Object {$members += $_};
    $path="\logs\log_$(Get-Date -format yyyy_MM_dd_hh_mm_ss_tt).log";
    Write-Host "The total members in group " $group " are " $members.length;
    Add-Content -Path $path -Value ("The total members in group " + $group + " are " + $members.length ) -Force;
    while ($rdr.Read())
    for ($i=0;$i -lt $rdr.FieldCount ; $i++)
    $found= $false;
    $s=$rdr.GetValue($i);
    $Search.Filter = "(&(objectCategory=User)(SamAccountName=$s))"
    if ($Search.FindAll().Count -eq 0)
    Add-Content -Path $path -Value "The user $s does NOT exists in AD global catalog" -Force;
    Write-Host "The user : " $s "does NOT exists in AD global catalog" ;
    $counter++;
    else {
    try {
    foreach ($res in $Search.FindAll())
    $User = $res.GetDirectoryEntry();
    Add-Content -Path $path -Value ("The user " + $User.SamAccountName + " Found in AD global catalog") -Force;
    Write-Host "The user distinguished name is : " $User.DistinguishedName " Found in AD global catalog" ;
    $DC = $User.DistinguishedName.ToString();
    $DCString = $DC.SubString($DC.IndexOf("DC="));
    $FQDN = $DCString.replace("DC=","").replace(",",".");
    # Add-Content -Path $path -Value $FQDN -Force;
    $found = $true;
    if ( ($found) -and ($members -notcontains $s))
    $checkuser= Get-ADUser $User.SamAccountName.ToString() -Server $FQDN ;
    Add-ADGroupMember $group -Members $checkuser -Server $ADGroupServerName -Credential $Credentials;
    Add-Content -Path $path -Value ("Added user: " + $User.SamAccountName ) -Force ;
    Write-Host "Added user: " $User.SamAccountName;
    $counterNew++;
    } catch [Exception] {
    Write-Host $_.Exception.Message "is inner catch";
    $returncode =1;
    Add-Content -Path $path -Value "Total of : $counterNew users users have been added " -Force;
    Write-Host "Total of : $counterNew users users have been added to AD Group";
    Add-Content -Path $path -Value "Total of : $counter users do NOT exist in Windows AD global catalog";
    Write-Host "Total of : $counter users do NOT exist in Windows AD global catalog";
    catch [Exception] {
    Write-Host $_.Exception.Message "is outer catch";
    $returncode =1;
    Write-Host \n;
    echo " End time is : $(Get-Date -format "yyyy:MM:dd hh:mm:ss:tt") ";
    Write-Host "value of return code is " $returncode;
    exit $returncode;

    Maybe the webpages below can help someone compose a workaround
    https://connect.microsoft.com/PowerShell/feedback/details/750653/powershell-exe-doesn-t-return-correct-exit-codes-when-using-the-file-option
    https://connect.microsoft.com/PowerShell/feedback/details/750653/powershell-exe-doesn-t-return-correct-exit-codes-when-using-the-file-option#

Maybe you are looking for

  • Question about setting cookies and custom authentication

    I have a question about setting cookies. I have two different 'projects' in HTMLDB - we will call them App1 and App2. I also have two different connection configurations setup in the DADs.conf file. - we will call them Connect1 and Connect2. App1 is

  • IPhone sending user information to...?

    Hello all, I love my iPhone, but lately I have been haunted by the static interferences with it and my table-top speakers. However, that isn't the primary concern for now - I am concerned as to why the iPhone seems to be sending my information (witho

  • SGD's Apache Start very Slowly

    hello everyone. my sgd's Apache start very Slowly, it costs several hours to start _* I have been annoyed by that for several weeks.so I reinstall My OS and install SGD. but I cannot believe sgd's Apache still start very Slowly. my environment: OS:So

  • How do I import XDCAM 422 .mov files into PP CS6?

    Tried the Calibrated codec--no dice. Tried Media Encode--nada tostada. Tried just playing it in QT--got only sound and a black screen. What do I do?

  • Single-folio apps with Pro subscription

    Hello, Are there any limitations for publishing single-folio apps using Pro subscription? Can I publish unlimited number of single-folio apps then? If no, what could it cost? Thanks a lot!