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

I'm going to run a script, but how do I point to a worksheet in Excel?

$
0
0

I'm going to run a script, but how do I point to a worksheet in Excel?


Get Computer name and move

$
0
0

Hi all ,

i need help with small problem ,

i tried to create new script that know get all computer names that start with " ISR..." And then move them to another ou ,

i have 2 convention name on my organization name  , 1 - ISR , 2 -TLV  . 

some computers :

ISR2

ISR3

ISR4

some computers :

TLV2

TLV3

TLV3

 i tried this command "

Get-ADComputer -Filter * {Name -Like "TLV,"}  Error :

Get-ADComputer : A positional parameter cannot be found that accepts argument 'Name -Like "TLV"'.
At line:1 char:15
+ Get-ADComputer <<<<  -Filter * {Name -Like "TLV"}
    + CategoryInfo          : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

or if have another option -command can read both computers name and then move them


My Website:www.Pelegit.co.il Mcitp /Mcsa 2012

Remote Get-Service as Normal user require other privileges

$
0
0

Hello,

I my setup I have two Windows 2012 R2 servers.

From Computer1 I do a enter-pssession  to Computer2 as a normal user. (The user is in the group Remote Management Users)

On Computer2 I can do a get-process and it works. If I do a get-service it does not work.

Could this be because get-service automatically adds -computer . ? and it's then a double-hop?

So is there a trick to get it to work as a normal user?

Cannot open Service Control Manager on computer '.'. This operation might require other privileges.
    + CategoryInfo          : NotSpecified: (:) [Get-Service], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand

I Can't Update Help - UICulture es-ES

$
0
0

Enviroment: Windows 7 Spanish - Powershell 3

I try to execute:

update-help -Force -Verbose -UICulture es-ES

But, It reports an error that It can't update because there are no references for this UICulture

I try it with en-US UICulture,

update-help -Force -Verbose -UICulture en-US

But it doesn't work .

Help Me, please.

Thanks!


Get and then Move ( Computer name )

$
0
0

Hi all ,

One of the nice people here helped me with Powershell script ,

My goal is Get from Specific OU  computer names like ISR and TLV and then move them to Another OU ,

This is my Script :

Get-ADComputer -SearchBase "CN=Computers,DC=XXX,DC=com" -Filter {(Name -Like "ISR*") -And
(Name -Like "TLV*")} | Move-ADObject -TargetPath "OU=xxx-Computers,DC=XXX,DC=com"

I get error that " GetADcomputer is not recognized as the name of a CMDlet:

The term 'Get-ADComputer' 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.


My Website:www.Pelegit.co.il Mcitp /Mcsa 2012



Windows 2008 R2 (or 2012) : Daily backup script of folders to FTP ?

$
0
0

Hi,
I have a Windows Server 2008 R2 system.
And I want to make a daily backup (rotation 15 days) script of some folder to an FTP.

I found this super script : https://gallery.technet.microsoft.com/scriptcenter/The-ultimate-backup-script-819e52ee#content
But no option to FTP.

Do you know how to add an option to save on FTP ?

Thanks for your help :)

Powershell script to install Pidgin

$
0
0

Hello,

I want to install Pidgin in all the computers on the network and I want to do it via Powershell. I modified a script that i found and it looks like this:

$computers = Get-Content "C:\Users\administrator.INTERN\Desktop\Scripts\Pidgin\computers.txt"

foreach ($computer in $computers) {


#The location of the file
    $Install = "\\voyager\Software\015 Messenger Clients"

#The Install string can have commands aswell
  $InstallString = "$Install\pidgin-2.10.11-offline.exe"

	([WMICLASS]"\\$computer\ROOT\CIMV2:Win32_Process").Create($InstallString)
#Output the install result to your Local C Drive
	Out-File -FilePath c:\Users\administrator.INTERN\Desktop\Scripts\Pidgin\installed.txt -Append -InputObject "$computer"}

But when i execute it i get this messages:

Cannot convert value "\\192.168.9.104\ROOT\CIMV2:Win32_Process" to type "System.Management.ManagementClass". Error:"The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
At C:\Users\administrator.INTERN\Desktop\Scripts\Pidgin\install pidgin.ps1:18 char:2+     ([WMICLASS]"\\$computer\ROOT\CIMV2:Win32_Process").Create($InstallString)+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [], RuntimeException+ FullyQualifiedErrorId : InvalidCastToWMIClass

I know nothing about scripting.

Also if it is posible , does anyone knows hot to make it so Pidgin uses the windows credentials???

Thanks

unable to specify an array (range of numbers) as integer

$
0
0

hi friends

where am i wrong here?

PS C:\>1..100 -is [int]

 false           :-(

[int]$array = 1..100

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32".

$array = 1..100

$array -as [int]

$array -is [int]

false     :-(

my goal is to use that array in the following command:

Get-random $array -count 3



Can't use Install-Windowsfeature with the -Source property to install .Net 3.5

$
0
0

The command I'm running is:

install-windowsfeature -computername server1 -name net-framework-core -source d:\sxs

I get an error stating:

The source files could not be downloaded.
Use the "source" option to specify the location of the files that are required to restore the feature. For more
information on specifying a source location, see http://go.microsoft.com/fwlink/?LinkId=243077. Error: 0x800f0906

I have taken the ISO file I have and extracted the SXS folder to the D drive.  If I mount the ISO to the machine then it installs fine.  I can't figure out why it won't work when I specify the folder name locally.  I know I've gotten this to work in the past but I know I've also had a lot of trouble getting this to work.

Anyone have any idea why this isn't working?

Thanks.

Trying to replace text after a certain point

$
0
0
Hi guys, very new to PowerShell and am trying to make a script to automate a project that I have a huge deadline for so no rush. Here is what I'm trying to do...I have a large number of accounts that are changing from one group to another but are staying in the same OU in Active Directory. Because of this, their display names need to be changed. For example, I have "Jamma, Mam A UNITED STATES TEXAS" Where TEXAS needs to changed for all of the users that have UNITED STATES in their display name. Here is what I have:
Get-ADUser -SearchBase $OU -Filter {DisplayName -like "*UNITED STATES*"} -Properties displayname, initials | % SetADUser $_ -DisplayName ($_.Displayname -replace "UNITED STATES", $GoodUnit)}
In this, I need $GoodUnit to replace TEXAS with whatever other state I choose. So far, what this does is insert the state between UNITED STATES and TEXAS so it would look something like this "Jamma, Mam A UNITED STATES ARIZONA TEXAS" Can someone help me fix this line so I can make it remove the previous state and insert the correct one? The problem is that it isn't always TEXAS and sometimes there might be a misspelled state such as TEAXS or T EXAS so I need it to replace everything after UNITED STATES instead of simply specifying "TEXAS".
I hope my post is understandable, I've tried to find something similar all over Google and can't seem to find exactly what I want. I appreciate any assistance!

PowerShell v4.0 VS v2.0 question

$
0
0

Hello everyone, I have a question regarding using powershell commands in a mixed environment.

I have a management server running Powershell v4.0 and I have domain controllers running Powershell v2.0

Question is: Can I use the v4 powershell on the management server to invoke commands remotely on the domain controllers running powershell v2?

Keep into consideration that the commands *need* powershell v4 to run.

Example of the commands I am using:

Move-Item -Path cert:\LocalMachine\CA\D559A586669B08F46A30A133F8A9ED3D038E2EA8 -Destination cert:\LocalMachine\root

It basically moves a certificate from the Intermediate container to the trusted root container.

This command needs powershell v4, so can I perform it on the management server, remotely targetting the domain controllers?

Thanks.


Execute script on multiple servers

$
0
0

Hey everyone,

For a monitoring project i've created a script to create a certificate on a server and create a winrm https listener from the thumbprint. Script is underneath and feel free to use it :)

Now I want to execute this on a lot of servers, can anyone suggest how the best way to do this would be? I can't reboot the servers. Also any suggestions on what folder location the script would best turn on the servers would also be welcome.

Kind regards

$computername = [System.Net.DNS]::GetHostByName('').HostName
$ReqFile = "newwinrmreq.req"
$InfFile = @"
[NewRequest]`r
Subject = "CN=$computername"`r
KeySpec = 1`r
KeyLength = 2048`r
Exportable = TRUE`r
RequestType = CMC`r
[RequestAttributes]`r
CertificateTemplate= WebServerforWinRM"@
$FinalInfFile = "Cert_Req_Inf-ComputerName-" + ".inf"
New-Item $FinalInfFile -type file -value $InfFile
cmd /c "certreq -new $FinalInfFile $ReqFile"
cmd /c "certreq -submit -attrib certificatetemplate:"WebServerforWinRM" -config fednot.be\CASERVERNAME -f newwinrmreq.req newwinrmreq.cer"
cmd /c "certreq -accept newwinrmreq.cer"
$Thumbprint = (Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object {$_.Subject -match "CN\=$computername"}).Thumbprint
$hostnodom = hostname
cmd /c "setspn -s HTTPS/$computername $hostnodom"
$command1 = "winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname=""" + $computername + """;CertificateThumbprint=""" + $Thumbprint + """}"
cmd /c "winrm create $command1"


How to Connect to One Server, Extract Data, Connect to Second Server, and Insert that Extracted Data into Table on Second Server

$
0
0
I have the following code that connect to my Central Management Server and loops through each server extracting data and inserting into a table on a different server.  I only want to connect to one server, extract data, connect to a second server, and insert that data into a table on that second server.

I am new to PowerShell and I have been trying to tweek the code below to do this.  However, I have been unsuccessful.  Can anyone help me learn how to do this or point me to a web page demonstrating this?




<#
.SYNOPSIS
Creates a DataTable for an object
.DESCRIPTION
Creates a DataTable based on an objects properties.
.INPUTS
Object
    Any object can be piped to Out-DataTable
.OUTPUTS
   System.Data.DataTable
.EXAMPLE
$dt = Get-Alias | Out-DataTable
This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable
.NOTES
Adapted from script by Marc van Orsouw see link
Version History
v1.0   - Chad Miller - Initial Release
v1.1   - Chad Miller - Fixed Issue with Properties
.LINK
http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx
#>
function Out-DataTable
{
    [CmdletBinding()]
    param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)

    Begin
    {
        $dt = new-object Data.datatable  
        $First = $true 
    }
    Process
    {
        foreach ($object in $InputObject)
        {
            $DR = $DT.NewRow()  
            foreach($property in $object.PsObject.get_properties())
            {  
                if ($first)
                {  
                    $Col =  new-object Data.DataColumn  
                    $Col.ColumnName = $property.Name.ToString()  
                    $DT.Columns.Add($Col)
                }  
                if ($property.IsArray)
                { $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 }  
                else { $DR.Item($property.Name) = $property.value }  
            }  
            $DT.Rows.Add($DR)  
            $First = $false
        }
    } 
     
    End
    {
        Write-Output @(,($dt))
    }

} #Out-DataTable




Import-Module “sqlps” -DisableNameChecking



  

foreach ($RegisteredSQLs in dir -recurse SQLSERVER:\SQLRegistration\'Central Management Server Group'\CentralManagementServerNameHere\ | where {$_.Mode -ne "d"} ) 

  
$dt = Invoke-sqlcmd -ServerInstance "$($RegisteredSQLs.ServerName)" -Database "tempdb" -InputFile "D:\CMS\Scripts\T-SQL\DatabasesNotIncludedInAvailabilityGroup.sql" | out-DataTable
$dt
# Write data table to database using TVP 
$conn = new-Object System.Data.SqlClient.SqlConnection("Server=ServerWhereRepositoryDatabaseIs;DataBase=CMSRepository;Integrated Security=SSPI") 
$conn.Open() | out-null
"Connected"
$cmd = new-Object System.Data.SqlClient.SqlCommand("dbo.usp_InsertDatabasesNotIncludedInAvailabilityGroup", $conn) 
$cmd.CommandType = [System.Data.CommandType]'StoredProcedure'
#SQLParameter 
$spParam = new-Object System.Data.SqlClient.SqlParameter 
$spParam.ParameterName = "@TVP"
$spParam.Value = $dt
$spParam.SqlDbType = "Structured" #SqlDbType.Structured 
$spParam.TypeName = "DatabasesNotIncludedInAvailabilityGroup"
  
$cmd.Parameters.Add($spParam) | out-Null
$cmd.ExecuteNonQuery() | out-Null
$conn.Close() | out-Null


lcerni

Create hash of rolled-up values

$
0
0

I have coded myself into a corner.  I have a script where I read in a bunch of .csv files into a hash that has a number of invoice lines from different invoices, containing 3 keys: UNIT (the item number), QTY (the number of items purchased) and PRICE (the unit cost of the item).  I need to output a summary of the order, with a record for each unique UNIT and the total of the QTYs, like a pivot table.  My newness to Powershell has me frustrated trying to implement the business logic.  All I need to do is look for the presence of the UNIT and add it if not found, or replace the QTY with the sum of the current and new QTY.

But I can't get it to work.  Can anyone post for example code?

Thanks


tom Repetti

Executing a script calling a module from task scheduler not fully working

$
0
0

Hello,

We have a module that checks the datetime of certain backup files to make sure they are written within the past 3 days, then if it finds it, it will execute a lot of SQL stored procs from within Powershell.  This works fine when I manually execute it, but it doesn't execute past the import-module command when I call it from task scheduler.

Task Scheduler action: Start a Program
Program/Script: C:\Windows\system32\WindowsPowerShell\v1.0\Powershell.exe

Arguments: -noexit C:\Scriptsfolder\DBrefresh.ps1 #Leaving noexit for testing. Fails with or without.

When it finishes, I see that it imported the modules but none of the actions are taken.  Here is the script that I'm using to call the module.

param(
$SI = "localhost\QAInstance",
$BUPath = "\\backuppath\BackupsSubFolder\env\blah",
$DBN = ("Database1","Database2")
)

#Import-Module DBRestore -verbose -force
DBRestoreExecutor -BackupPath $BUPath -ServerInstance $SI -DBName $DBN
I have tried it with commenting out import-module and it still has the same effect.



PowerShell Script to get TFS ChangeSet Number

$
0
0

I'm trying to write a PowerShell script that will get the latest ChangeSet ID that was checked into a specified path. I wrote the script below and it works fine on my server but when I try to run it anywhere else it doesn't populate $releaseNumber with the ID, the variable stays null. On the other servers I can get the full ChangeSet object by removing the .ChangeSetID, but can't get just the ID. What am I doing wrong? Thanks!

Try{
Add-Type -Path "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.VersionControl.Client.dll"}
 catch {
    Write-Host "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.VersionControl.Client.dll"
    Write-Host "Message: $($_.Exception.Message)"
    Write-Host "StackTrace: $($_.Exception.StackTrace)"
    Write-Host "LoaderExceptions: $($_.Exception.LoaderExceptions)"    
        }

$server = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer("http://MYTFSSERVER:8080/tfs/MYCOLLECTION")


$vcServer = $server.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])

$releaseNumber = $vcServer.QueryHistory("$/MyPath/Dev/Source/Databases", "Full" , 1).ChangeSetID

$releaseNumber = "2015.0." + $releaseNumber + ".0"

Write-Host $releaseNumber

 

Update-Help cmdlet not able to update the help with https protocol.

$
0
0

Hi all,

 

I am using powershell 3.0 and trying to implement this updatable feature for our custom powershell module. But I getting the below error:


PS C:\Users\scorchsvc> update-help -Module <modulename> -Force
update-help : Failed to update Help for the module(s) 'modulename' : HelpInfoURI
 https://10.65.182.141/dev_releases/modulename/onlinehelp does not start with http.
At line:1 char:1
+ update-help -Module modulename-Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (HelpInfoUri:Uri) [Update-Help], Exception
    + FullyQualifiedErrorId : InvalidHelpInfoUriFormat,Microsoft.PowerShell.Commands.UpdateHelpCommand

I am able to get this work if I use "http". Error message clearly says that it only expects http. But in the Microsoft help topic for Update-Help cmdlet, it is mentioned that cmdlet works for both http and https both.

Here are my enteries:

  • HelpInforURI entry in module manifest file is:

                    HelpInfoURI = "https://10.65.182.141/dev_releases/modulename/onlinehelp"

  • HelpContentURI in HelpInfo.xml file is:

                   <HelpContentURI> https://10.65.182.141/dev_releases/modulename/onlinehelp</HelpContentURI>

 

  • I am running powershell as an administrator.
  • I am not behind any proxy.
  • Windows firewall is off.
  • I am mentioning it AGAIN that I am ABLE to update help for our custom module if I use http in HelpInfoURI.

 

Can any one please help?

 

Thanks,

Vinay Ravish.

select object which is not null

$
0
0

Hi,

Is there a way to only show the properties which has values

Ex : get-wmiobject win32_bios | select *

it will show the properties which does not have value. Is there any way ...we can just show only the properties which have vlaue.

Thanks
Neo

Powershell - Rename-item returning "Access to the path pathname is denied"

$
0
0

Hi Guys,

There are a few hits with this error relating to this error, but I have yet to find one that resolves the error.

Most of the problems have been UAC or the user doesn't have permissions etc.

I am pretty sure I have covered these off, but I am still getting the error.

Rename-Item -path "\\servername\scratch\0_THIS_WEEK" -newName "\\servername\scratch\1_LAST_WEEK" -ErrorAction Stop
Rename-Item : Access to the path '\\servername\scratch\0_THIS_WEEK' is denied.
At line:1 char:1
+ Rename-Item -path "\\servername\scratch\0_THIS_WEEK" -newName "\\servername\scratch\1_LAST ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (\\servername\scratch\0_THIS_WEEK:String) [Rename-Item], IOException

    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

I can not rename manually as a domain admin (who is also a local admin) and running as administrator.

The new path does not already exist.

I have confirmed (with effective access) that I have full control of this directory.

I have got the verbose logging for the error...

$error[0] | fl * -force
ErrorRecord                 : Access to the path '\\servername\scratch\0_THIS_WEEK' is denied.
StackTrace                  :   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate (Object input, Hashtable errorResults, Boolean enumerate)
at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
                                at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
                                at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
WasThrownFromThrowStatement : False
Message                     : The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Access to the path '\\servername\scratch\0_THIS_WEEK' is denied.
Data                        : {System.Management.Automation.Interpreter.InterpretedFrameInfo}
InnerException              :
TargetSite                  : System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject] Invoke(System.Collections.IEnumerable)
HelpLink                    :
Source                      : System.Management.Automation
HResult                     : -2146233087

Domain users have read rights to the top level of the share and read and write rights on the 0_THIS_WEEK directory.  I have tried removing the R/W rights on 0_THIS_WEEK in case there are file locks but this hasn't helped.

Is there a way to find out what is preventing the rename (ie file locks) so I can either disconnect this session or release the lock?

NB:  I have also tried using d:\scratch\0_THIS_WEEK rather than the share name with the same results.

Thanks

Glenn


How to use New-Object PSObject

$
0
0
$(Foreach ($mailbox in Get-Recipient -ResultSize unlimited -RecipientType UserMailbox) {
    $stat = $mailbox | Get-MailboxStatistics | Select TotalItemSize
    New-Object PSObject @{
        FirstName = $mailbox.FirstName
        LastName = $mailbox.LastName
        DisplayName = $mailbox.DisplayName
        TotalItemSize = ($stat.TotalItemSize/1.0GB)
        PrimarySmtpAddress = $mailbox.PrimarySmtpAddress
        Alias = $mailbox.Alias
        }
}) | Select FirstName,LastName,DisplayName,TotalItemSize,PrimarySmtpAddress,Alias |
Export-CSV C:\MailboxReport.csv -NoTypeInformation

The above code is returning:

FirstName,LastName,DisplayName,TotalItemSize,PrimarySmtpAddress,Alias
,,,,,
,,,,,
,,,,,
,,,,,
,,,,,
,,,,,
,,,,,
,,,,,
,,,,,

Do I need something like this:

 $object = New-Object PSObject
      Add-Member -InputObject $object ...

I'm trying to compile a report with data gathered from Exchange 2007 on Server 2003 x64 using PowerShell 1.0.

Viewing all 21975 articles
Browse latest View live


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