I am having issues with the snippet below with Powershell 4.0 on 2012 R2:
$query = 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' +
$disk.DeviceID.replace('\','\\') +
'"} WHERE AssocClass=Win32_DiskDriveToDiskPartition'
On my Windows 7 laptop running Powershell 2.0 this works fine both in the Powershell cli and in a .ps1 script. In Powershell 4.0 if I run it in the cli it works fine, but if I run it out of a .ps1 script I get:
You cannot call a method on a null-valued expression.
At C:\temp\perf.ps1:94 char:1
+ $part_query = 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' + $disk.DeviceID.rep ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: ( [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : InvokeMethodOnNull
After some debug I think the issue is with .replace('\\','\\\').
I have tried .replace('\\\','\\\\\\\') but I get the same error.
Full code:
$diskdrives = get-wmiobject Win32_DiskDrive | sort Index
foreach ( $disk in $diskdrives ) {
write $disk
$scsi_details = 'SCSI ' + $disk.SCSIBus + ':' +
$disk.SCSILogicalUnit + ':' +
$disk.SCSIPort + ':' +
$disk.SCSITargetID
#$part_query = 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' + $disk.DeviceID.replace('\','\\') + '"} WHERE AssocClass=Win32_DiskDriveToDiskPartition'
$part_query = 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' + $disk.DeviceID.replace('\\','\\\') + '"} WHERE AssocClass=Win32_DiskDriveToDiskPartition'
$partitions = #( get-wmiobject -query $part_query |
sort StartingOffset )
foreach ($partition in $partitions) {
$vol_query = 'ASSOCIATORS OF {Win32_DiskPartition.DeviceID="' +
$partition.DeviceID +
'"} WHERE AssocClass=Win32_LogicalDiskToPartition'
$volumes = #(get-wmiobject -query $vol_query)
foreach ( $volume in $volumes) {
$allDiskInfo += $($volume.name + ' ' +
$volume.FileSystem + ' ' + $disk.Index + ' '
) | Out-String -stream
} # end foreach vol
} # end foreach part
} # end foreach disk
When I declared $disks I made it [string]. What I think happened is that Powershell 2.0 coerced it back to the system object but Powershell 4.0 must have stronger typing rules and was not coercing it from what I declared it as. Once I took [string] out of the declaration, it works on 4.0.
Thanks for the responses!!
Related
Hi I am trying to run a script to get information from all the datastores.
The code script I am running is giving an error:
At C:\Users\Administrator\Desktop\Scripts\test.ps1:125 char:2
+ $allstoreinfo += $storeinfo
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
The script is a simple for loop:
$datastores = Get-Datastore
$allstoreinfo = #()
foreach($store in $datastores){
$storeinfo = "" | Select Name, FileSystem, Type, CapacityGB, FreeSpaceGB
$datastoreview = get-datastore -Name $store.Name | Get-View | select -ExpandProperty summary
$CapacityGB = [math]::round($datastoreview.Capacity/1GB,2)
$FreeSpaceGB = [math]::round($datastoreview.FreeSpace/1GB,2)
$ProvisionedGB = [math]::round(($datastoreview.Capacity - $datastoreview.FreeSpace + $datastoreview.Uncommitted)/1GB,2)
$storeinfo.Name = $store.Name
$storeinfo.FileSystem = $store.FilesystemVersion
$storeinfo.Type = $store.Type
$storeinfo.CapacityGB = $CapacityGB
$storeinfo.FreeSpaceGB = $FreeSpaceGB
$allstoreinfo += $storeinfo
}
Write-Host "---------------------------------"
$allstoreinfo | Select Name, FileSystem, Type, CapacityGB, FreeSpaceGB
Write-Host "---------------------------------"
I am trying to add 100 user accounts with PowerShell in my domain system in Windows. I get an error message called "You cannot call a method on a null-valued expression" when running the script for import.
Error Message:
You cannot call a method on a null-valued expression.
At C:\Users\Administrator\Downloads\user-import.ps1:37 char:9
+ $brukernavn = ($fornavn.Substring(0,3) + $etternavn.Substring ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull*
The PowerShell Script:
Import-Module ActiveDirectory
$csvpath = $PSScriptRoot + "\produksjonsbrukereImport.csv"
if (Test-Path $csvpath) {
#$csvpath = "C:\script\produksjonsbrukereImport.csv"
$csv = Import-Csv -Delimiter "," -Path $csvpath -Encoding UTF7
$OUBasePath = ",OU=Produksjon,OU=OpMeis,DC=OpMeis,DC=local"
$logpath = "$PSScriptRoot\import-brukere-loggfil.txt"
}
foreach ($line in $csv) {
$fornavn = $line.fornavn
$etternavn = $line.etternavn
$navn = ($fornavn + " " + $etternavn)
$beskrivelse = $line.beskrivelse
$passord = $line.Passord
$avdeling = $line.avdeling
$brukernavn = ($fornavn.Substring(0,3) + $etternavn.Substring(0,3)).ToLower()
$brukernavn = $brukernavn -replace "æ", "a"
$brukernavn = $brukernavn -replace "å", "a"
$brukernavn = $brukernavn -replace "ø", "o"
$principal = $brukernavn + "#OpMeis.local"
$profPath = ($profBasePath + $brukernavn)
$profPathTrue = $profPath + ".V2"
$OU = ("OU=" + $avdeling + $OUBasePath)
}
I get this error when running this script:
Exception calling "Matches" with "1" argument(s): "Value cannot be
null. Parameter name: input" At V:\compiler\shitter2.ps1:3 char:1
+ $tables = $regex.matches((GC v:\compiler\test.txt -raw)).groups.value
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
Here is the script code:
$Path = 'V:\compiler\po.htm'
[regex]$regex = "(?s)<TABLE ID=.*?</TABLE>"
$tables = $regex.matches((GC v:\compiler\test.txt -raw)).groups.value
ForEach($String in $tables){
$table = $string.split("`n")
$CurTable = #()
$CurTableName = ([regex]'TABLE ID="
([^"]*)"').matches($table[0]).groups[1].value
$CurTable += ($table[1] -replace "</B></TH><TH><B>",",") -replace "</?
(TR|TH|B)>"
$CurTable += $table[2..($table.count-2)]|ForEach{$_ -replace "</TD>
<TD>","," -replace "</?T(D|R)>"}
$CurTable | convertfrom-csv | export-csv "$CurTableName.csv" -notype
}
You probably forgot the access the entry using [1]:
$tables = $regex.matches((GC v:\compiler\test.txt -raw)).groups[1].value
I have a problem with WMI in a machine with a Windows 8 Home Edition. I need to catch the CPU usage and the ProcessID by process. I've tried so many ways:
ShellExecute in Delphi
A *.bat with the code
A *.vbs
A *.vbs executed by a *.bat
A *.ps1
A *.ps1 executed by a *.bat
(Maybe some of these ways can be really stupid, but I've tried anyway)
In the User-Click it works perfectally, but by a standalone applicantion it doesn't work.
I have opened the Security on WMIMGMT.msi of some folders and the execution policy (in PowerShell) now is UNRESTRICTED.
This is the code on the *.ps1 file:
$ErrorActionPreference = "SilentlyContinue"
Stop-Transcript | Out-Null
$ErrorActionPreference = "Continue"
$perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
foreach ($p in $peflist) {
"" + $p.IDProcess + ";" + $p.PercentProcessTime
}
This is the code on *.bat
powershell -ExcetutionPolicy Unrestricted -File "C:\Somefolder\PP.ps1" > C:\SomeFolder\output.txt
All I got is this output:
get-wmiobject : Invalid query "select * from Win32_Win32_PerfFormattedData_PerfProc_Process"
In C:\Somefolder\PP.ps1:4 character: 14
+ $perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErroID : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Edit1: The code copied as asked:
*.ps1:
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
$perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
foreach ($p in $perflist) {
"" + $p.IDProcess + ";" + $p.PercentProcessorTime
}
*.bat
powershell -executionPolicy unrestricted -file "C:\MonitorPerformance\test.ps1" > C:\MonitorPerformance\output1.txt
Output: (Consulta inválida = Invalid Query; No = in; caractere = character)
get-wmiobject : Consulta inv lida "select * from Win32_PerfFormattedData_PerfProc_Process"
No C:\MonitorPerformance\test.ps1:4 caractere:14
+ $perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
replace this:
$perflist = (get-wmiobject Win32_Win32_PerfFormattedData_PerfProc_Process)
with this:
$perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
Windows 8 does not performs WMI actions perfectly when you use x32 applications, I made a dummy x64 application who executes the *.bat and it finally works. Thanks for all the help.
The following PowerShell script runs an ftp command but returns an error as it cannot get find the absolute source path (which includes white space and does take the complete path as "File One” and “Destination One".
Output:
/usr/bin/lftp -c \"mirror --only-missing --verbose sftp://jason#10.1.1.1:/e:/Files/File One e:/Files/Destination One/File One\"
Access failed: No such file (e:/Files/File)
The values of each variables are hardcoded and cannot be changed for a reason. In that case, what are the changes required in the $ftppath or $ftpcmd to include these white spaces in the source and dest, so it can return the ftpcmd correctly. Could someone please help?
Script:
# these values are hardcoded and cannot be modified
$root = "/e:/Files"
$source = "File One"
$dest = "e:/Files/Destination One/File One"
$user = "jason"
$server = "10.1.1.1"
# ftp command
$ftppath = "sftp://$user" + '#' + $server + ':' + $root + '/' + $source + ' ' + $dest
$ftpcmd = '/usr/bin/lftp -c \"mirror --only-missing --verbose ' + "$ftppath"+'\"'
$ftpcmd
Invoke-Expression -command $ftpcmd
so i guess you can simply use it like thi:
# these values are hardcoded and cannot be modified
$root = "/e:/Files"
$source = "File One"
$dest = "e:/Files/Destination One/File One"
$user = "jason"
$server = "10.1.1.1"
# ftp command
$ftppath = "sftp://$user" + '#' + $server + ':' + $root + '/' + $source + ' ' + $dest
$ftpcmd = '/usr/bin/lftp -c \"mirror --only-missing --verbose ' + "$ftppath"+'\"'
$ftpcmd
Invoke-Expression -command $ftpcmd.replace(" ", "\ ")
```shell
ftp command
$ftppath = "sftp://$user" + '#' + $server + ':' + $root + '/' + $source + ' ' + $dest
```
replace by this,use quote wrap $dest
```shell
ftp command
$ftppath = "sftp://$user" + '#' + $server + ':' + $root + '/' + $source + ' ' + "${dest}"
```