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

Powershell 3 compatible with .net.4.5

$
0
0

Hello, i have multiple machines with Powershell 3 ( Wmf 3) and .net 4.0 installed. Can i install .net 4.5? Does this cause any problems?

best regards, arhill


http://www.administrator.de/


Type already exists?

$
0
0

I am using Add-Type but I am getting the error:

Cannot add type. The type name 'TestSetup' already exists.

Can I tell if a type already exists and remove it so that I will not get this error?

Thank you.



Kevin Burton

Storing Credentials to be used as a different user - instantiation issue of securestrings

$
0
0

I have services which require certain credentials to log in and i am attempting to automate this process to run certain jobs. I've attempted storing password data as a securestring; however, secure string locks the encryption to the uesrid that encrypted it, effectively making it useless to anyone else attempting to access the password. 

To bypass this ive written a complex way of getting random numbers and letters and passing them into the secure string method; however, does anyone know if the code below would solve the instantiation problem?

PS:> # Save credentials for future use
PS:> $creds | Export-Clixml -Path c:\a.clixml

PS:> # Use the saved credentials when needed
PS:> $savedCreds = Import-Clixml -Path C:\a.clixml

Does anyone know if this uses a form of encryption that incorporates (instantiates) the userid into the file?

I.E. If i store it like this, can i pass my creds to a service to use or use them as SYSTEM on another box or are they only available to the ID i created them in? 

Mount-DiskImage in a remote session exeception- Cannot process Cmdlet Definition XML for the following file:

$
0
0

Hi everybody,

I have a strange problem with Mount-DiskImage command.

Environment: Windows server 2012 without any updates.

All scripts signed as it was in Hanselman's blogpost

http://www.hanselman.com/blog/SigningPowerShellScripts.aspx

First script(script1) executing on one machine (server1), then copy another script(script2) to the remote server(server2) and run script2 in a PS-Session. Both are signed. Certificates are located on both servers.

In a script I tried to

 Import-Module Storage
 $mountVolume = Mount-DiskImage -ImagePath $ImageSourcePath -PassThru

where ImageSourcePath is a networkpath to iso image.

But getting exception.

Exception Text:

Cannot process Cmdlet Definition XML for the following file:
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Storage\Disk.cdxml. At line:138 char:17
+                 $__cmdletization_objectModelWrapper = Microsoft.PowerShell.Utili ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Executable script code found in signature block.
At line:139 char:17
+                 $__cmdletization_objectModelWrapper.Initialize($PSCmdlet, $scrip ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Executable script code found in signature block.
At line:143 char:21

When I look into the C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Storage\Disk.cdxml I didn't get what's happend, because in line 138- was xml comment.

Any ideas?

IF Statement help - PowerShell

$
0
0

Hi,

I am trying to remove and add a group if a user is a member but the IF STATEMENT is not quite there.  It does not loop through every user in the spreadsheet.  Any assistance would be much appreciated, it's almost there:

$csv = Import-Csv "c:\SCRIPTS\users.csv"

Function switch-Office {
remove-adgroupmember -Identity "appmsoffice2003" -Member $sam -Confirm:$false
Add-ADGroupMember -Identity "appmsoffice2010" -Members $sam -Confirm:$false
}


Function switch-Outlook {
remove-adgroupmember -Identity "appmsoutlook2003" -Member $sam -Confirm:$false
Add-ADGroupMember -Identity "appmsoutlook2010" -Members $sam -Confirm:$false
}


foreach($row in $csv)
{
$sam = $row.sam

GET-QADUSER $SAM

IF (get-qaduser $SAM -MEMBEROF 'AppMSOffice2003')
{switch-office}
IF (get-qaduser $SAM -MEMBEROF 'AppMSOutlook2003') {
switch-office
}
}

I just need the IF loop tweaking, thanks, Matt.

[DOC BUG] in Start-Job cmdlet parameter -FilePath

$
0
0

In http://technet.microsoft.com/en-us/library/hh849698.aspx, it can be read:

<#

-FilePath<String>

... Enter the path and file name of the script or pipe a script path toStart-Job...

... 

Accept Pipeline Input? false

#>

The 2 informations are contradictory.

First, the documentation says it's possible to pipe data to Start-Job cmdlet's -FilePath parameter.

Later, it says this parameter doesn't accept pipeline input.


... don't disturb ... life is short, and I have to think what I'll do next ...

[BUG] in Start-Job cmdlet when piping job's name to the cmdlet: the resulting job can't be found by Receive-Job cmdlet.

$
0
0

Consider this script:

$job=[pscustomobject]@{Name='Qwerty'} | sajb -ScriptBlock {ps}

The job is created, successfully, with the name specified above.

It can be seen commanding:

gjb

Nonetheless, trying to receive the result from it (the job) results in job not found error.

rcjb -job $job


... don't disturb ... life is short, and I have to think what I'll do next ...

PCI Slot finding

$
0
0

Hi,

Is it possible using powershell to find PCI slot number of physical NIC card attached to server.
I am preparing Network inventory sheet for HyperV 2012 R2 project.


Setting Scope HyperV 2012 R2 What replaced ScopeOfResidence?

$
0
0
Basically, I want to know how to set the scope for a hyper-v vm in Server 2012 R2. I work at an academic institution, we intend to upgrade our 2008 R2 servers to 2012 R2 but before we can do that we need our vm creation script to work properly. In older editions that have the WMI v1 namespace it used to be to set the scope for a vm you did so by modifying Msvm_VirtualSystemGlobalSettingData.ScopeOfResidence. In the WMI v2 namespace Msvm_VirtualSystemGlobalSettingData has been removed and most of its features have been placed in Msvm_VirtualSystemSettingData. ScopeOfResidence however is not in there and I can't find it or anything that sounds the same in any of the virtual system classes. Below is the unedited portion of the old script I am having trouble converting to the v2 namespace. Someone please help, I need this working by the end of the month or I am going to have to abandon the server upgrade entirely.

# Set Scope!
$VM_Service = get-wmiobject -namespace root\virtualization Msvm_VirtualSystemManagementService
$ListofVMs = get-wmiobject -namespace root\virtualization Msvm_ComputerSystem -filter  "ElementName <> Name "  | `
    where { $_.ElementName -like $vmName }
foreach ($VirtualMachine in $ListofVMs) {
        if ($VirtualMachine -ne $Null)
        {
        $VMGlobalSetting = get-wmiobject -namespace root\virtualization Msvm_VirtualSystemGlobalSettingData | where `
           { $_.ElementName -like "*$($VirtualMachine.ElementName)*" }

         $VMGlobalSetting.ScopeOfResidence = $scope

         $VM_Service.ModifyVirtualSystem($VirtualMachine.__PATH, $VMGlobalSetting.psbase.Gettext(1))

          }
Write-Host "Virtual Machine" $vmName "Added to Scope" $scope
}
# End of Set Scope

Get Processes by Username without WMI

$
0
0

How about this for a solution that doesn't involve WMI.

  

#This will retrieve all processes by userid

$UserName="lsqa2setup"

$Processes=get-process|selectprocessname,Id,@{l="Owner";e={$owners[$_.id.tostring()]}}|Where-Object{$_.owner-eq$UserName}

#then filter the value you need

Foreach($Processin$Processes) { Write-host$Process.ProcessName }

Need VB script for SMTP Status

$
0
0

Hi guys,

Need a script for finding the SMTP status like Enable or disable for the list of servers.


Regards,

SreeM


Wait for process to start then loop start-process for another process until started

$
0
0

I am trying to wait for a process to start, once started, then loop start-process again for a second process until it starts, then wait until the first process has stopped and exit script. Heres my script. Even though the process has started already it still says waiting. What am i doing wrong. Its very frustrating


$ProcessActive = Get-Process xawoacp.exe -ErrorAction SilentlyContinue

if($ProcessActive -eq $null) { Do {write-host "waiting...."} until($ProcessActive -eq $True)

$Target = "xpwosrvr"

$Process = Get-Process | Where-Object { $_.ProcessName -eq $Target }

do { Start-Process -FilePath "D:\xpwosrvr.exe" -Wait}

while ($Process.Count -lt 1)

util ($ProcessActive -eq $null)


convert ObjectGuid attribute to HEX

$
0
0

I need to convert a computers active directory GUID into hex. The format I need this in is displayed the way I need it when I view the GUID through Active Directory Users and Computers, but every attempt to convert the return from [adsi] returns a different result than I get when I view the value through the application. 

All I want to do is display the following in HEX

([adsi]"LDAP://CN=SomeComputer,CN=Computers,DC=SomeDC,DC=com").objectguid

multiple table format through email using powershell

$
0
0

Hi All,

I have a powershell script which executes a SQL Query on three SQL instances and provides the result in table format through email. The output email contains all the result of the query in a single output itself. Please help me, I have provided the code which I am using

Sample output format which I am getting: 

ServerInstance DatabasenameEnabledStatus

Instance1Database1Enable

Instance1Database2Enable

Instance1Database3Enable

Instance2Database1   Enable

Instance2Database2Enable

My requirement is I should get two table formatted email like below:

Database status of Instance 1

ServerInstance DatabasenameEnabledStatus

Instance1Database1Enable

Instance1Database2Enable

Instance1Database3Enable

Database status of Instance 2

ServerInstance DatabasenameEnabledStatus

Instance2Database1   Enable

Instance2 Database2 Enable

#This PowerShell Scrip is well-suited with PowerShell V3.0
#import SQL Server module
#Import-Module SQLPS -DisableNameChecking 
#get all the instances and temporarily store them in a variable
$ServerInstances = Get-Content "C:\SQL_Servers.txt"
$scriptFile = "C:\restoredetails_mountdrive.sql"

$a = "Hi All, <BR> <BR>"
$a = $a + "Below is the TESTING Environment. This is an auto-generated mail.<BR><BR>"
$a = $a + "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 0px;width:150%;cellspacing=0 ;padding: 10px;border-style: solid;border-color: black;background-color:#43B2B2;font-family: Verdana;font-size:13 }"
$a = $a + "TD{border-width: 0px;width:150%;cellspacing=3 ;padding: 10px;border-style: solid;border-color: black;text-align: left;background-color:white;font-family: Verdana;font-size:11}"
$a = $a + "</style>" 
#he database we want to execute it against, regardless of the instance
$DBName = "master" 
#iterating through all instances.
$ServerInstances |
ForEach-Object {
#For each instance, we create a new SMO server object
$ServerObject = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $_
#use the Invoke-Sqlcmd cmdlet to execute the query
#we are passing in the pipeline is the instance name, which is $_
 $refresh_output1 = $refresh_output1 + (Invoke-Sqlcmd `
-ServerInstance $_ `
-Database $DBName `
-InputFile  $scriptFile
#-Query $SQLQuery
)

[string]$tst =   $refresh_output1 |convertTo-Html -Head $a -property InstanceName, DatabaseName,OverallStatus  | Out-String 

    write-output " " 
}

[System.Net.Mail.MailMessage]$message = New-Object System.Net.Mail.MailMessage("emailid.com", "toemailid.com", "Subject", $tst )

[System.Net.Mail.SmtpClient]$client = New-Object System.Net.Mail.SmtpClient("smtpserver",25)
$Message.IsBodyHtml = $true
$client.Timeout = 100

$client.Send($message)

Internet Explorer tab titles

$
0
0

Trying to write a script to retrieve the title for all open Internet explorer tabs on a terminalserver.

I have found several scripts to get all internet explorer tabs on a logged in user, but I need to get it for all logged in users

get-process | select name,mainwindowtitle get all iexplore sessions and the title of the main window, but how to get the title for all tabs, for all terminal server users?

regards

Andreas


how to create TFS query link

$
0
0

I have below TFS query and I want to create a link for TFS like QueryLink so when we click the link it should open the query in web in TFS

please let me know how do I create the link.

$tasktfs = $tfs.query("
    SELECT *
    FROM WorkItems
    WHERE [System.TeamProject] = 'DO'
    AND [System.WorkItemType] = 'RDTask'
    AND [System.AssignedTo] = '$team'
    AND [System.ChangedDate] >= '$fromDate'
    AND [System.ChangedDate] <= '$toDate' ")

Thanks


Thanks,

GetComputerSite()'s server list is empty...

$
0
0

Hey folks -- So I'm working in an Active Directory environment that is healthy.

I've run: 

[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite()

And expected the servers configured for my current site ("Site A") to be populated in the returning object's Servers property. However, the property returns empty.

If I run "Get-ADDomainController" for a server that I would expect to be in that list, I see that it is in the correct site. Has anyone run into a situation like this?

Oh - also - all of the other properties for that first command are as expected.

Thanks


G. Samuel Hays, MCT, MCSE 2012, MCITP: Enterprise Admin

Blog:gsamuelhays.blogspot.com

twitter:twitter.com/gsamuelhays

1 profile many comptuers

$
0
0

As a network adminisitrator and Powershell user I find myself having to copy my profile to every computer I log into in order to retain the same functionality across systems.  Is there a way to centralize my own $profile?

I tried to follow the advice @ http://blogs.technet.com/b/heyscriptingguy/archive/2012/05/23/use-a-central-file-to-simplify-your-powershell-profile.aspx under the portion that says "Use Your Own Profile".

I had took this to mean that in the orginal profile I needed to reference the profile I wanted to use like it regular scripts but this doesn't seem to be working & I'm now uncertain if I even can do it at all.  What I tried was this:

dc \\this\network\share
.\MyProfile.ps1

Doesn't seem to be working however.

Is what I want to do possible and if so what's the best way?


# When I wrote this script only God & I knew what I was doing. # Now, only God Knows! don't retire technet http://social.technet.microsoft.com/Forums/en-US/e5d501af-d4ea-4c0f-97c0-dfcef0192888/dont-retire-technet?forum=tnfeedback

Powershell - Modify Share Permissions on NAS (without WMI)

$
0
0

Good morning everyone!

I have been working with Powershell (and Orchestrator) to automate management of our file shares.  The plan is to modify, remove, rename and/or create these shares and apply permissions where neededBUT the trick is that half of our shares are hosted on an EMC NAS while the other half are on Windows file servers.  Because of this, I am unable to use WMI queries to set permissions on half of our shares.

I have successfully been able to query, remove and create shares with Powershell by using the scripts below but have been unable to apply SHARE permissions. NTFS permissions are not a problem.

I have been searching and reading for what seems like days and would love an outsiders view.

Here is what I have so far:

Query a share for local folder path:

$serverName = "NAMEOFSERVER"
$shareName = "NAMEOFSHARE"
$serverObj = [ADSI]"WinNT://$serverName/lanmanserver,fileservice"
$share = $serverObj.children | where {[string]($_.path) -match $shareName}

Write-Host $share.Path

Remove a share:

$serverName = "NAMEOFSERVER"
$shareName = "NAMEOFSHARE"

$ServerObj = [ADSI] "WinNT://$serverName/lanmanserver"
$ServerObj.delete("fileshare",$shareName)
$share = [ADSI] "WinNT://$serverName/lanmanserver/$shareName"

Create a share:

$serverName = "NAMEOFSERVER"
$shareName = "NAMEOFSHARE"
$localPath = "LOCALPATH"
$description = "DESCRIPTION"

$share = [ADSI]"WinNT://$serverName/LanManServer"
$newShare = $share.Create("fileshare", $shareName)
$newShare.Put("Path", $localPath)
$newShare.Put("Description", $description)
$newShare.SetInfo()

The problem is that the 'create a share' function creates the share with no share permissions.  I would love to grant everyone (or authenticated users) full access and limit the share with NTFS permissions if possible.

Does anyone have any tips or any other ways to do this?  Remember though, no WMI! :( I know it would be much easier with WMI.

Thanks!

Joe

How can I set permission for a shared folder?

$
0
0

Hello,

I want to share a folder and set permission for the shared folder.

I've shared the folder. I used "net use z: \\server\folder" and "$shares=[WMICLASS]"WIN32_Share" $shares.Create("\\server\folder","z:",0). Both work as expected.

Now I want to set share permission for the shared folder. I've use CACLS and Get/Set-ACL. But I can only set the security permission for the folder, not sharing permission level.

Is there any cmdlet or other ways to modify the share permission?

Thanks,

Cyril

Viewing all 21975 articles
Browse latest View live


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