Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

Excel with powershell and this big problem of locale

$
0
0

Hi Folks, I'm getting C R A Z Y with this Excel/Powershell Stuff...

MY display language is EN

My input language is fr_CH

the following code : 

function Invoke([object]$m, [string]$method, $parameters)
{
	$m.PSBase.GetType().InvokeMember(
	$method, [Reflection.BindingFlags]::InvokeMethod, $null, $m, $parameters,$ciUS)
}
$ciUS = [System.Globalization.CultureInfo]'fr-CH'
$objExcel = New-object -com Excel.Application
$objExcel.visible = $True
$ci = [System.Globalization.CultureInfo]'fr-CH'
$objWorkbook = Invoke $objExcel.Workbooks Add
$objWorksheet = $objWorkbook.Worksheets.Item(1)
$objWorksheet.Cells.Item(1,1).FormulaLocal = "A value in cell A1."
Invoke $objWorkbook SaveAs "C:ScriptsTest.xls" > $null
Invoke $objWorkbook Close 0 > $null
$objExcel.Quit()

throw me the error : 

Exception calling "InvokeMember" with "6" argument(s): "Object does not match target type."
At line:3 char:1
+ $m.PSBase.GetType().InvokeMember(
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : TargetException

You cannot call a method on a null-valued expression.
At line:11 char:1
+ $objWorksheet = $objWorkbook.Worksheets.Item(1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Basically this happend when you have english Excel with non english locale.

My OS is in english but my Keyboard is in French-Swiss.

Please help me I'm getting crazy...


MCITP Enterprise Administrator / Server Administrator



Test MS Word Document’s hyperlinks using PowerShell

$
0
0

I need to go through the MS Word document to find all hyperlinks and test if links are OK. Most of hyperlinks pointed to SharePoint documents.

thank you.

Copy files and Add user Full Control permissions on inheriting files and folders

$
0
0

Hi, i am building a script to move userhome directories around.

When i move them i must ensure that the same user has fullcontrol permissions to his my documents folder and all the below files and folders.

I have tried it with get-acl, set-acl but it is not working.

I have also tried it like this:

 $acl = Get-Acl $user.homedirectory
 $Ar = New-Object  system.security.accesscontrol.filesystemaccessrule("$user","FullControl","Allow")
 $Acl.SetAccessRule($Ar)

 Set-Acl $newuserhomedirectory $acl

Des anyone know a way to do this?

Thanks

Is Export-PSSession saves credentials?

$
0
0

Hello,

Is Export-PSSession to module saves session credentials? Any comment would be greatly appreciated. Thank you!

Functions and Global Scopes

$
0
0

I am creating a powershell script which has a few functions within it. I am looking to see if there is a way to make the results of my function (an array) availiable outside the function. How can I make $ActivationStatus availiable outside the function?

$DAG = "DAG01US"
Function global:ActivationStatus
{
$ActivationStatus = @()
$Colitems = Get-MailboxServer | Where {$_.DatabaseAvailabilityGroup -eq $DAG} | Select-Object Name,DatabaseCopyAutoActivationPolicy
	FOREACH($ExchSvr in $Colitems)
		{
			$SrvName = $ExchSvr.name
			$ActPolicy = $ExchSvr.DatabaseCopyAutoActivationPolicy
			$ActStatus = New-Object -TypeName PSObject -Property @{"Server Name" = $SrvName"Activation Status" = $ActPolicy
			}
			$ActivationStatus += $ActStatus
		}
		$ActivationStatus
}
ActivationStatus
$ActivationStatus

PS Script only works in ISE - Creating Scheduled Task

$
0
0



$folder = 'd:\sharesroot\008-upload-stuff-here\'
$filter = '*.*'                            
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$timeStamp = $Event.TimeGenerated

Set-ExecutionPolicy -ExecutionPolicy UnRestricted



$EmailFrom = “EMAIL@gmail.com”
$EmailTo = “EMAIL@gmail.com”
$Subject = “File Added”
$Body = $name
$SMTPServer = “smtp.gmail.com”
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“USER”, “PASSWORD”);
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

}

Hi, i have this script and when i select the text in PowerShell ISE and click run --> it runs great.

If i right click on the Scrpt.PS1 File and click run... it does not.

I am trying to set up a scheduled task to run this and its not working however i am convinced the reason is my problem stated above ^^

I tried searching but was unable to resolve, how can i make my script just run by right clicking run, or ... or if i were to make a Scheduled Task, what would i need to run this.

Bonus Question:

I was wondering would any of you know what i'd add to this script to say... exclude a file type such as (  .txt   )??  This way i wouldn't be emailed every time a Text File appears but only other files.

Thank you....

been trying to get this thing working for 1.5 hrs now.


coding noob but trying.

Error using Invoke-SqlCmd

$
0
0

Receiving error using this script: The TSQL script runs fine but errors in powershell.

Exception             : System.NullReferenceException: Object reference not set to an instance of an object.

                           at BatchParser.ThunkVariableResolver.ResolveVariable(ThunkVariableResolver* , UInt16* varName, UInt16** varValue)

                           at BatchParser.Variables.ResolveVariable(Variables* , basic_string<unsigned short\,std::char_traits<unsigned short>\,std::allocator<unsigned short> >* name, basic_string<unsigned short\,std::char_traits<unsign

                        ed short>\,std::allocator<unsigned short> >* val)

                           at BatchParser.Batch.listall(Batch* , basic_string<unsigned short\,std::char_traits<unsigned short>\,std::allocator<unsigned short> >* str, IVariables* variables, Int32 mark)

                           at BatchParser.Batch.popall(Batch* , basic_string<unsigned short\,std::char_traits<unsigned short>\,std::allocator<unsigned short> >* str, IVariables* variables, Int32 mark)

                           at BatchParser.ExecutionContext.ProcessBatch(ExecutionContext* , Boolean hasNum)

                           at BatchParser.BatchParserYacc.reduce(BatchParserYacc* , UInt32 ulProd, UInt32 ulSize)

                           at SSYacc.doReduce(SSYacc* )

                           at SSYacc.parse(SSYacc* )

                           at BatchParser.BatchParserInternal.Parse(BatchParserInternal* , ParserState* , Boolean flushBatchBuffer)

                           at ManagedBatchParser.Parser.Parse()

                           at Microsoft.SqlServer.Management.PowerShell.ExecutionProcessor.ExecuteTSql(String sqlCommand)

                           at Microsoft.SqlServer.Management.PowerShell.GetScriptCommand.ProcessRecord()

TargetObject          :

CategoryInfo          : InvalidResult: (:PSObject) [Invoke-Sqlcmd], NullReferenceException

FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

ErrorDetails          :

InvocationInfo        : System.Management.Automation.InvocationInfo

PipelineIterationInfo : {0, 1}

PSMessageDetails      :

cls
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$server = Get-Content c:\SQL_SERVERS\2008_UPDATE_JOB_STEPS.txt
$updatejob = "C:\SCRIPTS\Maintenance\CURRENT\UPDATE_JOB_STEP.sql"

foreach ($server in $server)
{
try
{
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $server
Invoke-Sqlcmd -InputFile $updatejob -ServerInstance $server 
}
catch
{
$Error[0]|format-list -force
Write-Host "Error on $server"
}
}


How develop this regex for log file

$
0
0

Hi, guys!

I want execute a regex in log file as the example following:

<Databases><Database SiteCount="44" Name="SharePoint_Content" DataSource="sxp0996"><Site Id="33cb5b0b-4aac-4555-b7ca-08b07c52c180" OwnerLogin="SP\xabomes" InSiteMap="True"><Webs Count="1"><Web Id="d365bc63-a7f6-4f7c-92d5-69608dd30256" Url="/sites/w-pm" LanguageId="1046" TemplateName="STS#1" TemplateId="1" /></Webs></Site><Site Id="1fe4fe6a-cb4d-4003-b29b-262cd7eac801" OwnerLogin="SP\xabomes" InSiteMap="True"><Webs Count="1"><Web Id="70ea0212-d96d-4765-87ef-1dd0263660a1" Url="/page/dos_cmd" LanguageId="1046" TemplateName="STS#0" TemplateId="1" /></Webs></Site><Site Id="555485b7-5471-422b-9c1e-26bcd2e5c976" OwnerLogin="SP\xabomes" InSiteMap="True"><Webs Count="1"><Web Id="92efa137-6d7e-4e39-b0f5-fa1ad12308b6" Url="/sites/gest_muda" LanguageId="1046" TemplateName="STS#0" TemplateId="1" /></Webs></Site>

The result should create in new file for example:

http://mysite/sites/w-pm
http://mysite/page/dos_cmd
http://mysite/sites/gest_muda
Therefore, the role should be:
- after of find Url=
- then the value (Url=) will be extracted between the first pair of quotes
- Finally, the hiperlink (http://mysite) will be add with o value extracted above (pair of quotes)

Thank you.

Se eu estiver respondendo a sua pergunta, e a mesma tiver utilidade. Vote com útil. Se for minha dúvida, e você me ajudar na solução, terei o maior prazer em votar como útil. Esse é o espírito do Forum MSDN !!! Valew !


Code to match seperate, large list, in any order, at any index?

$
0
0

The below code works as expected for two short list.

$aList = @( '1', '2', '3', '4', '5' )
$bList = @( 'a', 'b', 'c', '5', '4' )
foreach ($b in $bList) { $aList | where-object { $_ -match $b } }

It matches the 5 and 4. But when I use it to match two much longer list (each a few thousand entries long, with the entries made up of multiple alpha numeric characters, it returns nothing. Am I missing a variable or something to tell PS to keep going till it finishes processes everything? (From Task Manager, I'm not seeing any spike in CPU or RAM when I try with the longer list.) Is there some maximum I should be aware of here?

PowerShell Initializing Error

$
0
0
PowerShell Initializing Error I am trying to initialize PowerShell in the command prompt by typing C:\>powershell   An error displays saying:   The shell cannot be started. A failure occurred during initialization: Object reference not set to an instance of an object.

Deleting Old Backup's with Powershell Skript fails!

$
0
0

Hello Community,

On my PC the Windows-own Backup Tool is making a FileBackup and Systemimage.
It's too bad that this Tool isnt deleting the Filebackups automatically when the HDD runs full. So i want to delete it automatically with a Powershell Script. I know that there are several other ways to do this, but i want to do this with Powershell.

The System and Data i want to Backup lies on a intern HDD "C:". It will be backed up on an external HDD with 1TB "I:".

I put a few Test-Backups on the external HDD to test my Skript, but when i run it, they are'nt deleted. When i put some Datatrash on the Disk they are succesfully deleted. Why not the Test-Backups?

Here the Script:

--------------------------------------------------------------------------------------------------
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$princ = New-Object System.Security.Principal.WindowsPrincipal($identity)
if(!$princ.IsInRole( `
    [System.Security.Principal.WindowsBuiltInRole]::Administrator))
     {
    $powershell = [System.Diagnostics.Process]::GetCurrentProcess()
    $psi = New-Object System.Diagnostics.ProcessStartInfo $powerShell.Path
    $script = $MyInvocation.MyCommand.Path
    $prm = $script
   foreach($a in $args) {
     $prm += ' ' + $a
   }
   $psi.Arguments = $prm
   $psi.Verb = "runas"
   [System.Diagnostics.Process]::Start($psi) | Out-Null
   return;
 }


echo Beginne
Start-Sleep -s 5

$now = get-date
dir "I:\" | where {$_.LastWriteTime -le $now.AddHours(-0)} | del -recurse -force

Start-Sleep -s 7
--------------------------------------------------------------------------------------------------

I hope someone knows what to do,

Yours faithfully,

ToniLovesHisPrivacy


Powershell script to set the Computer Description field in AD to the display name - office number of the last person to login to a computer

$
0
0

I would like to create a Powershell script to set the Computer Description field in AD to the display name - office number of the last person to login to a computer. I've taken a couple posted ps scripts and have put this script together, but rather than using the username I would like to use the user's display name + office number:

Get-QADComputer -OSName "Windows 7*" | foreach{

    $name = $_.name

# would like to use display name + office number instead of username

    ((Get-WmiObject Win32_ComputerSystem -ComputerName $name -EA Stop).UserName)
    Set-QADComputer $name -Description

}

Powershell Forms

$
0
0

Hi, 

Whats wrong i this line? Keep getting "You cannot call a method on a null-valued expression."

$client = $wsus.SearchComputerTargets($server)

edit: 

$button_search_Click={
$wsusserver = $combobox_wsusserver.Text
$server = $textbox1.Text
$client = $wsus.SearchComputerTargets($server)
$richtextbox1.Text = $Client
}



convert internal write-progress to Windows.forms.progressbar

$
0
0

If I'm running a cmdlet that takes awhile, often times it will put up the write-progress status bar.  Is there any way to redirect or capture and reshape that progress information to the windows.forms.progressbar GUI element?

Obviously, if my own code has some kind of long loop, I can put up my own progressbar GUI element and update it on each iteration, but how can I do that if I'm just running a single command?  In this particular instance, I would like to make a single export-fimconfig call and have the progress appear in a GUI progress bar (since the PoSh console is not visible at all).

Thanks.

Scripts needed

$
0
0
Hi,

I need the script to get these below

1.Export all the services in HTML format
2.Export the IPCONFIG/ALL details in the HTML format
3.Get the Physical network card details with Speed, Coonection status all in HTML format

Can any one help me this?

Looking to report on drive space less than 1 gig (help with my script)

$
0
0

Can anyone help with my script, I am trying to only report on c drives equal or less than 1gig, but my following script wont work.

$computers = gc c:\scripts\list.txt               

foreach($computer in $computers) {

   Start-Job -Name $Computer -ScriptBlock { 

        Param ($Computer)

        Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk -Filter "DeviceID='C:'" | where {"freespace" -le 1000} | ForEach {

            $freeSpaceGB = $_.FreeSpace   

                New-Object PSObject -Property @{

                Computername = $computer.ToUpper()

                DeviceID = $_.DeviceID

                VolumeName = $_.VolumeName

                SizeGB = ("{0:N2}" -f ($_.Size /1GB))

                FreeSpaceGB = ("{0:N2}" -f ($_.FreeSpace /1GB))

                UsedSpace = ("{0:N2}" -f (($_.Size /1GB)-$freespaceGB))


            }

        }

    } -ArgumentList $Computer

}

       

Where-Object question or Filtering question

$
0
0

Hi everyone,

I would like to exclude items from a list in a text file by name. Using get-content and where object, is there a better way to exclude multiple items?

My example:

get-content .\mylist.txt | where-object {$_ -notmatch 'butter' -and $_ -notmatch 'cheese' -and $_ -notmatch 'milk'}

Seems like a lot of typing, especially if say I want to exclude 10 values or more, not just the 3 above....

Thanks,

Get-ADUser Output Strings

$
0
0

Hi There,

When I use the following command in the PS console window, the output I get is:  "Matthew". (Which is the GivenName for that user)

Get-ADUser -identity primem | Select-Object givenname

But when I use the same command as part of a script that exports to CSV I get a different output, " @{GivenName=Matthew} "

What I want to do is use the fields in the CSV in a mail merge for a whole bunch of users, using the GivenName at the top of the email. ie. "Hello <GivenName>,"

It's no good to me in the "@{GivenName=Matthew}" format, I just want the name.  How can I get it to output in the same format as it does in the console window?

Many thanks.

use write-host to output the array item

$
0
0

I am new to Powershell. I wrote below script.

#*************

$strComputerName = $env:COMPUTERNAME
$isCluster  = “NO”
$clusterName = ''
$node1 = ''
$node2 = ''
#*=============================================================================
#* Check if it is a windows cluster
#*=============================================================================
$ServiceName = "cluster Service"
$service = Get-Service -display $ServiceName -ErrorAction SilentlyContinue
 $isCluster
if ( ! $service ) { $isCluster  = “NO” } else { $isCluster  = “YES” }

if ($isCluster  -eq “YES” )
 { import-module failoverclusters -ErrorAction SilentlyContinue
   $nodes = get-clusterNode |select-object name
   $node1  = $Nodes[0]
   If ($nodes.count -gt 1) {$node2  = $Nodes[1]}
   $clusterName = get-cluster |select-object name
   Write-Host “$strComputerName is running windows cluster service and clsuter name : $clusterName , Nodes:  $node1 , $node2"
  }
Else { Write-Host “$strComputerName is a standalone server”  }
 
#***********************

Below is the output of Write-Host “$strComputerName is running windows cluster service and clsuter name : $clusterName , Nodes:  $node1 , $node2"

QRTXSQLN2 is running windows cluster service and clsuter name : @{Name=QRTXSQLN2cls} , Nodes:  @{Name=QRTXSQLN1} , @{Name=QRTXSQLN2}

My Question:

I do not undertsnad why $node1, $node2 and $nodes variables are arrays. I need the value in these values to be the pure string variables. I will using those variables and write to a sql server table later.

I am trying to get below output from write-host-

QRTXSQLN2 is running windows cluster service and clsuter name : QRTXSQLN2cls , Nodes:  QRTXSQLN1 , QRTXSQLN2



Configure SSO for Office 365?

$
0
0

I've been following the instructions at: http://technet.microsoft.com/en-us/magazine/jj631606.aspx

For the sake of background, I will explain that I have a public domain name (for my website) which is a.com, and the name for my AD Domain is the same name, but ending in a .local suffix.  I have configured the UPN suffixes for my user accounts in AD to allow the users to log on using the .com domain.

I have completed the steps from the link above up to the point where you use PowerShell to connect to Office365 and issue the following command: 

Set-MsolAdfscontext -Computer <FQDN of ADFS Server>

Now, in my case, the FQDN of my ADFS server is in the ".local" domain, not the ".com".  So, when I run the command, I get this result:

Set-MsolAdfscontext : The 'Microsoft.Adfs.PowerShell' Active Directory Federation Services 2.0 snap-in for
Windows PowerShell could not register on '<purposely removed>' computer.  Make sure that you either specify the name
of the Active Directory Federation Services 2.0 server using the -Computer parameter or that you are running
the installation on the AD FS 2.0 server.
At line:1 char:1
+ Set-MsolAdfscontext -Computer localhost
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Set-MsolADFSContext], FederationException
    + FullyQualifiedErrorId : GenevaPowerShellSnapInNotRegistered,Microsoft.Online.Identity.Federation.Power
   shell.ContextCredentialsCommand

For the sake of being thorough, the server on which I am trying to run this command is the DC of my domain, as well as the ADFS server.  It is a VM running Server 2012.

Any assistance is appreciated.

Thanks!

Viewing all 2562 articles
Browse latest View live


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