PowerShell Script Module PreCache Ignores DefaultCommandPrefix in Manifest - Results in Tab Completion Errors

Refer to this thread for background...
https://social.technet.microsoft.com/Forums/windowsserver/en-US/6507710a-5648-4f52-8d46-3bf6c75ac7f3/module-function-name-resolution-issues-with-defaultcommandprefix?forum=winserverpowershell
The issue is when PowerShell auto loads the meta data into the CommandAnalysis cache it loads the functions defined in a script module (*.psm1) without consideration that a manifest file (*.psd1) may contain a DefaultCommandPrefix declaration. As a result
if a user attempts to enter a function using tab completion PowerShell will offer the name as defined in the script module which fails to execute (name not recognized). Importing the module will make the correct name with prefix available for tab completion.
My recommended approach would be to include the DefaultCommandPrefix in the meta data cache during the initial population as a session is instantiated. Also, when a module is loaded explicitly by a user who specifies a -Prefix value the old references containing
the DefaultCommandPrefix would need to be removed.
William Busby, PMP

Hi William,
yes, that's something you'll either have to do the hard way or live with admin confusion.
If you're using Sapien's PowerShell Studio as an Editor (hint: Usually a great idea), you can very easily rename a function, even in a multi-file module project, by rightcklicking on the function-name and selecting "rename".
Alternatively you can do a bulk rename with Powershell:
Get all functions in your module (Load it and check exportedcommands)
loop over each function-name
calculate new name
search your entire project for all references and replace them.
Let me see ...
function Rename-ModulePrefix
[CmdletBinding()]
Param (
[Parameter(Position = 0, Mandatory = $true)]
[string]
$ModuleName,
[Parameter(Position = 1, Mandatory = $true)]
[string]
$OldPrefix,
[Parameter(Position = 2, Mandatory = $true)]
[string]
$NewPrefix,
[Parameter(Position = 3)]
[string]
$Path
# Catch all typos
Import-Module $ModuleName -ErrorAction 'Stop'
# Get root path if not manually passed
if (-not $PSBoundParameters["Path"])
$Path = (Get-Module $ModuleName).Path
# Get module files
$Files = Get-ChildItem -Path $path -Recurse -Include "*.ps1", "*.psm1", "*.psd1"
# Iterate over each file
foreach ($file in $Files)
# Null variable in case you get an empty file somewhere and run this from Win 7
$data = $null
# Get Content of file
$data = Get-Content $file
# Replace strings
foreach ($c in (Get-Module $ModuleName).ExportedCommands)
$newName = $c.Name -replace $OldPrefix, $NewPrefix
$data = $data | ForEach-Object { $_ -replace $c.Name, $newName }
# Write back to file
$data | Set-Content $file
While I didn't proof it, in theory this should do it (Make a backup before running it :) ).
Cheers,
Fred
There's no place like 127.0.0.1

Similar Messages

  • Does anyone have a PowerShell script which change the paper source on a Canon Image Runner Advance?

    I came across this Powershell script on the web, which does a good job of printing out PDFs:
    Start-Process -FilePath "C:\Users\Test\Documents\Listing.pdf” –Verb Print -PassThru | %{sleep 10;$_} | kill
    Start-Process -FilePath “C:\Users\Test\Documents\Scan0001.pdf” –Verb Print -PassThru | %{sleep 10;$_} | kill
    Start-Process -FilePath “C:\Users\Test\Documents\Scan0004.pdf” –Verb Print -PassThru | %{sleep 10;$_} | kill
    See: http://gregcaporale.wordpress.com/2012/01/18/powershell-to-print-files-automatically/ 
    What I want to know is, does someone know how to write a Powershell script so that before printing out each PDF, a tab will be pulled from a separate paper source tray.  I need the Powershell script to
    1. Set the paper source to tray 4 where the tabs are.
    2. Print a one page PDF which just reads "Tab 1" or whatever, on the tab itself
    3. Set the paper source to ray 1 where letter sized paper is.
    4. Print a PDF of the document to go behind tab 1.
    . . . and then repeat.
      I am working with a Canon Image Runner Advance copier/printer into which tabs can be loaded. It includes an insert sheets setting in the properties, which allows a user to specify the pages where a tab or slip sheet should go.  But I don't want to deal with creating a very large PDF, and then identifying all of the pages where an insert should occur.

    Here is the powershell code for adding ips to relayiplist..hope this helps.
    this code will take the ips of the host machine and add it to the relayiplist...works for me...
    $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName localhost | ? {$_.IPEnabled}
    $ipblock= @(24,0,0,128,
    32,0,0,128,
    60,0,0,128,
    68,0,0,128,
    1,0,0,0,
    76,0,0,0,
    0,0,0,0,
    0,0,0,0,
    1,0,0,0,
    0,0,0,0,
    2,0,0,0,
    1,0,0,0,4,0,0,0,0,0,0,0,76,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255)
    $ipList = @()
    $octet = @()
    foreach ($Network in $Networks)
         $ipList = $Network.IpAddress[0]
            $octet += $ipList.Split(".")
            $ipblock[36] +=1
            $ipblock[44] +=1;
    $smtpserversetting = get-wmiobject -namespace root\MicrosoftIISv2 -computername localhost -Query "Select * from IIsSmtpServerSetting"
    $ipblock += $octet
    $smtpserversetting.RelayIpList = $ipblock
    $smtpserversetting.put()
    kautilya

  • Powershell Script

    Hello,
    Need help with PowerShell. Do you have any powershell script or number of powershell scripts put together to get the following result :
    1.
    Name of all servers (including DB server)
    2. Service Pack level of each (aka. version number).
    3. Count and list of web application URL, site collections, content databases.
    4. List of managed accounts/service accounts used.
    5. List of service applications that are configured/turned on (e.g. Search, User Profile Sync, App Domain, WorkflowManager, Office WebApp, XLS/Visio/Powerpoint/WordAutomation, BCS, etc.)
    6. For EACH site collection:
    a. Actual storage used
    b. # of site at root level
    c. # of subsites (including the root sites) and how many has security inheritance broken.
    d. Deepest sub-site level.
    e. Names of site collection administrators.
    f. # of document libraries
    g. # of Infopath form libraries
    h. # of lists
    i. Top 5 list/library with most item counts.
    j. Number of documents with more than 20 versions.
    7. List of solutions deployed in Central Admin (if possible, all URL of site/subsites they’re activated at)
    8. List of error showing in Central Admin (under “Health Analyzer”)
    9. Current settings of:
    a. Default ULS log location.
    b. Current settings for Search Crawl schedule.
    c. Current setting for User Profile Sync schedule.
    d. Recycle Bin policy.
    e. Site quota templates configured
    Please help
    chirag

    Hi Chirag,
    I have not seen such a exhaustive
    powershell script available, however you may find individual scripts, and you can combine them in a single script.  I think bing would be able to help you in this case :)
    here are some to start with-
    http://talbottcrowell.wordpress.com/2010/10/22/listing-services-on-sharepoint-farm-by-server-using-powershell/
    http://code.msdn.microsoft.com/Find-Large-Lists-of-the-dde321f1
    http://code.msdn.microsoft.com/List-all-published-pages-70f9e356
    SharePoint Management PowerShell scripts
    http://sharepointpsscripts.codeplex.com/
    SharePoint 2013 Web Analytics Data Export to CSV using PowerShell
    http://sp2013wade.codeplex.com/
    Hope this helps!
    Ram - SharePoint Architect
    Blog - SharePointDeveloper.in
    Please vote or mark your question answered, if my reply helps you

  • Question regarding PowerShell script to Uninstall security updates in Windows 7/8

    Hello Everyone,
    I came across a great link on the Scriptcenter  
    https://gallery.technet.microsoft.com/scriptcenter/Uninstall-security-update-76f2dcb7  which has a PowerShell download that enables you to remove Microsoft updates from computers.  When I download the zip files ->extract it,  I have a
    file called " UninstallHotFix.psm1 ".   So far so good.  But where I am totally lost is in the directions to use this file. 
    Specifically: 
    Method 1:
    Download the script and open the script file together with Notepad or any other script editor.
    Scroll down to the end of the script file, and then add the example command which you want to run.
    Save the file then run the script in PowerShell
    I assume (1) refers to right clicking on "UninstallHotFix.psm1" and opening it with notepad?
    If I want to run the following...    Uninstall-OSCHotfix -HotFixID KB2830290   do I just paste it at the end of notepad?
    Do I save the file and attempt to run in powershell as a .psm1 file - or as a .ps1  file?
    Lost in Space....
    Adrian

    Hi Adrian,
    If the above doesn't help, I recommend posting questions about this item on the QandA tab of the script module:
    https://gallery.technet.microsoft.com/scriptcenter/Uninstall-security-update-76f2dcb7/view/Discussions#content
    I'd recommend following the steps in Method 2 on the gallery item. As an overview:
    1. Save the zip file into C:\Temp
    2. Extract the zip to C:\Temp\UninstallHotFix(PowerShell)
    3. Open a PS console and type the following:
    Import-Module 'C:\Temp\UninstallHotFix(PowerShell)\UninstallHotFix(PowerShell)\UninstallHotFix.psm1'
    You can verify that the module has been loaded by running Get-Module:
    PS C:\> Get-Module
    ModuleType Version Name ExportedCommands
    Manifest 3.1.0.0 Microsoft.PowerShell.Management {Add-Computer, Add-Content, Checkpoint
    Script 0.0 UninstallHotFix {Uninstall-OSCHotfix, UninstallHotFix}
    Don't retire TechNet! -
    (Don't give up yet - 13,225+ strong and growing)

  • Using Echo Command in PowerShell Script for Configuration Item

    Hello All,
    Before you tell me to post my PowerShell question to the PowerShell Forum, please know that the PowerShell portion of my task works just fine. It is the SCCM portion of my task that keeps failing, so that is why I am here. To give some background...
    There are two servers in our SCCM test environment. Both the SCCM server and SQL DB server are 2012, patched and updated.
    Test servers in my Device Collection being used for running Baselines and Reports against are 2008R2 and 2012, patched and updated.
    I have created a Configuration Item that checks to see if the FTP Server Role Feature has been installed on a 2008 or 2012 server. To do the check, I am using the following PowerShell script:
    (get-windowsfeature -Name Web-Ftp-Server).Installed
    When I log into my 2008R2 and 2012 test servers, and run this command directly on the server, it will return a "True" if the FTP Server Role Feature is installed on either server, and a "False" if it is not installed. Basically,
    it works as advertised.
    When I setup my Configuration Item and then deploy my Baseline, or run a report against my device collection of test servers, SCCM will return a correct response (True or False) for the 2012 test server, but throws the following error for the 2008R2
    server:
    0x87df00329 application requirement evaluation or detection failed
    Google searches for this have not been very helpful.
    Now, when I created the Configuration Item and referenced PowerShell, the configuration screen has the following note:
    "Specify the script to find and return the value to be assessed for compliance on client devices. Use the echo command to return the script value to Configuration Manager."
    Since I did not include an echo command in my PowerShell script above, I figured that was my problem, so I did the following:
    Logging onto both of my test servers (2008R2 & 2012) I was able to successfully run the following PowerShell commands and get the expected responses of True or False:
    (get-windowsfeature -Name Web-Ftp-Server).Installed | echo
    (get-windowsfeature -Name Web-Ftp-Server).Installed | write-output (http://technet.microsoft.com/en-us/library/hh849921.aspx)
    (get-windowsfeature -Name Web-Ftp-Server).Installed | write-host (http://technet.microsoft.com/en-us/library/ee177031.aspx)
    However, when I use any of these PowerShell commands in my Configuration Item, NEITHER of my test servers returns a response to the SCCM server.
    When I check the report, both servers show as "Unknown" and when I click on the number 2 (as in 2 servers unknown), the following report page (List of unknown assets for a configuration baseline) has absolutely no data/information at all.
    So...I am at a loss.
    SCCM tells me to use an echo command to return a script value to Configuration Manager. The PowerShell scripts above, with the various echo related commands, work just fine on the servers themselves, but they return no information when run via SCCM.
    What am I missing?
    Any help will be appreciated.
    Thanks in advance for your time.

    Sorry for my ignorance, but I don't understand. (I forgot to mention that I am new at both PowerShell and SCCM.)
    After I change the PowerShell script to add the echo/write-output/write-host cmdlet, I open the ConFig Item and "Clear" the PowerShell script and then re-add it. When I do that, it correctly shows the change in the ConFig Item.
    Next I open the Baseline, then open the ConFig Item within the Baseline to make sure the change is reflected there as well, which it is.
    I then deploy the Baseline to my Device Collection. After that, I run a report against the Baseline and Device Collection and it returns the "Unknown" result.
    If I open the PowerShell script and remove the echo/write-output/write-host cmdlet, then go through the rest of the process of updating and reporting, the result it returns changes, showing one server in compliance and the other server out of compliance,
    which leads me to think that all changes have taken correctly.
    Does that sound right? If I manually deploy the Baseline, is that the same as the client retrieving policies from the management point?
    Sorry to be so thick but I'm learning as I go.
    Thanks again for your help.

  • PowerShell Scripting help to combine two scripts

    I have a script that helps automate virtual server builds.  The script creates a specification document which is used to perform the actual builds.
    # Spec-And-Build.ps1 - Loops through a directory and performs an
    # end to end specification generation and build on each request in that directory
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string]$RequestDir,
        [Parameter(Mandatory=$true)]
        [string]$SpecDir,
        [Parameter(Mandatory=$false)]
        [pscredential]$Credential_CPR,
        [Parameter(Mandatory=$false)]
        [pscredential]$Credential_VDC,
        [Parameter(Mandatory=$false)]
        [pscredential]$Credential_Admin
    if (!$Credential_CPR) {
        $Credential_CPR = Get-Credential -Message "CPR Domain Credentials."
        if (!$Credential_CPR.UserName.ToUpper().StartsWith("CPR\")) {
            $Credential_CPR = New-Object pscredential(
                ("CPR\" + $Credential_CPR.UserName), $Credential_CPR.Password)
    if (!$Credential_VDC) {
        $Credential_VDC = Get-Credential -Message "VDC Domain Credentials."
        if (!$Credential_VDC.UserName.ToUpper().StartsWith("VDC\")) {
            $Credential_VDC = New-Object pscredential( `
                ("VDC\" + $Credential_VDC.UserName), $Credential_VDC.Password)
    if (!$Credential_Admin) {
        $Credential_Admin = Get-Credential -UserName "Administrator or root" `
            -Message "Enter the Administrator or root password for the new VM. The user name here will be ignored"
    .\Gen-VMSpec-Many.ps1 -RequestDir $RequestDir -SpecDir $SpecDir -Credential_VDC $Credential_VDC
    $caption = "Continue Build"
    $message = "Please validate the generated specification files in $SpecDir - Then click Continue to start build"
    $opContinue = new-Object System.Management.Automation.Host.ChoiceDescription "&Continue","help"
    $opAbort = new-Object System.Management.Automation.Host.ChoiceDescription "&Abort","help"
    $choices = [System.Management.Automation.Host.ChoiceDescription[]]($opContinue,$opAbort)
    $answer = $host.ui.PromptForChoice($caption,$message,$choices,0)
    if ($answer -eq 0) {
        .\Build-VM-Many.ps1 -SpecDir $SpecDir -Credential_CPR $Credential_CPR -Credential_VDC $Credential_VDC -Credential_Admin $Credential_Admin
    } else {
        Write-Host "Build step aborted, run Build-VM-Many.ps1 manually to continue."
    This script works well.  Now I need to add a section that adds Active Directory groups to the built servers from the spec document.  I found this script which also works well:
    # Create local group on the local or a remote computer 
    Write-Host -foregroundcolor Yellow 'Admin Privileges Required!' 
    $computerName = Read-Host 'Enter computer name or press <Enter> for localhost' 
    $localGroupName = Read-Host 'Enter local group name' 
    $description = Read-Host 'Enter description for new local group' 
    if ($computerName -eq "") {$computerName = "$env:computername"} 
    if([ADSI]::Exists("WinNT://$computerName,computer")) { 
        $computer = [ADSI]"WinNT://$computerName,computer" 
        $localGroup = $computer.Create("group",$localGroupName) 
        $localGroup.SetInfo() 
        $localGroup.description = [string]$description 
        $localGroup.SetInfo() 
    My question is, how do I make one script from the two?  I am very new to PowerShell scripting.

    Here are the instructions on how to use PowerShell:
    http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx
    Your question is vague and is asking for someone to do this for you.  It is better if you do it yourself and post back with specific questions.
    In the end you have to write and debug the scripts. We will not do this for you but we will answer questions.
    ¯\_(ツ)_/¯

  • Looking for a Powershell Script which can put the scom servers in maintenance mode

    Looking for a Powershell Script which can put the scom servers in maintenance mode so that SCOM should not send an alert during planned task.
    Rahul

    1. Provide list of servers line-by-line in C:\ServerList.txt, make sure you provide limited no. of servers, do not exceed 20 - 25 per batch
    2. Save the script with suitable name (test.ps1)
    3. Open PowerShell cmd prompt
    4. Script accepts 3 params - TimeInMinutes, Reason and Comment
    **** Please note, this script will work for SCOM 2012 R2
    param([int32]$TimeMin, [string]$Reason, [string]$Comment)
    try
    $api = new-object -comObject 'MOM.ScriptAPI'
    Import-Module operationsmanager
    New-SCOMManagementGroupConnection
    $Servers = Get-Content "C:\ServerList.txt"
    $Time = (Get-Date).Addminutes($TimeMin)
    Foreach ($Server in $Servers)
    #Get Computer instance
    $ComputerClass = Get-SCOMClass -Name Microsoft.Windows.Computer
    $ComputerClassInstance = Get-SCOMClassInstance  -Class $ComputerClass | Where {$_.DisplayName -eq $Server}
    If ($ComputerClassInstance -ne $Null)
    $HealthServiceWatcherClass = Get-SCOMClass -name:Microsoft.SystemCenter.HealthServiceWatcher
    #Get Health Service Watcher Class instance of the server
    $HSWClass = Get-SCOMClass -Name Microsoft.SystemCenter.HealthServiceWatcher
    $HSWClassIns = Get-SCOMClassInstance  -Class $HSWClass | Where {$_.DisplayName -eq $Server}
    #Starting the maintenance mode
    Start-SCOMMaintenanceMode -Instance $HSWClassIns -EndTime $Time -Reason $Reason -Comment $Comment
    Start-SCOMMaintenanceMode -Instance $ComputerClassInstance -EndTime $Time  -Reason $Reason -Comment $Comment
    Write-Host "Health Service Watcher and Agent server "$Server " kept in maintenance mode"  -foregroundcolor "green"
    $api.LogScriptEvent('MaintenanceModeScript.ps1', 200, 0, "$Server kept in maintenance mode for $TimeMin minutes")
    Else
    Write-Host $Server" not found " -foregroundcolor "red"
    $api.LogScriptEvent('MaintenanceModeScript.ps1', 201, 1, "$Server could not be found in domain")
    Catch [system.exception]
    $api.LogScriptEvent('MaintenanceModeScript.ps1', 201, 1, $_.Exception.Message)
    Faizan

  • 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]'

  • Powershell script to Get members of AD group members with first, last, email address

    I'm running a powershell script to retrieve AD users from a specific AD group and pipe specific attributes to a csv file. The script is working perfectly except for one detail. I want the script to ignore any users who have a null value in any of the values
    I'm piping to the spreadsheet. Meaning that if any of the users found in the queried groups have a null value in the attributes givenname, sn or mail, ignore the user and do not pipe to the csv.
    Get-ADGroupMember -identity adgroup -recursive | get-adobject -Properties givenname,sn,mail | select givenname,sn,mail |export-csv -path c:\powershell\groupmembers.csv
    –NoTypeInformation

    Hi,
    You can pipe your user objects through ForEach-Object and then use if to verify all three properties exist. If so, output the object. If not, move to the next object. After you've processed all user objects, then pipe into Export-Csv.
    EDIT: See below.
    Don't retire TechNet! -
    (Don't give up yet - 13,225+ strong and growing)

  • The PowerShell script failed with below exception

    I'm receiving the following errors on all SQL Express Servers (every machine that has SQL Express inside).
    it seems that the discovery has found SQL Express but could not connect to the instance.
    details on the alerts:
    Date and Time:
    10/22/2013 12:04:22 PM
    Log Name:
    Operations Manager
    Source:
    Health Service Modules
    Generating Rule:
    Collect Power Shell Module Events
    Event Number:
    22406
    Level:
     Error
    Logging Computer:
    SQLEXPRESS.DOMAIN.COM
    User:
    N/A
    Description:
    The PowerShell script failed with below exception
    System.Management.Automation.RuntimeException: Exception calling "Fill" with "1" argument(s): "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)"
    At line:44 char:19
    + $SqlAdapter.Fill <<<< ($DataSet)|out-null
    at System.Management.Automation.FlowControlNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
    at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
    at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
    Script Name: StolenServerMemory2008.ps1
    One or more workflows were affected by this.
    Workflow name: Microsoft.SQLServer.2008.DBEngine.StolenServerMemoryMonitor
    Instance name: SQLEXPRESS
    Instance ID: {9705795C-4F3B-C2EF-AA7D-C736B40FD6A4}
    Management group: SCOMGROUP 

    Some additional inf.
    http://stackoverflow.com/questions/6466974/unable-to-connect-to-sql-express-error-26-error-locating-server-instance-speci?rq=1
    anyway you can disable this rule/monitor as no control from monitoring solution in that case. Or try to rewrite the same monitor...
    The problem in your case is when function tries to get Max Server Memory MB by connecting to master DB, but you can replace it with performance counter like Target Server Memory (KB)...
    just see the function main in StolenServerMemory2008.ps1 and what you need to replace
    $api = New-Object -comObject "MOM.ScriptAPI"
    $bag = $api.CreatePropertyBag()
    $msg = [Environment]::NewLine
    $err = [Environment]::NewLine
    #try {
    $maxMemoryMB = GetMaxServerMemoryMB $ComputerName $InstanceName
    $stolenPages = (Get-Counter ("\" + $PerformanceCounterObject + ":Buffer Manager\Stolen Pages")).CounterSamples[0].CookedValue
    $pakeSizeKB = 8
    [double]$stolenMemoryMB = $stolenPages * $pakeSizeKB / 1024                                      
    [double]$stolenMemoryPercent = 0
    if($maxMemoryMB -gt 0){
    [double]$stolenMemoryPercent= 100.0 * $stolenMemoryMB / $maxMemoryMB
    $bag.AddValue("StolenMemoryMB", $stolenMemoryMB)
    $bag.AddValue("StolenMemoryPercent", $stolenMemoryPercent)                                  
    $msg += "StolenMemoryMB=$stolenMemoryMB StolenMemoryPercent=$stolenMemoryPercent"
    $msg += [Environment]::NewLine                          
    #debug $api.LogScriptEvent("SQL 2008 Stolen Server Memory data source", $SCRIPT_EVENT_ID, $INFORMATION_EVENT_TYPE, $msg + $err)                     
    #catch {
    #             $header = "Managegement Group: $Target/ManagementGroup/Name$. Script: {0}" -f ($MyInvocation.MyCommand).Name.ToString()
    #             $msg += "Error occured during SQL 2008 Stolen Server Memory data source executing.{0}Computer:{1} {0}Reason: {2}" -f [Environment]::NewLine, $env:COMPUTERNAME, $_.Exception.Message
    #             $api.LogScriptEvent($header, $SCRIPT_EVENT_ID, $ERROR_EVENT_TYPE, $msg + $err)                           
    $bag

  • Error with SMLets in an Orchestrator called PowerShell Scripts

    Hi!
    This is likely so simple I am overlooking the problem but...
    I have a "Run .Net Script" activity in an Orchestrator 2012 SP1 Runbook.  It calls SMLets.  The issue is it runs in the PowerShell ISE on the Runbook server without issue.  It runs in the Runbook Tester just fine.  But if I
    call the runbook with the PowerShell script, it errors out on the first call the a SMLets provide cmdlet.
    A Few Detail:
    We loaded the latest SMLets from CodePlex.  We can use the cmdlets in both the 32-bit and 64-bit environments.
    The very first line of the PowerShell script is: Import-Module SMLets
    The first SM cmdlet is: $class = Get-SCSMClass System.WorkItem.Activity.ReviewActivity$
    The Runbook Containing the PowerShell Script:
    And lastly, the Event of the error thrown:
    In trying to make this work we have tried to run the script remotely on the SCSM server (New-PSSession and Invoke-Command).  Failures due to rights on the SCSM server. 
    My opinion is the issue is a rights issue but we cannot find the difference between any of the accounts testing/debugging and the Orchestrator Runbook Service account.  I can run the PowerShell and the Runbook Tester when logged on as the
    Orchestrator Runbook Service account.  It works until I have to call the runbook with the PowerShell Activity.  It just like my Account.  We've even set the account on the security tab of the Invoke Runbook Activity.
    Is there something I've overlooked?  Something in the install of the SMLets, maybe? A clue?  Help?
    If nothing else, thank you for letting me voice my issue onto the 'Net.  Maybe someone else has been down this road and can tell me where the off-ramp is.  ;-)
    Ray Watters,
    Chicago, IL

    Hi,
    also make sure that your PS scriptruns with Windows PowerShell (x86) (32bit)
    http://www.sc-orchestrator.eu/index.php/scoblog/64-using-64bit-powershell-cmdlets-in-the-run-net-script-activity-from-orchestrator
    or with PowerShell V2
    http://www.sc-orchestrator.eu/index.php/scoblog/102-running-powershell-30-with-the-run-net-script-activity
    Regards,
    Stefan
    www.sc-orchestrator.eu ,
    Blog sc-orchestrator.eu

  • Windows 8.1 - How to enable "Require additional authentication at startup" for bitlocker using powershell script?

    I need help to do this using powershell scripts on Windows 8.1?
    OS : Windows 8.1 Enterprise
    TPM Chip : None
    Enabling bitlocker on OS drive with a password at boot time is a 2 step process.
    1) Edit the Group Policy (gpedit.msc) - Administrative Templates -> Windows Components -> BitLocker Drive Encryption -> Operating System Drives ->
    Require additional authentication at startup -> Allow bitlocker without a compatible TPM
    ref : http://www.7tutorials.com/how-enable-bitlocker-without-tpm-chip-windows-7-windows-8
    2) Enable Bitlocker on c driver using manage bitlocker snapin
    I need help to do this using powershell scripts?
    I researched on the forums but ran into an issue.
    I found that Group policy commandlets can be used to do step 1.  
    I am getting the error : "ins have been registered for Windows PowerShell version 4" when I try to do the following in windows 8.1
    Add-PSSnapin GroupPolicy
    Import-Module GroupPolicy -Verbose

    Hi TinkerBotFoo,
    I’m writing to just check in to see if the suggestions were helpful. If you need further help,
    please feel free to reply this post directly so we will be notified to follow it up.
    If you have any feedback on our support, please click here.
    Best Regards
    Anna
    TechNet Community Support
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • Running PowerShell Script to automate the installation of IIS feature - Add-WindowsFeature error, help please

    I'm just learning PS scripting and Chef Programming, so I'm sure I'm missing something simple. I'm trying to run a recipe that is using PS as the interpreter. I've ensured I'm running PS in 64 bit with admin privileges, and have Imported the ServerManager
    module. I even added a line to my script to have it run that first, but am still receiving an error in my script. I'm running this on a VM of Server 2008R2
    Script:
    powershell_script 'Install IIS' do
      code "Import-Module ServerManager -passthru"
      code "Add-WindowsFeature Web-Server"
      guard_interpreter :powershell_script
      not_if "(Get-WindowsFeature -Name Web-Server).Installed"
    end
    Error:
    PS C:\Users\Administrator\chef-repo> chef-apply webserver.rb
    Recipe: (chef-apply cookbook)::(chef-apply recipe)
      * powershell_script[Install IIS] action run
        ================================================================================
        Error executing action `run` on resource 'powershell_script[Install IIS]'
        ================================================================================
        Mixlib::ShellOut::ShellCommandFailed
        Expected process to exit with [0], but received '1'
        ---- Begin output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat
    None -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
        STDOUT:
        STDERR: The term 'Add-WindowsFeature' 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.
        ---- End output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat No
    ne -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
        Ran "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -File "C:/Us
    ers/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" returned 1
        Resource Declaration:
        # In webserver.rb
          1: powershell_script 'Install IIS' do
          2:   code "Import-Module ServerManager -passthru"
          3:   code "Add-WindowsFeature Web-Server"
          4:   guard_interpreter :powershell_script
          5:   not_if "(Get-WindowsFeature -Name Web-Server).Installed"
          6: end
        Compiled Resource:
        # Declared in webserver.rb:1:in `run_chef_recipe'
        powershell_script("Install IIS") do
          action "run"
          retries 0
          retry_delay 2
          guard_interpreter :powershell_script
          command "\"powershell.exe\" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -Fi
    le \"C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1\""
          backup 5
          returns 0
          code "Add-WindowsFeature Web-Server"
          interpreter "powershell.exe"
          cookbook_name "(chef-apply cookbook)"
          recipe_name "(chef-apply recipe)"
          not_if "(Get-WindowsFeature -Name Web-Server).Installed"
        end
    [2014-12-24T10:29:56-08:00] FATAL: Stacktrace dumped to C:/chef/cache/chef-stacktrace.out
    [2014-12-24T10:29:56-08:00] FATAL: Mixlib::ShellOut::ShellCommandFailed: powershell_script[Install IIS] ((chef-apply coo
    kbook)::(chef-apply recipe) line 1) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0
    ], but received '1'
    ---- Begin output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None
     -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
    STDOUT:
    STDERR: The term 'Add-WindowsFeature' is not recognized as the name of a cmdlet, function, script file, or operable prog
    ram. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    ---- End output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -
    File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
    Ran "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -File "C:/Users/
    ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" returned 1

    Hi There,
    We have a application named Microsoft SCOM. That as well requires ISS to be installed. I tried this long back and it worked in powershell. Below is the powershell script i used to install IIS and some specific features from it. Hope it helps in altering
    it and making one of your own script.
    1.  Launch the PowerShell command
    prompt
     Run this command
    Import-Module ServerManager
    3. Press Enter
    4. Run this
    command
    Add-WindowsFeature NET-Framework-Core,Web-Metabase,Web-WMI,Web-Static-Content,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Asp-Net,Web-Net-Ext,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Filtering,Web-Windows-Auth,
    Web-Mgmt-Console –restart
    Gautam.75801

  • What's the standard header in PowerShell scripts (documentation)?

    Can anyone tell me what the "standard header" that I see in a lot of PowerShell scripts is all about? I have been unable to find any explanation so far.
    Here's a snippet:
    <#
    .SYNOPSIS
    Counts the Grateful Dead shows in my archives
    .DESCRIPTION
    This script looks at my GD archive, and uses folder names to
    determine show type (aud, sbd, etc), and checks to see what
    shows have checked MD5s
    .NOTES
    File Name : count-gdshows.ps1
    Author : Thomas Lee - [email protected]
    Requires : PowerShell V2 CTP3
    .LINK

    The help data can be used inside a function body or in a script. A script is not much different than a function, actually you can think of it as a function *without* a name, the name is the script name. You can a function like:
    function foo
    <# 
    .SYNOPSIS 
        Counts the Grateful Dead shows in my archives
    #>
       param($a,$b)
       $a+$b
    And execute it like:
    foo -a 3  -b 4
    or write the function body in a script file called foo.ps1 :
    ## foo.ps1 ##
    <# 
    .SYNOPSIS 
        Counts the Grateful Dead shows in my archives
    #>
       param($a,$b)
       $a+$b
    and execute it like so:
    .\foo.ps1 -a 3 -b 4
    they give the same output. Windows 7 is goiung to RTM soon and as you probably know PowerShell v2 ships with it, so you can switch to v2 in the very near future. I'm working with v2 since the CTP versions (on my production machine) and it is working very good, lots of new exiting stuff!
    As for functions vs scripts... it depends. On my personal machine I save my functions in various ways. I categorize them and save each bunch in a seperate script file (i.e. utilities.ps1, exchange.ps1, ad.ps1 etc). Some files I use more on a regular basis so I dot-source them in my profile, other scripts I load when I need. v2 introduced a module concept so the next evolution of my script files will turn into modules.  I also implement some functions in ps1xml files, these are used to extend objects , via PowerShells' Extended Type System (ETS), you can find an example on my blog (http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2009/05/31/getting-certificates-expiration.aspx).
    Shay Levy [MVP]
    http://blogs.microsoft.co.il/blogs/ScriptFanatic
    PowerShell Toolbar

  • Is it possible to catch a PowerShell script output when an exit code is setted?

    Hi,
    i'm using TEO 2.1.2 with the hotfixes from 1 to 12 already installed and i have a problem using the "Execute Windows PowerShell Script" in reading the output of a PowerShell script if an exit code is expressly setted . For example if i try to execute a script like:
    the output given by the activity is only 0 (like the exit code).
    This is a problem if i use a script with multiple exit codes corrisponding to different kind of situations and different outputs like the following:
    if($flag -eq "0")
       Write-output "Hello"
       exit 0
    elseif ($flag -eq "1")
       Write-output "Error 1"
       exit 1
    else
      Write-output "Error 2"
      exit 2
    or if i call an executable which exit codes i want to identify by a readable description.
    Anyone knows a way to solve this issue?
    Thanks a lot,
    bye.
    Giulio

    Thanks Shaun,
    i was already looking toward this kind of approch, but i was also curious if there was a different way of doing this.
    Anyway just a little annotation about your line of code, in Tidal 2.1.2 at least, Write-host doesn't work right, echo or Write-Output are fine but Write-host seems to be ignored. To the following script:
    the output is
    Maybe i'm missing something. Regarding an upgrade, as a devoloper i'd really like to try the improvement of the new version but this is not a decision I can make.
    Thank you,
    bye.
    Giulio

Maybe you are looking for

  • Direct Printing PDF via Acrobat 8.0 under Lion

    Direct printing a PDF via Acrobat 8.0 worked under Snow Leopard but no longer under Lion. I have a relatively old installation of CS3 on my MacBookPro and wanted to print a pages document with 12 x 12 cm size onto an A4 page (with integrated cutting

  • Compressing attachments in entourage email

    I am unable to compress attachments in my entourage email. I have Stuffit Expander installed, and I still can't compress pictures and video. Is there something else that needs to be done?? Please help Powerbook G4   Mac OS X (10.4.6)  

  • Migrating, but don't want to transfer partition and Parallels

    I am migrating from a white Macbook to aluminum; I do not want to transfer Parallels and the disk partition. How can I transfer all my info and settings except parallels and Windows XP?

  • Error when trying to run jsp on oas4081

    Hi there! As many others before, I'm trying to get jsp to run on oas4081. Although I think I did everything what the docs (and the other posts here) say, I get an error. Here is what I did: * download ojsp.zip * add a JServlet application * under ENV

  • MacBook should be used as a VMWare environment?

    In my work, I am be assigned as Windows server administrator. I want to learn Windows server technoligy. I installed VMWare Fusion in my MacBook Air 2013 mid. But sometimes, I think why I take work into my personal life? Why use my own Mac to do my c