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

powershell questions

$
0
0

What Windows PowerShell commands should you use to create a simple volume of the same size on disk 3 using the drive letter G:?

i created a 10Gb in disk 3

can anyone tell me what command i need to use here.

thanks


Select-Object worked the same inside and outside a % loop?!

$
0
0

I'm a bit mystified by a powershell output - it seems to have done what I meant, not what I said:

First I loaded up a list of firstname/lastname lines from a CSV:

$rlist = import-csv -path "c:\work\rlist.csv"

Then I wasn't paying attention to where I put the "select" and placed it inside a loop:

PS AD:\> $rlist | % {>>   $first = $_.first>>   $last = $_.last>>   get-aduser -filter { givenname -eq  $first -and surname -eq $last } | select samaccountname, name, enabled>> }

which somehow gave me one line of headers, and several lines of samaccountame, name, enabled as I wanted, but didn't expect.

as a sanity check, I tried the following, which gave the same output:

PS AD:\> $rlist | % {>>   $first = $_.first>>   $last = $_.last>>   get-aduser -filter { givenname -eq  $first -and surname -eq $last }>> } | select samaccountname, name, enabled

I've read other forum posts exhorting PowerShell users to make sure the select-object is outside any loops to avoid duplicate headers, so I'm mystified how the first one did NOT duplicate headers?


DISM Path failure

$
0
0

I'm trying to run a powershell script for a study course I have, however each time I get the below failure.

Import-Module : Cannot bind argument to parameter 'Name' because it is null.
At C:\Program Files\WindowsPowerShell\Modules\Lability\0.10.1\Lib\Dism.ps1:63 char:43
+         $dismModule = Import-Module -Name $dism Path -Force -Scope Gl ...
+                                          ~~~~~
    + CategoryInfo          : InvalidData: (:) [Import-Module], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ImportModul
   eCommand

 

and 

GetDscModule : DSC module\resource 'PSDesiredStateConfiguration\MSFT_WindowsOptionalFeature' not found.
At C:\Program Files\WindowsPowerShell\Modules\Lability\0.10.1\Lib\DscResource.ps1:37 char:33
+ ... ourcePath = GetDscModule -ModuleName $ModuleName -ResourceName $Resou ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,GetDscModule

What have I missed here?

Remotely enable PSRemoting

$
0
0

Hi guys,

So, the scripting world is new to me but I’m trying to get a handle on it, and hope that you can help me.

I’m working in a mixed environment; our domain contains XP clients and 2008R2 servers. All client computers have PS 2.0 installed.

I want to be able to work with PSRemoting on other client computers. Of course I have Admin privileges and I ran the commands as admin.

My problem is that I can't enable remoting through Group Policy. Our organization is really big and changing GPO will take forever because of IT policies and different approvals.

Right now we have a few jobs we really need to execute and can’t wait till GPO changes are done.

So actually, I’m looking for a way to enable remoting on remote machines in our domain. When I logon interactively to a machine and enable PSReomting, I’m able to work remotly on this machine after that. But I can't find a way to remotely enable PSReomting.

I’ve tried to enable thewinrm service through cmd, and then with PS, like this:

SC\\server start winrm

Then, from PS:

foreach ($i in 'Computer') { Enable-PSRemoting -Force }

Then I ranwinrm quickconfig, and the result was:

WinRM already is set up to receive requests on this machine

WinRM already is set up for remote management on this machine

After performing these steps, I tried remoting and got this error:

"Connecting to remote server failed with the following error message: access is denied. for more info...."

I went through every step in About_Remote_Troubleshooting but found nothing.

After googling for hours I found nothing.

Also, does anyone know if PS Active Directory module is available for XP? After some searching it looks like XP doesn’t support this module, but just to make sure.

Thank youJ

Encryption of file using Powershell using Keys

$
0
0
I want to do a PGP Encryption of a file using keys stored at one location using powershell. I know how to do using password but I want to do using keys. Could you guide me for the same.

Doc file save as PDF with Password Protection

$
0
0

Please help me, The below code is not working.

$File='docfile.doc'
$pfile='pdffile.pdf'
$Word=NEW-OBJECT –COMOBJECT WORD.APPLICATION
$Doc=$Word.Documents.Open($File)
$Doc.saveas($pfile,17,"password comment,"password")
$Doc.close()

Error message is :

At D:\test\code\pdftest.ps1:6 char:42
+ $Doc.saveas($pfile,17,"password comment","password")
+                                          ~
Missing ')' in method call.
At D:\test\code\pdftest.ps1:6 char:50
+ $Doc.saveas($pfile,17,"password comment,"password")
+                                                  ~~
The string is missing the terminator: ".
At D:\test\code\pdftest.ps1:6 char:42
+ $Doc.saveas($pfile,17,"password comment,"password")
+                                          ~~~~~~~~~~
Unexpected token 'password")
$Doc.close()
' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall



Powershell parses %SystemRoot% variable from registry key retrieved by Get-ItemProperty

$
0
0

Hi,

I try to set a path variable in an offline WinPE image. Therefor I mount the image and load the offline hive into my registry unter "HKLM\winpe". I try to retrieve the path value from "HKEY_LOCAL_MACHINE\winpe\ControlSet001\Control\Session Manager\Environment" with the following command:

(Get-ItemProperty -Path "HKLM:\winpe\ControlSet001\Control\Session Manager\Environment" -Name "Path").Pat

The value of the variable "path" in the registry is

%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\

But when I load it into a powershell variable it is

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\

which is of course not correct, because the Windows PE system is in "X:\Windows". Therefor I need the string with not parsed variables. Has somebody a idea on how to achieve this?

I need this because I want to append some stuff and need to concatenate the existing content with my content and then write it back to the registry.

Thanks, bye.


Get-Printer -Computername does not work

$
0
0

I have created a script for creating print queues on multiple print servers. I have used it a lot but now it doesn't work anymore.

It turns out that when running the script towards print server 1, get-printer -computername goes in some kind of no response and never returns a list of printers and never stops with an error.

The funny thing is that there is no problem when running get-wmiobject win32_printer -computername or if I run get-printer from enter-pssession. When I log directly on print server 1 i can also use get-printer without any problem.

Does anyone knows what the problem is?


Powershell - How to list Disk Activity Files column from Resource Monitor

$
0
0

Hello!

I'm trying to view the File column from the Disk Activity section of Resource Monitor. I've looked through several different pages of explanations on displaying Disk Activity information but nothing ever covers the File column. The different WMI classes people have used to get Disk Activity information are Win32_PerfFormattedData_PerfDisk_LogicalDisk, Win32_PerfRawData_PerfDisk_LogicalDisk, Win32_PerfFormattedData_PerfDisk_PhysicalDisk, and Win32_PerfRawData_PerfDisk_PhysicalDisk. I've explored these classes and can't find where I'd retrieve the File column info.

The different websites and blogs seem to provide all the Disk Activity information but never the File column or address why the File column information isn't provided. Is it even possible to access this information from Powershell? The screenshot below reflects the information I'm trying to gather. Thanks for the help!

So in Powershell, I imagine it'd look something like this:

Image          PID        File
-----              ---          ----
System         4           C:\ProgramData\CentraStage\...
System         4           E:\Video.Storage\d253...
svchost.ex... 4           C:\Windows\System32\...


DSC register agent forbidden

$
0
0

Hi Guys

I need some help with my DSC error when I run following command to apply DSC config.

Set-DscLocalConfigurationManager -Path LCM -Verbose

The output is this:

Registration of the Dsc Agent with the server https://dscpull.mydomain.com:8080/PSDSCPullServer.svc failed.

The underlying error is: The attempt to register Dsc Agent with AgentId '2B96C0D8-XXXX-XXXX-XXXX-XXXXXXXX'

with the server ... returned unexpected response code Forbidden.


Firewall is not blocking and url of pull server is reachable from browser.

The RegistrationKey is in the local MOF file under LCM folder.

Other Clients are okey with the same pull server and analog config.

Any ideas?

Kind Regards

Steve


Powershell Errors

$
0
0

I have been following the Microsoft guide for setting up AlwaysOnVPN and having problems running the following script. 

https://docs.microsoft.com/en-us/windows-server/remote/remote-access/vpn/always-on-vpn/deploy/vpn-deploy-client-vpn-connections#bkmk_fullscript

I have customised the custom elements at the start but i am getting the following errors any one got any ideas. 

At C:\build\MakeProfile.ps1:47 char:48
+  $ProfileNameEscaped = $ProfileName -replace ' ', '%20'
+                                                ~~~~
Unexpected token '', '' in expression or statement.
At C:\build\MakeProfile.ps1:47 char:53
+  $ProfileNameEscaped = $ProfileName -replace ' ', '%20'
+                                                     ~
You must provide a value expression following the '%' operator.
At C:\build\MakeProfile.ps1:47 char:53
+  $ProfileNameEscaped = $ProfileName -replace ' ', '%20'
+                                                     ~~~
Unexpected token '20'
 $ProfileXML = '''' in expression or statement.
At C:\build\MakeProfile.ps1:51 char:38
+  $ProfileXML = $ProfileXML -replace '<', '&lt;'
+                                      ~
The '<' operator is reserved for future use.
At C:\build\MakeProfile.ps1:51 char:43
+  $ProfileXML = $ProfileXML -replace '<', '&lt;'
+                                           ~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to 
pass it as part of a string.
At C:\build\MakeProfile.ps1:52 char:43
+  $ProfileXML = $ProfileXML -replace '>', '&gt;'
+                                           ~
Unexpected token '&' in expression or statement.
At C:\build\MakeProfile.ps1:53 char:38
+  $ProfileXML = $ProfileXML -replace '"', '&quot;'
+                                      ~~~~~~~~~~~~
Unexpected token '"', '&quot;'
 $nodeCSPURI = "' in expression or statement.
At C:\build\MakeProfile.ps1:55 char:18
+  $nodeCSPURI = "./Vendor/MSFT/VPNv2"
+                  ~
Missing property name after reference operator.
At C:\build\MakeProfile.ps1:65 char:19
+  $Message = "User SID is $SidValue."
+                   ~~~
Unexpected token 'SID' in expression or statement.
At C:\build\MakeProfile.ps1:131 char:22
+  Write-Host "$Message"
+                      ~
The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

remove computer object from AD

$
0
0

Hi,

I used below script to delete AD computer account . On my VM i have latest powershell it works fine...but my customer has PS1..it gives error

Script working on latest PS

Get-ADComputer -filter {name -like 'whmm16066'} | %{Remove-ADComputer $_.distinguishedName}

Error i get on PS1

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.
At line:1 char:15
+ Get-ADComputer <<<<  -filter {name -like 'whmm16066'} | %{Remove-ADComputer $
_.distinguishedName -Credential $admin}
    + CategoryInfo          : ObjectNotFound: (Get-ADComputer:String) [], Comm
   andNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Thanks,

Alex


Alex

Do While loop User existing

$
0
0

Hi,

I'm trying to run a script to create a new user in Active Directory by using Do While loop.
I have a var called $alias that its value is the Alias/SamAccountName of the user now i'd like to use a loop that will use the var $alias that i already have to search for an existing samaccountname then eventually to replace the var $alias with a new samaccount name that doesn't exist.

For example:

$alias = John
$filter = "Get-ADUser -Filter {SamAccountName -eq $Alias}"

Do   

{
     $filter
}

while  (Read-Host "User $alias exist type new alias" -OutVariable alias)


I know the example is totally wrong but you got the point.

Thanks in advance.



Registry Recurse - Finding and changing a d-word subkey

$
0
0

I'm trying to find a way in PowerShell where I can change the "RoamingPreferredBandType" key located in [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\

The tricky part is that we're looking through several different laptop models and this key is located in different subkeys of the hive. For example:

One laptop model the "RoamingPreferredBandType" is located in 

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\0001]

whereas another is located in 

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\0002]

I'm looking for a way to recurse through this subset of keys regardless of where it is located to change the "RoamingPreferredBandType" key. 

Powershell - How to list Disk Activity Files column from Resource Monitor

$
0
0

Hello!

I'm trying to view the File column from the Disk Activity section of Resource Monitor. I've looked through several different pages of explanations on displaying Disk Activity information but nothing ever covers the File column. The different WMI classes people have used to get Disk Activity information are Win32_PerfFormattedData_PerfDisk_LogicalDisk, Win32_PerfRawData_PerfDisk_LogicalDisk, Win32_PerfFormattedData_PerfDisk_PhysicalDisk, and Win32_PerfRawData_PerfDisk_PhysicalDisk. I've explored these classes and can't find where I'd retrieve the File column info.

The different websites and blogs seem to provide all the Disk Activity information but never the File column or address why the File column information isn't provided. Is it even possible to access this information from Powershell? The screenshot below reflects the information I'm trying to gather. Thanks for the help!

So in Powershell, I imagine it'd look something like this:

Image          PID        File
-----              ---          ----
System         4           C:\ProgramData\CentraStage\...
System         4           E:\Video.Storage\d253...
svchost.ex... 4           C:\Windows\System32\...



Powershell is not recognizing functions within the script

$
0
0

in Script Build.ps1 I have a Function RunFolder defined on line 132 

In ISe I can Type RunFolder and Intelisence will show me the parameters 

When I run Build.ps1 when it gets to the call on line 207 which is in a second Function RunBuild 

> RunBuild $Database $user $pass  
>>  RunFolder -ScriptPath $fp -cdb $db -user $user -pass $pass 
>>> RunScript -ScriptFile $file.fullname $cdb $user $pass 

I now get the error "RunFolder.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program."

This is a Change to the Behavior of powershell.

Is this a change in managing SCOPE and I can't call one function from another function from within the same PS1? 


Randy Pitkin CEO | Solutions Architect YDPages INC Projects@ydpages.com

Unexpected token ')' after upgrading PowerShell

$
0
0

I (foolishly) ran the Chocolatey package manger command to upgrade all my packages. Now when I try and run any node package I get the error:

At C:\Users\xxxx\AppData\Local\Yarn\bin\rimraf.ps1:5 char:13
+     *CYGWIN*) basedir=`cygpath -w "$basedir"`;;
+             ~
Unexpected token ')' in expression or statement.

<snip>

My version of powershell is

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      16299  785


Need to declare a variable into a path

$
0
0

Hi,

 I need: [Environment]::GetFolderPath('MyDocuments') into this string

 Add-Type -Path '\\My Documents\WindowsPowerShell\Modules\SharePointOnline.CSOM\0.1.0\Microsoft.SharePoint.Client.dll'

P.


How to use Power Shell to retrieve drive space?

$
0
0

Hi Guys,

I created one script to retrieve , but can't to export csv file.

The pc list is $computernames

$disk = @()
Foreach($pci in $computernames){
        IF(Test-Connection -ComputerName $pci -Quiet) {
            $rr = Get-WmiObject win32_logicaldisk -ComputerName $pci -filter "DeviceID='C:'"
            $rr |select PSComputerName, DeviceID, @{n="Size (GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="FreeSpace (GB)";e={[math]::Round($_.FreeSpace/1GB,2)}}

           }
        Else {
          $MemberObject = New-Object System.Object
          $MemberObject | Add-Member -Name PCName -Value $pci -MemberType NoteProperty
          $MemberObject | Add-Member -Name Status -Value "PC_OFFLINE" -MemberType NoteProperty
    $PC_Type += $MemberObject 
              }
        }

The PowerShell windows is show all , but I think to export csv file , the $disk.count =0 ,no data.


Can I to do?

Thanks!

How to check if multiple servers are down/inactive already?

$
0
0

Hi, Guys.

How to check if multiple servers are down/inactive already?

Thank you.

Viewing all 21975 articles
Browse latest View live


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