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

Call function from target script at remote script

$
0
0

Hello,

My script looks like this:

cls
$RemoteServer = "zserver101"
$WorkItemID = "202"
$WorkItemState = "Stage to CONS"
Function LoglinesSmall
{
	Write-Host ""
	Write-Host "            -------------------"
	Write-Host ""
}
$script =
{
	param ($WorkItemID, $WorkItemState)
	#Region ########################## 	Get environment and state variable's ##########################
		$Staging_Directory = "c:\StagerTemp\"
		$Servername = $env:COMPUTERNAME
		$Currentuser = [Environment]::UserName
		Write-Host "Get environment and state to variable"
		Write-Host	"Current Username: " $Currentuser
		Write-Host "Work Item ID: "$WorkItemID
		Write-Host "Work Item State: "$WorkItemState
		$filevalue = "Current Username: " +$Currentuser +";Servername: "+$Servername
		New-Item c:\test_psscript.txt -ItemType File -value $filevalue -Force
		LoglinesSmall
}
Invoke-Command 	-ComputerName 			$RemoteServer `
						-ScriptBlock 	$script `
						-ArgumentList	$WorkItemID, $WorkItemState `
						-ErrorAction 	Stop

I get an error:

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

How can I call the function LoglinesSmall from target script at invoke-command?


Thanks Horst MOSS 2007 Farm; MOSS 2010 Farm; TFS 2010; IIS 7.5


DbNull Treatment in PoSh 2 vs. 3

$
0
0

PoSh v3 apparently interprets System.DbNull values differently than PoSh v2.

In v2, this expression returns True: [System.DbNull]::Value -eq $null. In v3, it returns False.

More specifically, in v3 ([System.DbNull]::Value).Length returns 1, whereas in v2 it returns $null.

Has anybody else seen this?

Read servernames from text file and perform action for all of them

$
0
0

Hi all

I have the following code

$CheckOut =Get-EventLog-ComputerNameNameofServer-LogNameSystem|where{$_.eventID-eq1074} |ft-AutoSize-Wrap|Out-String

$today = Get-Date -format d

Send-MailMessage -SmtpServerSMTPName-Toemailadress-Fromemailadress-subject"Reboots for $today"-Body$CheckOut

This will only do the server stored in NameOfServer. How do i change the code if i have a text file with servernames and the code must run for every name in the text file and output to the body of the email. Will appreciate any any help. Thanks in advance

Convet to HTML

$
0
0

How can I  convert my script to HTML?  I've tried with convertto-html but it comes out unformatted.

import-module failoverclusters
$clustername = 'myclustername'

$resources = get-cluster $clustername | get-clusterresource | select OwnerGroup, Name, OwnerNode, State | sort OwnerGroup | ft -auto

$objs = @()

$csvs = Get-ClusterSharedVolume -cluster $clustername
foreach ( $csv in $csvs )
{
   $csvinfos = $csv | select -Property Name -ExpandProperty SharedVolumeInfo
   foreach ( $csvinfo in $csvinfos )
   {
      $obj = New-Object PSObject -Property @{
         Name        = $csv.Name
         OwnerNode   = $csv.OwnerNode
         Size        = $csvinfo.Partition.Size
         FreeSpace   = $csvinfo.Partition.FreeSpace
         UsedSpace   = $csvinfo.Partition.UsedSpace
         PercentFree = $csvinfo.Partition.PercentFree
      }
      $objs += $obj
   }
}

$storage = $objs | ft -auto Name,@{ Label = "Size(GB)" ; Expression = { "{0:N2}" -f ($_.Size/1024/1024/1024) } },@{ Label = "FreeSpace(GB)" ; Expression = { "{0:N2}" -f ($_.FreeSpace/1024/1024/1024) } },@{ Label = "UsedSpace(GB)" ; Expression = { "{0:N2}" -f ($_.UsedSpace/1024/1024/1024) } },@{ Label = "PercentFree" ; Expression = { "{0:N2}" -f ($_.PercentFree) }}, OwnerNode
$results = ($resources + $storage)
$results

Thanks

Exchange move users in OU

$
0
0

Hello

Is it possible to prompt a admin who is running a PS script for information.  I am using the script below to get the users from an OU and move them from exchange 2003 DB to a new DB on exchange 2010.  We have a number of OU's in AD and when the script is run I would like it to Prompt for OU and the Target DB. 

Get-Mailbox -OrganizationalUnit "OU name" | New-MoveRequest -TargetDatabase " DataBase"

w

Problems with directory traversal

$
0
0

Hello,

I've recently started learning PowerShell and I've been running into some problems with this piece of code: pastebin.com/NRDjXKvW .

This is a part of the output i'm getting: 

D:\workspace\ASC
0

D:\workspace\ASC\tema1
1

D:\workspace\ASC\tema1\.idea
1

...etc. Where is that 0 and 1 coming from ? I keep getting errors "Get-Item : Cannot find path 'C:\Users\Kingaap\1' because it does not exist." Because of that.

And another thing, why isn't indent changing? I'm clearly passing $indent+1 in the inside function call.


Powershell Simple addition of array element integers

$
0
0

Hi

I'm able to do this simple task in VBS but can't figure out the syntax in PS.  Basically I need to gather the total disk space used for a number of files in different folders. Thant I can happily do and have a simple array with integer amounts: eg

 PS C:\> $size

 107327185408
 375809638912

the question is how do I add these element together? Seems simple but I can't find the correct formatting to sum these items.

thanks

powershell script to modify web.config file

$
0
0

HI All,

I have Powershell script to modify web.config file's connection String with XML modifier, but its not working as expected.

Task is powershell query should take the data from XML and update the config file and should update the XML child tag value which is <chngVal>

Below query which we are using Powershell and XML:-

XML content :-

<Test1PathBusinessService>
<Path>//configuration/connectionStrings/add</Path>
<chkAttrib>name</chkAttrib>
<chkval>PmcDatabaseEntities</chkval>
<chngAttrib>connectionString</chngAttrib> 
<chngVal>"metadata=res://*/PmcDatabaseModel.csdl|res://*/PmcDatabaseModel.ssdl|res://*/PmcDatabaseModel.msl:provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=zol78qp1bs.database.windows.net:initial catalog=dev_20130502;persist security info=True;user id=pmctstadmn;password=P@ssw0rd;multipleactiveresultsets=True:application name=EntityFramework&amp;quot;"</chngVal>

Powershell query:-

$XMLfilescontent =Get-ContentTest1Env.xml

./Xmlmodifier.exe /file:"D:\Bhupendra\MPN Portal\Dev\Src\Azure\Services\Pmc.Azure.Services.BusinessService\Web.config" /xpath=$XMLfilescontent.Settings.Test1PathBusinessService.Path /chkVal:$XMLfilescontent.Settings.Test1PathBusinessService.chkval  /chkAttrib:$XMLfilescontent.Settings.Test1PathBusinessService.chkAttrib /chngAttrib:$XMLfilescontent.Settings.Test1PathBusinessService.chngAttrib /chngVal:$XMLfilescontent.Settings.Test1PathBusinessService.chngVal

 

 

 


Output list view shows dotted lines

$
0
0

Hi

I'm writing a small script to get information about my servers. One of the things I'm doing is getting FSMO roles like this:

     $AllDomainControllers = Get-ADDomainController -Filter * -server $Domain
      Foreach ($DCController in $AllDomainControllers)
       {
       $ObjDCControllerInfo = New-Object PSObject
       $ObjDCControllerInfo | Add-Member -MemberType NoteProperty -Name OperationMasterRoles -Value $DCController.OperationMasterRoles
       }

When I output this custom object this is what I get:

        OperationMasterRoles       : {SchemaMaster, DomainNamingMaster, PDCEmulator, RIDMaster...}

Note the dotted lines at the end. How do I get ridd of this?

I tryed to output this to a file using width:

        $ObjDCControllerInfo | Out-File $LogFile -Width 120 -encoding unicode

but I still get the dotted lines in the log file. Is there maybe a limit on the size for NoteProperty type?


Best regards, Bjorn Moritz


How can I run diskshadow (List Shadows all) for multiple servers?

$
0
0
Hi all,

At the moment I have to logon to 20+ servers and check for any snapshots and clear them down. I want to automate the listing of the snapshots but it I cant seem to remotely rundiskshadow.

I have tried using powershell and psexec but not luck.

The manually process I go through at the moment is...

Logon to server

Open command prompt
Run "diskshadow"
then "list shadows all"

Any ideas?

Spooter

My first PowerShell script, also my first C# code -- extracting a zipped file

$
0
0

I'm familiar with coding in VBA but this is my first PowerShell script and my first C# code.

I've been tasked with writing a PowerShell script to unzip a file and then change the filename. Unzipping the file works fine if I hardcode the filename:

function Extract-Zip {
   param([string]$zipfilename, [string] $destination)
   $shellApplication = new-object -com shell.application
  
#   $zipPackage = $shellApplication.NameSpace($zipfilename) 
   $zipPackage = $shellApplication.NameSpace("C:\MyPath\SimpleZipname.zip")

   $destinationFolder = $shellApplication.NameSpace("C:\MyPath")
  
   $myfile = $destinationFolder.CopyHere($zipPackage.Items())
   Write-Host $myfile
}

Extract-Zip "C:\MyPath\SimpleZipname.zip", "C:\MyPath"

But if I try to use the same path passed in as a parameter, I get the error "You cannot call a method on a null-valued expression":

function Extract-Zip {
   param([string]$zipfilename, [string] $destination)
   $shellApplication = new-object -com shell.application
  
   $zipPackage = $shellApplication.NameSpace($zipfilename)
#   $zipPackage = $shellApplication.NameSpace("C:\MyPath\SimpleZipname.zip")

   $destinationFolder = $shellApplication.NameSpace("C:\MyPath")
  
   $myfile = $destinationFolder.CopyHere($zipPackage.Items())
   Write-Host $myfile
}

Extract-Zip "C:\MyPath\SimpleZipname.zip", "C:\MyPath"

What am I doing wrong?

I'm on Windows 7. This will eventually go on a Windows 2008 Server.

Thanks,

Greg

Exchange Message Count

$
0
0

Hi There,

I am using the cmdlet below to extract the number of messages received by a users in Exchange 2010. it works fine and give me the message count however I cannot find a way to output the recipient name.

Any help on this would be appreciated.

get-messagetrackinglog -server svrname-recipients user@domain.com -Start "04/01/2013 00:00:00" -End "04/30/2013 00:00:00" |  measure-object



Check Whether drive exists

$
0
0
function get-checkdrive($server)
{	
		write-verbose "check drive -started"
	    $check= 'D:\' # no escape 
		$testobj=get-wmiobject win32_volume -filter  "DriveLetter= 'D:'" -computername $server
		$caption= $testobj.Caption
		if($check -contains ($caption) )
		{ 
			$TotalGB=@{Name="Capacity(GB)";expression={[math]::round(($_.Capacity/1073741824),2)}}
			$FreeGB=@{Name="FreeSpace(GB)";expression={[math]::round(($_.FreeSpace /1073741824),2)}}
			$test=$testobj|Select Name , $TotalGB,$FreeGB	
		    write-verbose "check drive -Completed"
            return ($test)
        }
        else                
        { 
			write-output "$check doesnt exist"
        }
}

I have wriitten this script to check whether the D DRIVE exist or not. the script works fine but the problem is if D doesn't exist it doesn;t print drive doesnt exist instead print

@{Name=D: , Freespace(GB)=0 , Capacity(GB)=0). please help.

New-PSSession limited to 25

$
0
0

I am trying to start 50 sessions on a server, but once I pass 25 new sessions, I get this error:

New-PSSession : [MyServer] Connecting to remote server systemarchi failed with the following error message : The WS-
Management service cannot process the request. This user has exceeded the maximum number of concurrent shells allowed f
or this plugin. Close at least one open shell or raise the plugin quota for this user. For more information, see the ab
out_Remote_Troubleshooting Help topic.

WinRM settings:

Config
    MaxEnvelopeSizekb = 500
    MaxTimeoutms = 60000
    MaxBatchItems = 32000
    MaxProviderRequests = 4294967295
    Client
        NetworkDelayms = 5000
        URLPrefix = wsman
        AllowUnencrypted = false
        Auth
            Basic = true
            Digest = true
            Kerberos = true
            Negotiate = true
            Certificate = true
            CredSSP = false
        DefaultPorts
            HTTP = 5985
            HTTPS = 5986
        TrustedHosts
    Service
        RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)
        MaxConcurrentOperations = 4294967295
        MaxConcurrentOperationsPerUser = 1500
        EnumerationTimeoutms = 240000
        MaxConnections = 300
        MaxPacketRetrievalTimeSeconds = 120
        AllowUnencrypted = false
        Auth
            Basic = false
            Kerberos = true
            Negotiate = true
            Certificate = false
            CredSSP = false
            CbtHardeningLevel = Relaxed
        DefaultPorts
            HTTP = 5985
            HTTPS = 5986
        IPv4Filter = *
        IPv6Filter = *
        EnableCompatibilityHttpListener = false
        EnableCompatibilityHttpsListener = false
        CertificateThumbprint
        AllowRemoteAccess = true
    Winrs
        AllowRemoteShellAccess = true
        IdleTimeout = 7200000
        MaxConcurrentUsers = 10
        MaxShellRunTime = 2147483647
        MaxProcessesPerShell = 52
        MaxMemoryPerShellMB = 1024
        MaxShellsPerUser = 52

I have other servers, where i'm not limited to 25 sessions. Does anyone have a clue where to fix this?


add file name without extension to combined output

$
0
0

 I have a script that combines all (.dat) files from a folder into a specific output file. I would like to write at the end
of each line the file name from where it originated. I do some backups to save my original files...

Filenames

505.dat
00 87 88 90

506.dat
00 87 88 90

desired ouput
00 87 88 90 505

00 87 88 90 506

Script:

$path='\\virtualdy\adv2\'
get-childitem -path $path *.dat | % {
       " Starting File Process....."  >> \\virtualdy\adv2\adv2.log
       $date = get-date -uformat "_%d_%m_%Y_%H%M%S.bak"
       "Set backup date to $date" >> \\virtualdy\adv2\adv2.log
       $newname=($_.fullname -replace ".dat",$date)
       "File backup name is $newname" >> \\virtualdy\adv2\adv2.log
       Rename-Item $_.fullname $newname
       "Renamed file to $newname" >> \\virtualdy\adv2\adv2.log
       (Get-Content $newname | Select -Skip 0) | Add-Content "$path\adv2.csv" -encoding ASCII
              
       Write-Host $_.fullname
      "Files Processed on $date are $_.fullname " >> \\virtualdy\adv2\adv2.log
}


  Thanks.


Asynchronous Timer Events not working when script run via batch file

$
0
0

Hello.

I have a PowerShell script that uses an Asynchronous Timer Event (background process) to measure how long a certain condition has been occurring before taking appropriate action.

This is working perfectly fine when I run the script inside PowerGUI but when I run the script using dot-sourcing or run it via a batch file the Timer Event actions are not firing.

Here is a code snippet.

$timer = New-Object System.Timers.Timer
$timer.Interval = 10000  
$timer.AutoReset = $true 
$timeout = 0


$action = { 
"timeout: $timeout" | Add-Content $loglocation

<more stuff here>

$timer.stop()

}

$start = Register-ObjectEvent -InputObject $timer -SourceIdentifier TimerElapsed -EventName Elapsed -Action $action $timer.start()

When it works, we will see the "timer: XX" output every 10 seconds written to the log.  But this is only happening when inside the editor.

So my question is why is my experience different when running the script inside PowerGUI versus via command line?  My thought is there's an issue with scoping but I'm not sure what the issue is.  I am not running these events inside any functions or loops (yet).


Do-While loop until input is null

$
0
0

Hello, I am trying to write a script to do something with user names that is entered in at the input.

$users = @() Do {$users += Read-Host "What is the username: "} until ($users -eq "")

I have that code so far, but the problem is, it doesn't exit until I hit 'ENTER' three times (so it gives 2 null values until it exits).

I viewed this thread: http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/cfb361d2-0868-414a-9b9c-6342df4437b1 , but I don't really understand the TRY/CATCH statement that's in there (that's marked as the answer) and if it's even needed for my use.

Thanks!

Powershell Get-WmiObject -Class Win32_LogicalDisk -ComputerName $k - not substitutes variable

$
0
0

hello

This is my first post, please be understanding.

This is my script

$hosty = net view
foreach ($j in $hosty) {
    if ($j -match 'ROW') { 
        $k = $j -replace '\\*'
        ForEach ( $i in (Get-WmiObject -Class Win32_LogicalDisk -ComputerName $k)) {
            $partycja = $i.DeviceID
                $wolne = $i.FreeSpace
                $rozmiar = $i.Size
                $nazwa = $i."Nazwa: $j""Partycja: $partycja""Miejsce wolne: {0:#.00 GB}" -f ($wolne / 1GB)
            }
        }
    }

Variable $k is not substitutes.

Please Help

Comparison of dhcp scope with AD sites & service through power shell

$
0
0

Hi All,

I am thinking of something that could parse through all Scopes in all DHCP servers and then make sure that there is a site and a subnet associated with that DHCP Scope. How can we get this done by using PowerShell script?

Thanks in advance....  

Error Handling during Import from CSV (Using Set-QADUser)

$
0
0

Folks,

I'm using the Quest Set-QADUser powershell along with the Import-CSV command (see below for syntax) and I am having some issues with error handling that I need advice on. Essentially the import works fantastic as long as the users in the source file are present in the AD..if however, they are not present the powershell import stops and no more information is updated.

I would like to know how I get the powershell to log the error to a log file and then continue to the next account in the import (CSV) file...

######################################

# Use Quest ActiveRoles Active Directory Powershell CMDLETs

Add-PSSnapin Quest.ActiveRoles.ADManagement

#Get Date

$now = [datetime]::now.ToString('yyyy-MM-dd')

IMPORT-CSV d:\oracle\scripts\pilot.csv | Set-QADUser -Identity {_.mail} | Out-File -FilePath ("d:\oracle\changelog\changelog_$now.log") -encoding ASCII -append -width 1000

########################################

Viewing all 21975 articles
Browse latest View live