Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

powershell execution error

$
0
0

Hi,

I am getting the below error while executing PS.Anybody experienced the same? what could be the reason?


Best Regards, Arun http://whynotsql.blogspot.com/


New-WebBinding syntax to add SSL binding to specific IIS Web Site

$
0
0

I can't figure out what I'm doing wrong -- to be fair to myself the online support "New-Item" is pretty poor but I am new to this.

I'm trying to add an SSL binding to 1 of 3 web sites.  The script below works but it doesn't add the binding to the Host/Site that

I want.  What is the syntax to specify host name and site.

Here's the script I'm using

write-host "Delete binding"
Get-WebBinding -Port 443 -Name "IdentityServer" | Remove-WebBinding
write-host "create new binding"
New-WebBinding -name "IdentityServer" -Protocol https -HostHeader "Identity-dev.acme.com" -Port 443 -SslFlags 1
$cert = Get-ChildItem -Path Cert:\LocalMachine\My | where-Object {$_.subject -like "*acme.com*"} | Select-Object -ExpandProperty Thumbprint
cd IIS:\SslBindings
get-item -Path "cert:\localmachine\my\$cert" | New-Item 0.0.0.0!443!Identity-dev.acme.com

The result from the IIS:\SslBindings folder (not what I want):

IP Address          Port   Host Name        Store            Sites                           
----------          ----   ---------        -----            -----                           
0.0.0.0             443                     my  

The result I'm looking for:

IP Address          Port   Host Name        Store         Sites                           
----------          ----   ---------         -----          -----                           
0.0.0.0             443     Identity-dev.acme.com     my  IdentityServer

Thanks,

Tim

Replacing Single Line of Code in XML File on Multiple Systems

$
0
0

Hey Guys -

I'm not a pro PowerShell user, but dabble in it when I can.  I have a task I need to perform which I need assistance with, please - one that I'd think would be easy for the pros.

I am needing to deploy a script which will change a single line of code in an XML files on multiple systems on our domain.  The challenge is that the XML also contains user-specific data which is why I can't just copy/replace a new file in.  Here's what I'm wanting it to do:

- See if XML has a line that starts with "<isolationLevel"

- If so, replace it with another similar line of code

That's it - Is this easily possible?  Thanks!


Ben K.

Powershell sql server install automation

$
0
0

I need help with below code I am writing to automate sql server install

param( 
        #Name of SQL Server host 
        [parameter(Mandatory=$true, 
               HelpMessage="Enter Server Name/machine name",Position=0)] 
        [String] 
        [ValidateNotNullOrEmpty()] 
        $server = $(throw "server parameter is required."), 

        #MS Install folder name 
        [parameter(Mandatory=$true, 
               HelpMessage="Enter Install folder name",Position=1)] 
        [String] 
        [ValidateNotNullOrEmpty()] 
        $folder = $(throw "Install folder name is required."),

        #MS SQL Server edition, std or ent 
        [parameter(Mandatory=$true, 
               HelpMessage="Enter SQL Server STD or ENT Edition",Position=2)] 
        [String] 
        [ValidateNotNullOrEmpty()] 
        $edition = $(throw "edition parameter is required."),

        #MS SQL Server service pack install
        [parameter(Mandatory=$true, 
               HelpMessage="Install service pack YES or NO",Position=3)] 
        [String] 
        [ValidateNotNullOrEmpty()] 
        $servpk = $(throw "Service pack YES or NO is required."),

        #Enter Environment PROD, QA, DR or DEV
        [parameter(Mandatory=$true, 
               HelpMessage="Enter Environment PROD, QA, DR or DEV",Position=4)] 
        [String] 
        [ValidateNotNullOrEmpty()] 
        $environment = $(throw "Environment parameter PROD, QA, DR or DEV is required."),

        #Instance name , null for default
        [parameter(Mandatory=$true, HelpMessage="Enter Instance name, null for default", Position=5)]
        [String] 
        [AllowEmptyString()] 
        $instance

    ) 


###Variables
#  map network drive to Z drive
Remove-PSDrive -Name Z
New-PSDrive –Name Z –Root "\\nylimrps-fs1\vol2\wp" -Persist -PSProvider FileSystem
#  set to default scripts directory
$scriptsHome = 'Z:\AN0413\SQL\DBStandards\SQL Server 2008 Silent install\InstallFolder\'

cd 'Z:\AN0413\SQL\DBStandards\SQL Server 2008 Silent install\InstallFolder\'

New-Item $folder -type directory

cd $folder

$logFile = $PWD.Path + '\SQLDeploy_Log.txt'
Write-Host "Your log file is ",$logFile

#Initialize log file
Get-Date | Out-File $logFile

If ($edition -eq 'STD')
{
If $instance -eq "" -or $instance -eq $null
{
Copy-Item 'Z:\AN0413\SQL\DBStandards\SQL Server 2008 Silent install\Default Instance Install\ConfigurationFile.ini' 
Copy-Item 'Z:\AN0413\SQL\DBStandards\SQL Server 2008 Silent install\Default Instance Install\InstallSQL2008R2_STD_default.bat'
}
ELSE
{
Copy-Item 'Z:\AN0413\SQL\DBStandards\SQL Server 2008 Silent install\Named Instance Install\ConfigurationFile_NamedInstance.ini'
Copy-Item 'Z:\AN0413\SQL\DBStandards\SQL Server 2008 Silent install\Named Instance Install\InstallSQL2008R2_STD_NamedInstance.bat' 
}
}

The above code snipet is saved as InstallSQL1.ps1 under C:\Silent install testing\

I am running this

cd 'C:\Silent install testing\'
set-executionpolicy unrestricted

powershell.exe -NoProfile -Command .\InstallSQL1.ps1 [-server] 'test' [-folder] 'test1' [-edition] 'STD' [-servpk] 'NO' [-environment] 'DEV' [-instance] 'TEST1'  

I get below error, about positional paramter [-servpk] but I am passing it so I am not sure why its giving this error

    powershell.exe : C:\Silent install testing\InstallSQL.ps1 : A positional parameter cannot be 
At line:3 char:1
+ powershell.exe -NoProfile -Command .\InstallSQL.ps1 [-server] 'test' [-folder] ' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (C:\Silent insta...eter cannot be :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
found that accepts argument '[-servpk]'.
At line:1 char:1
+ .\InstallSQL.ps1 [-server] test [-folder] test1 [-edition] STD [-servpk] NO 
[-en ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
    + CategoryInfo          : InvalidArgument: (:) [InstallSQL.ps1], Parameter 
   BindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,InstallSQL.ps1
 
powershell.exe : C:\Silent install testing\InstallSQL1.ps1 : A positional parameter cannot be 
At line:4 char:1
+ powershell.exe -NoProfile -Command .\InstallSQL1.ps1 [-server] 'test' [-folder]  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (C:\Silent insta...eter cannot be :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
found that accepts argument '[-servpk]'.
At line:1 char:1
+ .\InstallSQL1.ps1 [-server] test [-folder] test1 [-edition] STD [-servpk] NO 
[-e ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
    + CategoryInfo          : InvalidArgument: (:) [InstallSQL1.ps1], Paramete 
   rBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,InstallSQL1.ps1
 


                                     

RPSAdmin

Question about null value and delimter

$
0
0

I've made a script to export Ad information, this works fine.

I want to skip de header. But when I add a skip -1 + the selected objects it won't work and I have a null value in the OS service pack that brakes my terminator in the CSV file, so I got problems with importing it in SQL.
Can anybody explain me how to solve this issues.

Many thanks.

Import-Module (Get-PSSnapin Quest.ActiveRoles.ADManagement -Registered).modulename

$filepath = "e:\OutputScripts\$(get-date -f "yyMMdd") COMPUTERS_AD_RWS_NL.csv"
$file= $filepath
$file = New-Item -type file $file -Force

$nu = (Get-Date)

getAdInfo = GET-QADCOMPUTER -ldapFilter '(!(userAccountControl:1.2.840.113556.1.4.803:=2))' -SizeLimit 0 -IncludedProperties lastLogonTimestamp | where {
$_.lastlogontimestamp -notlike ""} | Select-Object Name, lastLogonTimestamp, `
OSName, ParentContainerDN, osversion,osServicePack |   Export-CSV $file -NoTypeInformation -delimiter ";"

Can I use Powershell script on Win8 machine to upload files to xxx.sharepoint.com?

$
0
0

I am confused if my request is possible. The company I work for uses Office 365 and they gave us Sharepoint. We access SP by going to xxx.sharepoint.com on the Internet. I am thinking of writing a Powershell script that runs on my Windows 8 machine to upload files from a network drive in the office WAN to xxx.sharepoint.com. I have write permission to some document libraries in xxx.sharepoint.com and I am a site administrator of xxx.sharepoint.com but not the global administrator.

It seems that the examples I saw on the Internet about Powershell script running against a SharePoint site are those which are on-premises, not SharePoint Online.

Does it mean that my Powershell script will never work?

Preference variable, Action switches, and scopes

$
0
0

Hello,

I am rewriting some most basic powershell write functions (mainly write-error and write-warning), partly to improve my understanding of their behaviour, partly because I don't like the format of the text I see in the console, and I am having some issues working with $ErrorActionPreference and $WarningPreference.

First of all, I can't seem to be able to set these variable globally.

(I am using powershell 4.0 on a win7 environment btw)

my functions is as follows

Function Write-MyWarning {
 Param (
  [Parameter(Mandatory=$True)]
  [string]$Message="$Message"
  [switch]$ConfirmAll
 )
 if ($SuspendAll) {Set-Variable -Name "WarningPreference" -Value "Confirm" -Scope Global}
 if ($WarningAction) {$WarningPreference=$WarningAction}
 switch($WarningPreference) {"Continue" {Write-Host "[WARNING] $Message"}"Confirm" {Read-Confirm "[WARNING] $Message"}
   default {Write-Host "[WARNING] $Message"}
 }

}

Somehow the $WarningAction variable is always $Null, and $WarningPreference isn't set globally but only in my function.

Do you know how I could/should use these variables ?

Thanks in advance for your answers

PS : I apologize if my English is a bit akward, I am not a native speaker

What is wrong with my Get-Content

$
0
0

I have a very simple script that for some reason fails me when I try to use the Get-Content issue. 

$scriptLoc = [string](Get-Location)
$path = $scriptLoc + '\temp_folder\'
$files = Get-ChildItem -Path $path -filter hello*.txt
write-host $files


So this works fine. It goes to this destination. C:\Scripts\temp_folder

In this folder are two files. 

1. hello_dave.txt

2.bye_dave.txt

when I run the script above it successfully only shows file 1.

So why does it fail with this?

$file = Get-Content $files

Actually I know why it fails, but why it fails make no sense. It returns an error saying that it cannot find the path. 

The path it lists is not the one I have setup. This is the folder the txt file is in, and what I have setup earlier. C:\Scripts\temp_folder

This is what it returns instead. Cannot find path 'C:\Scripts\hello_dave.txt' because it does not exist. 


PowerShell Assistance - Office 365 - unlicensed users in a specific group

$
0
0

Hello all,

I am just getting started with PowerShell in order to manage our new installation of Office 365.  I posted this question in the Office 365 forum and someone there recommended I post the question here.

I have a script that will license all users withing a specific group with a specific SKU.

In the line below I assign all users that are member s of a specific group to a variable:

$VARIABLE = Get-MsolGroup | ?{ $_.DisplayName -eq "GROUP NAME" } | %{ Get-MsolGroupMember -All -GroupObjectId $_.ObjectId }

Can any one please show me how I would modify the line above to assign only the unlicensed users from the group to the variable?

Thank you

Getting user input then saving it to send an email to the input

$
0
0

Hi All,

Just experimenting with PowerShell and sending e-mail and wonder if you would be able to help me.

I'm trying to get Powershell to prompt for an input then save it and user the entered input in the next part of the script.

Here is the code I have :

$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "tlewis@organisation.com"
 $Mail.Subject = "test"
$Mail.Body ="test"
 $Mail.Send()

That works fine, but I would like to get users to edit the $mail.to so they can type in an email address.

For instance, when you run the script I want PowerShell to prompt "Mail to:" then the user would enter the email address "user1@organisation.com"

It would then save this input and add it to the $Mail.to location then send it.

To streamline this a bit more would it be possible so the user only needs to type in the first part of the email address? e.g "user1" and it will always keep the @organisation.com constant so they wouldn't need to enter as much?

Thanks for any help with this, just something I'm experimenting with. I'm trying to do this on my own but I'm really struggling to understand what I need to do.

Hoping I can reverse engineer anything you give me to better understand the processes involved.

I have the first part of the prompt:

$name=Read-Host'Email to:'

And I can enter an e-mail address (although would prefer a prompt) I just want it to save what I type and add it into the code.


Powershell command to Run Multiple task

$
0
0

Dear Guys,

could we run PowerShell command in one line rename-item, remove-item and move-item with pipe line | , because below code not running
Get-ChildItem *.Txt | Rename-Item -NewName { $_.name -replace '\.txt','.eml'}|Remove-Item *.prop | Move-Item -Path .\*.eml -Destination 'C:\Program Files\Microsoft\Exchange Server\V14\TransportRoles\Replay'


Best Regards, Hussain

Raise a PowerShell events from within a runspace (which has no GUI elements) to the Powershell host

$
0
0

Hello everyone,

I saw this PS code snippet on stackoverflow from the PS MVP Bo Prox;

$Global:x = [Hashtable]::Synchronized(@{})
$x.Host = $Host
$rs = [RunspaceFactory]::CreateRunspace()
$rs.ApartmentState,$rs.ThreadOptions = "STA","ReUseThread"
$rs.Open()
$rs.SessionStateProxy.SetVariable("x",$x)
$cmd = [PowerShell]::Create().AddScript({
Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase
$x.w = [Windows.Markup.XamlReader]::Parse(@"<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MaxWidth="800" WindowStartupLocation="CenterScreen" WindowStyle="None" SizeToContent="WidthAndHeight"><Button Name="test" Content="Starte Installation"/></Window>"@)
$x.test = $x.w.FindName('test')

$x.test.Add_Click({
    $x.Host.Runspace.Events.GenerateEvent( "TestClicked", $x.test, $null, "test event")
} )

$x.w.ShowDialog()
})
$cmd.Runspace = $rs
$handle = $cmd.BeginInvoke()
Register-EngineEvent -SourceIdentifier "TestClicked" -Action {$Global:x.host.UI.Write("Event Happened!")}

My question is whether it is possible to raise a non-GUI based event from the runspace which can be handled in the PowerShell host using the Register-EngineEvent?

I tried New-Event from within the runspace which is "-forward"ed through another engine event in the same run space hoping that it will be received by the PowerShell Host Engine Event but it does not appear to have worked. The fact that the above GUI based event has worked, I am hopeful there has to be a way for the non-gui based runspace.

Thanks in advance



All users except for users in the OU 'domain/cluboffice/SAP'

$
0
0

I am hoping not to edit this that much but I would want all users except those in the Active Directory OU 'domain/cluboffice/SAP'.  I have tried several iterations from different posts here and I just can't get it to work.  I was hoping someone could help with my existing script.

Get-ADUser -Filter { (ObjectClass -eq "user") -and (Enabled -eq $true) } -Properties Mail,otherHomePhone |
Select-Object GivenName,Surname,userPrincipalName,mail,@{n="otherHomePhone";e={$_.otherHomePhone[0]}} |  
Export-Csv -NoType "jper263a.csv"

How to define a variable

$
0
0

hi all,

I've a requirement to define a variable to store a directory path and used it in my ps script.  below is the script

param([String]$DatabaseName)
[string]$db = 'Catalog='+ $DatabaseName
(Get-Content C:\SS\Load.dtsConfig) | 
Foreach-Object {$_ -replace "Catalog=([A-Za-z0-9_]+)", $db} | Set-Content C:\SS\Load.dtsConfig

I want to avoid hard coding of path C:\SS\Load.dtsConfig, instead I want to have a variable to store root path and I would like to just add the file name (Load.d)

can some one help me in modifying this script.


Neil

user logon count

$
0
0

I am trying to get user logon count

I am able to run a command:

Get-QADUser username -properties logoncount | select logoncount

and get a complete count. What if i need to get a number for a week? or a month?

Thank you.


How do I access this forum using an RSS feed?

$
0
0

How do I access this forum using an RSS feed?

I used to be able to do that.

Start a script on a remote computer

$
0
0

All I want to do is send a command to a list of computers to start a script I have on each computer. The remote script will need to be entirely UI based.

I have tried using the invoke-command -filepath $filepath technique and it cannot run gui forms remotely (If I'm mistaken PLEASE tell me)

I am currently trying to deploy a version that runs a scheduled task on the computers to execute said remote script. Unfortunately this only works for windows 8.1+ and I'd like to have one that works for windows 7. 

Any advice?

Wait until child job is completed

$
0
0

hello

i have to run a job  that copy 10 GB size of folders to 20 remote computers, and want to immediatley trigger another script when the chils job copy is completed on one of the remote computer 

start-job -name copyjob {
foreach ($computer in $computers) {   
Copy-Item c:\source -Destination \\$computer\c$\dest -Recurse      
}# end FOREACH

get-job |wait-job

when the child job is completed on one of the remote computer execute the script notification.ps1 , the problem with get-job | wait-job is that it wait until the job is completed on all 20 computers

or how we can get the computer on which the child job copy is completed

than you

Output format depends on hower PowerShell is invoked?

$
0
0

Hi,

I am currently developing a script to collect information about the software installed on client computers which is based on Jaap Brasser's Get-RemoteProgram.ps1 (https://gallery.technet.microsoft.com/scriptcenter/Get-RemoteProgram-Get-list-de9fd2b4). Depending on how I invoke the script, the format of the output is different...

When I start PowerShell (on Windows Server 2012 in case it matters) and issue the command 

.\Get-RemoteProgram.ps1 | out-file result.txt -encoding Default

the column containing the program name is 100 characters wide. However, if I am running the command from the shell like

Powershell -command ".\Get-RemoteProgram.ps1 | Out-File result.txt -encoding Default; exit"

that column is just 66 characters wide so that several program names are truncated.

Why is that, and how can I avoid it? Excuse me if that is a trivial question but I am not an experienced PowerShell guy...

Thanks, Georg.

Who's responsible for creating \Documents\WindowsPowerShell?

$
0
0

I'm working on stabilizing an 8.1 hyper-v VM. I'm having strangeness re: powershell functionality - no env variables are populated and no \Documents\WindowsPowerShell subdirectory. Is there a way to repair powershell on windows 8.1 - or otherwise re-set to a factory state? (which this really _should be but...)

thx

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>